/
HttpGraphSubjects.java
254 lines (215 loc) · 9.01 KB
/
HttpGraphSubjects.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
/**
* Copyright 2013 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 com.google.common.base.Function;
import com.hp.hpl.jena.rdf.model.Resource;
import org.fcrepo.kernel.exception.RepositoryRuntimeException;
import org.fcrepo.kernel.rdf.GraphSubjects;
import org.fcrepo.kernel.services.functions.GetDefaultWorkspace;
import org.slf4j.Logger;
import static com.hp.hpl.jena.rdf.model.ResourceFactory.createResource;
import static java.util.Collections.singletonMap;
import static javax.jcr.PropertyType.PATH;
import static org.apache.commons.lang.StringUtils.EMPTY;
import static org.apache.commons.lang.StringUtils.replaceOnce;
import static org.fcrepo.jcr.FedoraJcrTypes.FCR_CONTENT;
import static org.fcrepo.kernel.services.TransactionServiceImpl.getCurrentTransactionId;
import static org.modeshape.jcr.api.JcrConstants.JCR_CONTENT;
import static org.slf4j.LoggerFactory.getLogger;
import java.net.URI;
import java.util.Map;
import javax.jcr.Node;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.ValueFormatException;
import javax.jcr.Workspace;
import javax.validation.constraints.NotNull;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
/**
* Translate JCR paths to URLs. There are a few types of translations
* that occur as part of this implementation:
* <ul>
* <li>jcr:content is replaced with fcr:content</li>
* <li>information about the transaction is added</li>
* </ul>
*
*/
public class HttpGraphSubjects implements GraphSubjects {
private static final Logger LOGGER = getLogger(HttpGraphSubjects.class);
public static final String WORKSPACE_PREFIX = "workspace:";
public static final String TX_PREFIX = "tx:";
protected final UriBuilder nodesBuilder;
private final String basePath;
private final int pathIx;
private final URI context;
private final Session session;
private final String defaultWorkspace;
private final Function<Repository, String> getDefaultWorkspace = new GetDefaultWorkspace();
/**
* Build HTTP graph subjects relative to the given JAX-RS resource, using the UriInfo provided.
*
* The session may provide additional information (e.g. workspaces) that need to be
* taken into account.
*
* @param relativeTo
* @param uris
*/
public HttpGraphSubjects(final Session session, final Class<?> relativeTo, final UriInfo uris) {
this.context = uris.getRequestUri();
this.nodesBuilder = uris.getBaseUriBuilder().path(relativeTo);
String normalizedBasePath = nodesBuilder.build("").toString();
if (!normalizedBasePath.endsWith("/")) {
normalizedBasePath = normalizedBasePath + "/";
}
this.basePath = normalizedBasePath;
this.pathIx = normalizedBasePath.length() - 1;
this.session = session;
this.defaultWorkspace = getDefaultWorkspace.apply(session.getRepository());
LOGGER.debug("Resolving graph subjects to a base URI of \"{}\"",
normalizedBasePath);
}
@Override
public Resource getGraphSubject(final String absPath)
throws RepositoryException {
final URI result =
nodesBuilder.buildFromMap(getPathMap(absPath));
LOGGER.debug("Translated path {} into RDF subject {}", absPath, result);
return createResource(result.toString());
}
@Override
public Resource getContext() {
return createResource(context.toString());
}
private static String getResourceURI(final Resource subject) {
if (!subject.isURIResource()) {
LOGGER.debug("RDF resource {} was not a URI resource: returning null.",
subject);
return null;
}
return subject.getURI();
}
@Override
public String getPathFromGraphSubject(final Resource subject) throws RepositoryException {
final String subjectUri = getResourceURI(subject);
if (subjectUri == null) {
return null;
}
return getPathFromGraphSubject(subjectUri);
}
/**
* Gets a path from the graph subject's URI. This method does the heavy
* lifting for getNodeFromGraphSubject and getPathFromGraphSubject in a way
* that's tied to a more generic URI rather than a rdf Resource.
*/
protected String getPathFromGraphSubject(@NotNull final String subjectUri) throws RepositoryException {
if (!isFedoraGraphSubject(subjectUri)) {
LOGGER.debug(
"RDF resource {} was not a URI resource with our expected basePath {}, returning null.",
subjectUri, basePath);
return null;
}
final StringBuilder pathBuilder = new StringBuilder();
final String absPath;
final String[] pathSegments =
subjectUri.substring(pathIx).split("/");
for (final String segment : pathSegments) {
if (segment.startsWith(TX_PREFIX)) {
final String tx = segment.substring(TX_PREFIX.length());
final String currentTxId = getCurrentTransactionId(session);
if (currentTxId == null || !tx.equals(currentTxId)) {
throw new RepositoryException(
"Subject is not in this transaction");
}
} else if (segment.startsWith(WORKSPACE_PREFIX)) {
final String workspace = segment.substring(WORKSPACE_PREFIX.length());
if (!session.getWorkspace().getName().equals(workspace)) {
throw new RepositoryException(
"Subject is not in this workspace");
}
} else if (segment.equals(FCR_CONTENT)) {
pathBuilder.append("/");
pathBuilder.append(JCR_CONTENT);
} else {
if (!segment.isEmpty()) {
pathBuilder.append("/");
pathBuilder.append(segment);
}
}
}
if (pathBuilder.length() == 0) {
absPath = "/";
} else {
absPath = pathBuilder.toString();
}
if (isValidJcrPath(absPath)) {
return absPath;
}
return null;
}
private boolean isValidJcrPath(final String absPath) {
try {
String pathToValidate = absPath;
final String txId = getCurrentTransactionId(session);
if (txId != null) {
final String txIdWithSlash = "/" + TX_PREFIX + txId;
/* replace the first occurrence of tx within the path */
pathToValidate = replaceOnce(absPath, txIdWithSlash, EMPTY);
LOGGER.debug("removed {} from URI {}. Path for JCR validation is now: {}",
txIdWithSlash, absPath, pathToValidate);
}
session.getValueFactory().createValue(pathToValidate, PATH);
return true;
} catch (final ValueFormatException e) {
LOGGER.trace("Unable to validate JCR path", e);
return false;
} catch (final RepositoryException e) {
throw new RepositoryRuntimeException("Unable to validate JCR path", e);
}
}
@Override
public boolean isFedoraGraphSubject(final Resource subject) {
return subject.isURIResource()
&& isFedoraGraphSubject(subject.getURI());
}
private boolean isFedoraGraphSubject(final String subjectUri) {
return subjectUri.startsWith(basePath)
&& isValidJcrPath(subjectUri.substring(pathIx));
}
protected Map<String, String> getPathMap(final Node node)
throws RepositoryException {
return getPathMap(node.getPath());
}
private Map<String, String> getPathMap(final String absPath) {
// the path param value doesn't start with a slash
String path = absPath.substring(1);
if (path.endsWith(JCR_CONTENT)) {
path = path.replace(JCR_CONTENT, FCR_CONTENT);
}
if (session != null) {
final Workspace workspace = session.getWorkspace();
final String txId = getCurrentTransactionId(session);
if (txId != null) {
path = TX_PREFIX + txId + "/" + path;
} else if (workspace != null &&
!workspace.getName().equals(defaultWorkspace)) {
path = WORKSPACE_PREFIX + workspace.getName() + "/" + path;
}
}
return singletonMap("path", path);
}
}