]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms/src/org/argeo/cms/integration/JcrServlet.java
a1113261f3a3e7d78fb4fda2ca951508c5882d28
[lgpl/argeo-commons.git] / org.argeo.cms / src / org / argeo / cms / integration / JcrServlet.java
1 package org.argeo.cms.integration;
2
3 import java.io.IOException;
4
5 import javax.jcr.Node;
6 import javax.jcr.NodeIterator;
7 import javax.jcr.Property;
8 import javax.jcr.PropertyIterator;
9 import javax.jcr.PropertyType;
10 import javax.jcr.Repository;
11 import javax.jcr.RepositoryException;
12 import javax.jcr.Session;
13 import javax.jcr.Value;
14 import javax.jcr.nodetype.NodeType;
15 import javax.servlet.ServletException;
16 import javax.servlet.http.HttpServlet;
17 import javax.servlet.http.HttpServletRequest;
18 import javax.servlet.http.HttpServletResponse;
19
20 import org.apache.commons.io.FilenameUtils;
21 import org.apache.commons.io.IOUtils;
22 import org.apache.commons.logging.Log;
23 import org.apache.commons.logging.LogFactory;
24 import org.apache.jackrabbit.api.JackrabbitNode;
25 import org.apache.jackrabbit.api.JackrabbitValue;
26 import org.argeo.jcr.JcrUtils;
27
28 import com.fasterxml.jackson.core.JsonGenerator;
29 import com.fasterxml.jackson.databind.ObjectMapper;
30
31 /** Access a JCR repository via web services. */
32 public class JcrServlet extends HttpServlet {
33 private static final long serialVersionUID = 6536175260540484539L;
34 private final static Log log = LogFactory.getLog(JcrServlet.class);
35
36 private final static String PARAM_VERBOSE = "verbose";
37 private final static String PARAM_DEPTH = "depth";
38
39 public final static String JCR_NODES = "jcr:nodes";
40 public final static String JCR_PATH = "jcr:path";
41 public final static String JCR_NAME = "jcr:name";
42
43
44 private Repository repository;
45 private Integer maxDepth = 8;
46
47 private ObjectMapper objectMapper = new ObjectMapper();
48
49 @Override
50 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
51 if (log.isTraceEnabled())
52 log.trace("Data service: " + req.getPathInfo());
53
54 String dataWorkspace = getWorkspace(req);
55 String jcrPath = getJcrPath(req);
56
57 boolean verbose = req.getParameter(PARAM_VERBOSE) != null && !req.getParameter(PARAM_VERBOSE).equals("false");
58 int depth = 1;
59 if (req.getParameter(PARAM_DEPTH) != null) {
60 depth = Integer.parseInt(req.getParameter(PARAM_DEPTH));
61 if (depth > maxDepth)
62 throw new RuntimeException("Depth " + depth + " is higher than maximum " + maxDepth);
63 }
64
65 Session session = null;
66 try {
67 // authentication
68 session = openJcrSession(req, resp, repository, dataWorkspace);
69 if (!session.itemExists(jcrPath))
70 throw new RuntimeException("JCR node " + jcrPath + " does not exist");
71 Node node = session.getNode(jcrPath);
72 if (node.isNodeType(NodeType.NT_FILE)) {
73 resp.setContentType("application/octet-stream");
74 resp.addHeader("Content-Disposition", "attachment; filename='" + node.getName() + "'");
75 IOUtils.copy(JcrUtils.getFileAsStream(node), resp.getOutputStream());
76 resp.flushBuffer();
77 } else {
78 resp.setContentType("application/json");
79 JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(resp.getWriter());
80 jsonGenerator.writeStartObject();
81 writeNodeProperties(node, jsonGenerator, verbose);
82 writeNodeChildren(node, jsonGenerator, depth, verbose);
83 jsonGenerator.writeEndObject();
84 jsonGenerator.flush();
85 }
86 } catch (Exception e) {
87 new CmsExceptionsChain(e).writeAsJson(objectMapper, resp);
88 } finally {
89 JcrUtils.logoutQuietly(session);
90 }
91 }
92
93 @Override
94 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
95 if (log.isTraceEnabled())
96 log.trace("Data service: " + req.getPathInfo());
97
98 String dataWorkspace = getWorkspace(req);
99 String jcrPath = getJcrPath(req);
100
101 Session session = null;
102 try {
103 // authentication
104 session = openJcrSession(req, resp, repository, dataWorkspace);
105 if (!session.itemExists(jcrPath)) {
106 String parentPath = FilenameUtils.getFullPathNoEndSeparator(jcrPath);
107 String fileName = FilenameUtils.getName(jcrPath);
108 Node folderNode = JcrUtils.mkfolders(session, parentPath);
109 byte[] bytes = IOUtils.toByteArray(req.getInputStream());
110 JcrUtils.copyBytesAsFile(folderNode, fileName, bytes);
111 } else {
112 Node node = session.getNode(jcrPath);
113 if (!node.isNodeType(NodeType.NT_FILE))
114 throw new IllegalArgumentException("Node " + jcrPath + " exists but is not a file");
115 byte[] bytes = IOUtils.toByteArray(req.getInputStream());
116 JcrUtils.copyBytesAsFile(node.getParent(), node.getName(), bytes);
117 }
118 } catch (Exception e) {
119 new CmsExceptionsChain(e).writeAsJson(objectMapper, resp);
120 } finally {
121 JcrUtils.logoutQuietly(session);
122 }
123 }
124
125 protected Session openJcrSession(HttpServletRequest req, HttpServletResponse resp, Repository repository,
126 String workspace) throws RepositoryException {
127 return workspace != null ? repository.login(workspace) : repository.login();
128 }
129
130 /**
131 * To be overridden.
132 *
133 * @return the workspace to use, or <code>null</code> if default should be used.
134 */
135 protected String getWorkspace(HttpServletRequest req) {
136 return null;
137 }
138
139 protected String getJcrPath(HttpServletRequest req) {
140 return req.getPathInfo();
141 }
142
143 protected void writeNodeProperties(Node node, JsonGenerator jsonGenerator, boolean verbose)
144 throws RepositoryException, IOException {
145 String jcrPath = node.getPath();
146 jsonGenerator.writeStringField(JcrServlet.JCR_NAME, node.getName());
147 jsonGenerator.writeStringField(JcrServlet.JCR_PATH, jcrPath);
148
149 PropertyIterator pit = node.getProperties();
150 properties: while (pit.hasNext()) {
151 Property property = pit.nextProperty();
152
153 if (!verbose) {
154 if (property.getName().equals("jcr:primaryType") || property.getName().equals("jcr:mixinTypes")
155 || property.getName().equals("jcr:created") || property.getName().equals("jcr:createdBy")
156 || property.getName().equals("jcr:lastModified")
157 || property.getName().equals("jcr:lastModifiedBy")) {
158 continue properties;// skip
159 }
160 }
161
162 if (property.getType() == PropertyType.BINARY) {
163 if (!(node instanceof JackrabbitNode)) {
164 continue properties;// skip
165 }
166 }
167
168 if (!property.isMultiple()) {
169 jsonGenerator.writeFieldName(property.getName());
170 writePropertyValue(property.getType(), property.getValue(), jsonGenerator);
171 } else {
172 jsonGenerator.writeFieldName(property.getName());
173 jsonGenerator.writeStartArray();
174 Value[] values = property.getValues();
175 for (Value value : values) {
176 writePropertyValue(property.getType(), value, jsonGenerator);
177 }
178 jsonGenerator.writeEndArray();
179 }
180 }
181
182 // meta data
183 if (verbose) {
184 jsonGenerator.writeStringField("jcr:identifier", node.getIdentifier());
185 }
186 }
187
188 protected void writePropertyValue(int type, Value value, JsonGenerator jsonGenerator)
189 throws RepositoryException, IOException {
190 if (type == PropertyType.DOUBLE)
191 jsonGenerator.writeNumber(value.getDouble());
192 else if (type == PropertyType.LONG)
193 jsonGenerator.writeNumber(value.getLong());
194 else if (type == PropertyType.BINARY) {
195 if (value instanceof JackrabbitValue) {
196 String contentIdentity = ((JackrabbitValue) value).getContentIdentity();
197 jsonGenerator.writeString("SHA256:" + contentIdentity);
198 } else {
199 jsonGenerator.writeNull();
200 }
201 } else
202 jsonGenerator.writeString(value.getString());
203 }
204
205 protected void writeNodeChildren(Node node, JsonGenerator jsonGenerator, int depth, boolean verbose)
206 throws RepositoryException, IOException {
207 if (!node.hasNodes())
208 return;
209 if (depth <= 0)
210 return;
211 NodeIterator nit = node.getNodes();
212 jsonGenerator.writeFieldName(JcrServlet.JCR_NODES);
213 jsonGenerator.writeStartArray();
214 children: while (nit.hasNext()) {
215 Node child = nit.nextNode();
216
217 if (child.getName().startsWith("rep:")) {
218 continue children;// skip Jackrabbit auth metadata
219 }
220
221 jsonGenerator.writeStartObject();
222 writeNodeProperties(child, jsonGenerator, verbose);
223 writeNodeChildren(child, jsonGenerator, depth - 1, verbose);
224 jsonGenerator.writeEndObject();
225 }
226 jsonGenerator.writeEndArray();
227 }
228
229 public void setRepository(Repository repository) {
230 this.repository = repository;
231 }
232
233 public void setMaxDepth(Integer maxDepth) {
234 this.maxDepth = maxDepth;
235 }
236
237 }