-
Notifications
You must be signed in to change notification settings - Fork 129
/
HttpResourceConverter.java
452 lines (373 loc) · 16.5 KB
/
HttpResourceConverter.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/**
* Copyright 2015 DuraSpace, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.fcrepo.http.commons.api.rdf;
import static com.google.common.collect.ImmutableList.copyOf;
import static com.google.common.collect.ImmutableList.of;
import static com.google.common.collect.Iterables.concat;
import static com.google.common.collect.Lists.newArrayList;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createResource;
import static org.apache.commons.lang.StringUtils.EMPTY;
import static org.apache.commons.lang.StringUtils.replaceOnce;
import static org.fcrepo.kernel.FedoraJcrTypes.FCR_METADATA;
import static org.fcrepo.kernel.FedoraJcrTypes.FCR_VERSIONS;
import static org.fcrepo.kernel.impl.identifiers.NodeResourceConverter.nodeConverter;
import static org.fcrepo.kernel.impl.services.TransactionServiceImpl.getCurrentTransactionId;
import static org.fcrepo.kernel.impl.utils.FedoraTypesUtils.getClosestExistingAncestor;
import static org.fcrepo.kernel.impl.utils.FedoraTypesUtils.isFrozenNode;
import static org.fcrepo.kernel.utils.NamespaceTools.validatePath;
import static org.modeshape.jcr.api.JcrConstants.JCR_CONTENT;
import static org.slf4j.LoggerFactory.getLogger;
import static org.springframework.web.context.ContextLoader.getCurrentWebApplicationContext;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.version.VersionHistory;
import javax.ws.rs.core.UriBuilder;
import org.fcrepo.kernel.models.NonRdfSourceDescription;
import org.fcrepo.kernel.models.FedoraResource;
import org.fcrepo.kernel.exception.IdentifierConversionException;
import org.fcrepo.kernel.exception.RepositoryRuntimeException;
import org.fcrepo.kernel.exception.TombstoneException;
import org.fcrepo.kernel.identifiers.IdentifierConverter;
import org.fcrepo.kernel.impl.TombstoneImpl;
import org.fcrepo.kernel.impl.identifiers.HashConverter;
import org.fcrepo.kernel.impl.identifiers.NamespaceConverter;
import org.glassfish.jersey.uri.UriTemplate;
import org.slf4j.Logger;
import org.springframework.context.ApplicationContext;
import com.google.common.base.Converter;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.hp.hpl.jena.rdf.model.Resource;
/**
* Convert between Jena Resources and JCR Nodes using a JAX-RS UriBuilder to mediate the
* URI translation.
*
* @author cabeer
* @since 10/5/14
*/
public class HttpResourceConverter extends IdentifierConverter<Resource,FedoraResource> {
private static final Logger LOGGER = getLogger(HttpResourceConverter.class);
protected List<Converter<String, String>> translationChain;
private final Session session;
private final UriBuilder uriBuilder;
protected Converter<String, String> forward = identity();
protected Converter<String, String> reverse = identity();
private final UriTemplate uriTemplate;
/**
* Create a new identifier converter within the given session with the given URI template
* @param session
* @param uriBuilder
*/
public HttpResourceConverter(final Session session,
final UriBuilder uriBuilder) {
this.session = session;
this.uriBuilder = uriBuilder;
this.uriTemplate = new UriTemplate(uriBuilder.toTemplate());
resetTranslationChain();
}
private UriBuilder uriBuilder() {
return UriBuilder.fromUri(uriBuilder.toTemplate());
}
@Override
protected FedoraResource doForward(final Resource resource) {
final Map<String, String> values = new HashMap<>();
final String path = asString(resource, values);
try {
if (path != null) {
final Node node = getNode(path);
final boolean metadata = values.containsKey("path")
&& values.get("path").endsWith("/" + FCR_METADATA);
final FedoraResource fedoraResource = nodeConverter.convert(node);
if (!metadata && fedoraResource instanceof NonRdfSourceDescription) {
return ((NonRdfSourceDescription)fedoraResource).getDescribedResource();
}
return fedoraResource;
}
throw new IdentifierConversionException("Asked to translate a resource " + resource
+ " that doesn't match the URI template");
} catch (final RepositoryException e) {
validatePath(session, path);
try {
if ( e instanceof PathNotFoundException ) {
final Node preexistingNode = getClosestExistingAncestor(session, path);
if (TombstoneImpl.hasMixin(preexistingNode)) {
throw new TombstoneException(new TombstoneImpl(preexistingNode));
}
}
} catch (final RepositoryException inner) {
LOGGER.debug("Error checking for parent tombstones", inner);
}
throw new RepositoryRuntimeException(e);
}
}
@Override
protected Resource doBackward(final FedoraResource resource) {
return toDomain(doBackwardPathOnly(resource));
}
@Override
public boolean inDomain(final Resource resource) {
final Map<String, String> values = new HashMap<>();
return uriTemplate.match(resource.getURI(), values) && values.containsKey("path");
}
@Override
public Resource toDomain(final String path) {
final String realPath;
if (path == null) {
realPath = "";
} else if (path.startsWith("/")) {
realPath = path.substring(1);
} else {
realPath = path;
}
final UriBuilder uri = uriBuilder();
if (realPath.contains("#")) {
final String[] split = realPath.split("#", 2);
uri.resolveTemplate("path", split[0], false);
uri.fragment(split[1]);
} else {
uri.resolveTemplate("path", realPath, false);
}
return createResource(uri.build().toString());
}
@Override
public String asString(final Resource resource) {
final Map<String, String> values = new HashMap<>();
return asString(resource, values);
}
/**
* Convert the incoming Resource to a JCR path (but don't attempt to load the node).
*
* @param resource Jena Resource to convert
* @param values a map that will receive the matching URI template variables for future use.
* @return
*/
private String asString(final Resource resource, final Map<String, String> values) {
if (uriTemplate.match(resource.getURI(), values) && values.containsKey("path")) {
String path = "/" + values.get("path");
final boolean metadata = path.endsWith("/" + FCR_METADATA);
if (metadata) {
path = replaceOnce(path, "/" + FCR_METADATA, EMPTY);
}
path = forward.convert(path);
if (path == null) {
return null;
}
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (final UnsupportedEncodingException e) {
LOGGER.debug("Unable to URL-decode path " + e + " as UTF-8", e);
}
if (path.isEmpty()) {
return "/";
}
return path;
}
return null;
}
private Node getNode(final String path) throws RepositoryException {
if (path.contains(FCR_VERSIONS)) {
final String[] split = path.split("/" + FCR_VERSIONS + "/", 2);
final String versionedPath = split[0];
final String versionAndPathIntoVersioned = split[1];
final String[] split1 = versionAndPathIntoVersioned.split("/", 2);
final String version = split1[0];
final String pathIntoVersioned;
if (split1.length > 1) {
pathIntoVersioned = split1[1];
} else {
pathIntoVersioned = "";
}
final Node node = getFrozenNodeByLabel(versionedPath, version);
if (pathIntoVersioned.isEmpty()) {
return node;
} else if (node != null) {
return node.getNode(pathIntoVersioned);
} else {
throw new PathNotFoundException("Unable to find versioned resource at " + path);
}
}
return session.getNode(path);
}
/**
* A private helper method that tries to look up frozen node for the given subject
* by a label. That label may either be one that was assigned at creation time
* (and is a version label in the JCR sense) or a system assigned identifier that
* was used for versions created without a label. The current implementation
* uses the JCR UUID for the frozen node as the system-assigned label.
*/
private Node getFrozenNodeByLabel(final String baseResourcePath, final String label) {
try {
try {
final Node frozenNode = session.getNodeByIdentifier(label);
/*
* We found a node whose identifier is the "label" for the version. Now
* we must do due dilligence to make sure it's a frozen node representing
* a version of the subject node.
*/
final Property p = frozenNode.getProperty("jcr:frozenUuid");
if (p != null) {
final Node subjectNode = session.getNode(baseResourcePath);
if (p.getString().equals(subjectNode.getIdentifier())) {
return frozenNode;
}
}
/*
* Though a node with an id of the label was found, it wasn't the
* node we were looking for, so fall through and look for a labeled
* node.
*/
} catch (final ItemNotFoundException ex) {
/*
* the label wasn't a uuid of a frozen node but
* instead possibly a version label.
*/
}
final VersionHistory hist =
session.getWorkspace().getVersionManager().getVersionHistory(baseResourcePath);
if (hist.hasVersionLabel(label)) {
LOGGER.debug("Found version for {} by label {}.", baseResourcePath, label);
return hist.getVersionByLabel(label).getFrozenNode();
}
LOGGER.warn("Unknown version {} with label or uuid {}!", baseResourcePath, label);
throw new PathNotFoundException("Unknown version " + baseResourcePath
+ " with label or uuid " + label);
} catch (final RepositoryException e) {
throw new RepositoryRuntimeException(e);
}
}
private static String getPath(final FedoraResource resource) {
if (isFrozenNode.apply(resource)) {
try {
// the versioned resource we're in
final FedoraResource versionableFrozenResource = resource.getVersionedAncestor();
// the unfrozen equivalent for the versioned resource
final FedoraResource unfrozenVersionableResource = versionableFrozenResource.getUnfrozenResource();
// the identifier for this version (by default, the UUID for the versioned resource)
final String versionIdentifier = versionableFrozenResource.getNode().getIdentifier();
// the path to this resource within the versioning tree
final String pathWithinVersionable;
if (!resource.equals(versionableFrozenResource)) {
pathWithinVersionable = getRelativePath(resource, versionableFrozenResource);
} else {
pathWithinVersionable = "";
}
// and, finally, the path we want to expose in the URI
final String path = unfrozenVersionableResource.getPath()
+ "/" + FCR_VERSIONS
+ "/" + versionIdentifier
+ pathWithinVersionable;
return path.startsWith("/") ? path : "/" + path;
} catch (final RepositoryException e) {
throw new RepositoryRuntimeException(e);
}
}
return resource.getPath();
}
private static String getRelativePath(final FedoraResource child, final FedoraResource ancestor) {
return child.getPath().substring(ancestor.getPath().length());
}
/**
* Get only the resource path to this resource, before embedding it in a full URI
* @param resource
* @return
*/
private String doBackwardPathOnly(final FedoraResource resource) {
String path = reverse.convert(getPath(resource));
if (path != null) {
if (resource instanceof NonRdfSourceDescription) {
path = path + "/" + FCR_METADATA;
}
if (path.endsWith(JCR_CONTENT)) {
path = replaceOnce(path, "/" + JCR_CONTENT, EMPTY);
}
return path;
}
throw new RuntimeException("Unable to process reverse chain for resource " + resource);
}
protected void resetTranslationChain() {
if (translationChain == null) {
translationChain = getTranslationChain();
final Converter<String,String> transactionIdentifierConverter = new TransactionIdentifierConverter(session);
@SuppressWarnings("unchecked")
final ImmutableList<Converter<String, String>> chain = copyOf(
concat(newArrayList(transactionIdentifierConverter),
translationChain));
setTranslationChain(chain);
}
}
private void setTranslationChain(final List<Converter<String, String>> chained) {
translationChain = chained;
for (final Converter<String, String> t : translationChain) {
forward = forward.andThen(t);
}
for (final Converter<String, String> t : Lists.reverse(translationChain)) {
reverse = reverse.andThen(t.reverse());
}
}
private static final List<Converter<String, String>> minimalTranslationChain = of(
new NamespaceConverter(), (Converter<String, String>) new HashConverter()
);
protected List<Converter<String,String>> getTranslationChain() {
final ApplicationContext context = getApplicationContext();
if (context != null) {
final List<Converter<String,String>> tchain =
getApplicationContext().getBean("translationChain", List.class);
return tchain;
}
return minimalTranslationChain;
}
protected ApplicationContext getApplicationContext() {
return getCurrentWebApplicationContext();
}
/**
* Translate the current transaction into the identifier
*/
class TransactionIdentifierConverter extends Converter<String, String> {
public static final String TX_PREFIX = "tx:";
private final Session session;
public TransactionIdentifierConverter(final Session session) {
this.session = session;
}
@Override
protected String doForward(final String path) {
if (path.contains(TX_PREFIX) && !path.contains(txSegment())) {
throw new RepositoryRuntimeException("Path " + path
+ " is not in current transaction " + getCurrentTransactionId(session));
}
return replaceOnce(path, txSegment(), EMPTY);
}
@Override
protected String doBackward(final String path) {
return txSegment() + path;
}
private String txSegment() {
final String txId = getCurrentTransactionId(session);
if (txId != null) {
return "/" + TX_PREFIX + txId;
}
return EMPTY;
}
}
}