Mercurial > hg > AnnotationManagerN4J
annotate src/main/java/de/mpiwg/itgroup/annotations/restlet/AnnotatorResourceImpl.java @ 90:475ab3d32630
update to Restlet 2.3.1.
author | casties |
---|---|
date | Sun, 08 Feb 2015 16:57:42 +0100 |
parents | 247cbbb385de |
children | cf44d9e1a4a7 |
rev | line source |
---|---|
3 | 1 package de.mpiwg.itgroup.annotations.restlet; |
2 | |
70 | 3 /* |
4 * #%L | |
5 * AnnotationManager | |
6 * %% | |
7 * Copyright (C) 2012 - 2014 MPIWG Berlin | |
8 * %% | |
9 * This program is free software: you can redistribute it and/or modify | |
10 * it under the terms of the GNU Lesser General Public License as | |
11 * published by the Free Software Foundation, either version 3 of the | |
12 * License, or (at your option) any later version. | |
13 * | |
14 * This program is distributed in the hope that it will be useful, | |
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of | |
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
17 * GNU General Lesser Public License for more details. | |
18 * | |
19 * You should have received a copy of the GNU General Lesser Public | |
20 * License along with this program. If not, see | |
21 * <http://www.gnu.org/licenses/lgpl-3.0.html>. | |
22 * #L% | |
23 */ | |
24 | |
3 | 25 import java.io.UnsupportedEncodingException; |
5 | 26 import java.text.SimpleDateFormat; |
3 | 27 import java.util.ArrayList; |
5 | 28 import java.util.Calendar; |
16 | 29 import java.util.HashSet; |
3 | 30 import java.util.List; |
16 | 31 import java.util.Set; |
75 | 32 import java.util.logging.Logger; |
3 | 33 import java.util.regex.Matcher; |
34 import java.util.regex.Pattern; | |
35 | |
36 import net.oauth.jsontoken.Checker; | |
37 import net.oauth.jsontoken.JsonToken; | |
38 import net.oauth.jsontoken.JsonTokenParser; | |
39 import net.oauth.jsontoken.SystemClock; | |
40 import net.oauth.jsontoken.crypto.HmacSHA256Verifier; | |
41 import net.oauth.jsontoken.crypto.Verifier; | |
42 | |
43 import org.apache.commons.codec.binary.Base64; | |
44 import org.json.JSONArray; | |
45 import org.json.JSONException; | |
46 import org.json.JSONObject; | |
47 import org.restlet.data.Status; | |
90 | 48 import org.restlet.data.Header; |
3 | 49 import org.restlet.representation.Representation; |
50 import org.restlet.resource.Options; | |
51 import org.restlet.resource.ServerResource; | |
72
4c2cea836bc0
restlet 2.1 works now. (it's the start() method, stupid!)
casties
parents:
70
diff
changeset
|
52 import org.restlet.util.Series; |
3 | 53 |
88 | 54 import com.google.gson.JsonArray; |
55 import com.google.gson.JsonElement; | |
56 import com.google.gson.JsonObject; | |
57 | |
9 | 58 import de.mpiwg.itgroup.annotations.Actor; |
4 | 59 import de.mpiwg.itgroup.annotations.Annotation; |
60 import de.mpiwg.itgroup.annotations.Annotation.FragmentTypes; | |
10 | 61 import de.mpiwg.itgroup.annotations.Group; |
62 import de.mpiwg.itgroup.annotations.Person; | |
48
0e00bf8e27fb
targets and resources of Annotation object are objects now.
casties
parents:
40
diff
changeset
|
63 import de.mpiwg.itgroup.annotations.Resource; |
0e00bf8e27fb
targets and resources of Annotation object are objects now.
casties
parents:
40
diff
changeset
|
64 import de.mpiwg.itgroup.annotations.Target; |
4 | 65 import de.mpiwg.itgroup.annotations.neo4j.AnnotationStore; |
3 | 66 |
67 /** | |
68 * Base class for Annotator resource classes. | |
69 * | |
70 * @author dwinter, casties | |
71 * | |
72 */ | |
73 public abstract class AnnotatorResourceImpl extends ServerResource { | |
74 | |
89 | 75 protected static Logger logger = Logger.getLogger(AnnotatorResourceImpl.class.getCanonicalName()); |
4 | 76 |
77 private AnnotationStore store; | |
3 | 78 |
79 protected String getAllowedMethodsForHeader() { | |
80 return "OPTIONS,GET,POST"; | |
81 } | |
82 | |
4 | 83 protected AnnotationStore getAnnotationStore() { |
84 if (store == null) { | |
19 | 85 store = ((BaseRestlet) getApplication()).getAnnotationStore(); |
4 | 86 } |
87 return store; | |
88 } | |
89 | |
3 | 90 public String encodeJsonId(String id) { |
64 | 91 if (id == null) |
92 return null; | |
3 | 93 try { |
94 return Base64.encodeBase64URLSafeString(id.getBytes("UTF-8")); | |
95 } catch (UnsupportedEncodingException e) { | |
96 return null; | |
97 } | |
98 } | |
99 | |
100 public String decodeJsonId(String id) { | |
64 | 101 if (id == null) |
102 return null; | |
3 | 103 try { |
104 return new String(Base64.decodeBase64(id), "UTF-8"); | |
105 } catch (UnsupportedEncodingException e) { | |
106 return null; | |
107 } | |
108 } | |
109 | |
110 /** | |
111 * Handle options request to allow CORS for AJAX. | |
112 * | |
113 * @param entity | |
114 */ | |
115 @Options | |
116 public void doOptions(Representation entity) { | |
75 | 117 logger.fine("AnnotatorResourceImpl doOptions!"); |
3 | 118 setCorsHeaders(); |
119 } | |
120 | |
121 /** | |
122 * set headers to allow CORS for AJAX. | |
123 */ | |
124 protected void setCorsHeaders() { | |
90 | 125 Series<Header> responseHeaders = (Series<Header>) getResponse().getHeaders(); |
3 | 126 if (responseHeaders == null) { |
72
4c2cea836bc0
restlet 2.1 works now. (it's the start() method, stupid!)
casties
parents:
70
diff
changeset
|
127 responseHeaders = new Series<Header>(Header.class); |
3 | 128 getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders); |
129 } | |
130 responseHeaders.add("Access-Control-Allow-Methods", getAllowedMethodsForHeader()); | |
131 // echo back Origin and Request-Headers | |
72
4c2cea836bc0
restlet 2.1 works now. (it's the start() method, stupid!)
casties
parents:
70
diff
changeset
|
132 @SuppressWarnings("unchecked") |
4c2cea836bc0
restlet 2.1 works now. (it's the start() method, stupid!)
casties
parents:
70
diff
changeset
|
133 Series<Header> requestHeaders = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers"); |
3 | 134 String origin = requestHeaders.getFirstValue("Origin", true); |
135 if (origin == null) { | |
136 responseHeaders.add("Access-Control-Allow-Origin", "*"); | |
137 } else { | |
138 responseHeaders.add("Access-Control-Allow-Origin", origin); | |
139 } | |
140 String allowHeaders = requestHeaders.getFirstValue("Access-Control-Request-Headers", true); | |
141 if (allowHeaders != null) { | |
142 responseHeaders.add("Access-Control-Allow-Headers", allowHeaders); | |
143 } | |
144 responseHeaders.add("Access-Control-Allow-Credentials", "true"); | |
145 responseHeaders.add("Access-Control-Max-Age", "60"); | |
146 } | |
147 | |
148 /** | |
149 * returns if authentication information from headers is valid. | |
150 * | |
151 * @param entity | |
152 * @return | |
153 */ | |
154 public boolean isAuthenticated(Representation entity) { | |
88 | 155 return (getUserFromAuthToken(entity) != null); |
3 | 156 } |
157 | |
158 /** | |
57
4efb21cf0ce0
new non-authorized mode without tokens. enabled by default. configured with annotationmanager.authorization=false property.
casties
parents:
52
diff
changeset
|
159 * Checks Annotator Auth plugin authentication information from headers. |
61 | 160 * Returns userId if successful. Returns "anonymous" in non-authorization |
161 * mode. | |
3 | 162 * |
163 * @param entity | |
86 | 164 * @return user-id |
3 | 165 */ |
88 | 166 public Person getUserFromAuthToken(Representation entity) { |
72
4c2cea836bc0
restlet 2.1 works now. (it's the start() method, stupid!)
casties
parents:
70
diff
changeset
|
167 @SuppressWarnings("unchecked") |
4c2cea836bc0
restlet 2.1 works now. (it's the start() method, stupid!)
casties
parents:
70
diff
changeset
|
168 Series<Header> requestHeaders = (Series<Header>) getRequest().getAttributes().get("org.restlet.http.headers"); |
3 | 169 String authToken = requestHeaders.getFirstValue("x-annotator-auth-token", true); |
57
4efb21cf0ce0
new non-authorized mode without tokens. enabled by default. configured with annotationmanager.authorization=false property.
casties
parents:
52
diff
changeset
|
170 if (authToken == null) { |
4efb21cf0ce0
new non-authorized mode without tokens. enabled by default. configured with annotationmanager.authorization=false property.
casties
parents:
52
diff
changeset
|
171 if (!((BaseRestlet) getApplication()).isAuthorizationMode()) { |
89 | 172 // no token, no-auth mode -> anonymous |
88 | 173 return Person.getAnonymous(); |
57
4efb21cf0ce0
new non-authorized mode without tokens. enabled by default. configured with annotationmanager.authorization=false property.
casties
parents:
52
diff
changeset
|
174 } |
89 | 175 // no token, auth mode -> null |
57
4efb21cf0ce0
new non-authorized mode without tokens. enabled by default. configured with annotationmanager.authorization=false property.
casties
parents:
52
diff
changeset
|
176 return null; |
4efb21cf0ce0
new non-authorized mode without tokens. enabled by default. configured with annotationmanager.authorization=false property.
casties
parents:
52
diff
changeset
|
177 } |
88 | 178 try { |
179 // decode token first to get consumer key | |
180 JsonToken token = new JsonTokenParser(null, null).deserialize(authToken); | |
181 String consumerKey = token.getParamAsPrimitive("consumerKey").getAsString(); | |
182 // get stored consumer secret for key | |
183 BaseRestlet restServer = (BaseRestlet) getApplication(); | |
184 String consumerSecret = restServer.getConsumerSecret(consumerKey); | |
185 logger.fine("requested consumer key=" + consumerKey + " secret=" + consumerSecret); | |
186 if (consumerSecret == null) { | |
187 logger.warning("Error: unknown consumer key: "+consumerKey); | |
188 return null; | |
189 } | |
190 // logger.fine(String.format("token=%s tokenString=%s signatureAlgorithm=%s",token,token.getTokenString(),token.getSignatureAlgorithm())); | |
3 | 191 List<Verifier> verifiers = new ArrayList<Verifier>(); |
192 // we only do HS256 yet | |
193 verifiers.add(new HmacSHA256Verifier(consumerSecret.getBytes("UTF-8"))); | |
194 // verify token signature(should really be static...) | |
195 new JsonTokenParser(new SystemClock(), null, (Checker[]) null).verify(token, verifiers); | |
88 | 196 // create Person |
197 JsonObject payload = token.getPayloadAsJsonObject(); | |
198 // userId is mandatory | |
199 String userId = payload.get("userId").getAsString(); | |
89 | 200 Person user = new Person(userId); |
88 | 201 // displayName is optional |
202 if (payload.has("displayName")) { | |
203 user.name = payload.get("displayName").getAsString(); | |
204 } | |
205 // memberOf groups is optional | |
206 if (payload.has("memberOf")) { | |
207 Set<String> groups = new HashSet<String>(); | |
208 JsonArray jgroups = payload.get("memberOf").getAsJsonArray(); | |
209 for (JsonElement jgroup : jgroups) { | |
210 groups.add(jgroup.getAsString()); | |
211 } | |
212 user.groups = groups; | |
213 } | |
89 | 214 logger.fine("auth OK! user=" + user); |
215 return user; | |
88 | 216 } catch (Exception e) { |
217 logger.warning("Error checking auth token: "+e.toString()); | |
3 | 218 } |
89 | 219 return null; |
3 | 220 } |
221 | |
222 /** | |
223 * creates Annotator-JSON from an Annotation object. | |
224 * | |
88 | 225 * @param annot annotation object |
61 | 226 * @param forAnonymous |
88 | 227 * @return Annotator-JSON |
3 | 228 */ |
14
629e15b345aa
permissions mostly work. need more server-side checking.
casties
parents:
10
diff
changeset
|
229 public JSONObject createAnnotatorJson(Annotation annot, boolean forAnonymous) { |
5 | 230 // return user as a JSON object (otherwise just as string) |
3 | 231 boolean makeUserObject = true; |
232 JSONObject jo = new JSONObject(); | |
233 try { | |
4 | 234 jo.put("text", annot.getBodyText()); |
235 jo.put("uri", annot.getTargetBaseUri()); | |
40
03e0f7574224
saving and loading resource targets should work now (no searching yet)
casties
parents:
22
diff
changeset
|
236 if (annot.getResourceUri() != null) { |
03e0f7574224
saving and loading resource targets should work now (no searching yet)
casties
parents:
22
diff
changeset
|
237 jo.put("resource", annot.getResourceUri()); |
03e0f7574224
saving and loading resource targets should work now (no searching yet)
casties
parents:
22
diff
changeset
|
238 } |
76 | 239 if (annot.getQuote() != null) { |
240 jo.put("quote", annot.getQuote()); | |
241 } | |
3 | 242 |
16 | 243 /* |
244 * user | |
245 */ | |
64 | 246 Actor creator = annot.getCreator(); |
247 if (creator != null) { | |
248 if (makeUserObject) { | |
249 // create user object | |
250 JSONObject userObject = new JSONObject(); | |
251 // save creator as uri | |
252 userObject.put("uri", creator.getUri()); | |
253 // make short user id | |
254 String userId = creator.getIdString(); | |
255 // set as id | |
256 userObject.put("id", userId); | |
257 // get full name | |
258 String userName = creator.getName(); | |
259 if (userName == null) { | |
260 BaseRestlet restServer = (BaseRestlet) getApplication(); | |
86 | 261 userName = restServer.getFullNameForId(userId); |
64 | 262 } |
263 userObject.put("name", userName); | |
264 // save user object | |
265 jo.put("user", userObject); | |
266 } else { | |
267 // save user as string | |
268 jo.put("user", annot.getCreatorUri()); | |
5 | 269 } |
3 | 270 } |
271 | |
16 | 272 /* |
273 * ranges | |
274 */ | |
4 | 275 if (annot.getTargetFragment() != null) { |
3 | 276 // we only look at the first xpointer |
4 | 277 List<String> fragments = new ArrayList<String>(); |
278 fragments.add(annot.getTargetFragment()); | |
279 FragmentTypes xt = annot.getFragmentType(); | |
280 if (xt == FragmentTypes.XPOINTER) { | |
281 jo.put("ranges", transformToRanges(fragments)); | |
282 } else if (xt == FragmentTypes.AREA) { | |
61 | 283 jo.put("shapes", transformToShapes(fragments)); |
84 | 284 } else if (xt == FragmentTypes.WKT) { |
285 jo.put("shapes", transformToShapes(fragments)); | |
3 | 286 } |
287 } | |
61 | 288 |
16 | 289 /* |
290 * permissions | |
291 */ | |
10 | 292 JSONObject perms = new JSONObject(); |
293 jo.put("permissions", perms); | |
294 // admin | |
295 JSONArray adminPerms = new JSONArray(); | |
296 perms.put("admin", adminPerms); | |
297 Actor adminPerm = annot.getAdminPermission(); | |
298 if (adminPerm != null) { | |
299 adminPerms.put(adminPerm.getIdString()); | |
14
629e15b345aa
permissions mostly work. need more server-side checking.
casties
parents:
10
diff
changeset
|
300 } else if (forAnonymous) { |
629e15b345aa
permissions mostly work. need more server-side checking.
casties
parents:
10
diff
changeset
|
301 // set something because its not allowed for anonymous |
629e15b345aa
permissions mostly work. need more server-side checking.
casties
parents:
10
diff
changeset
|
302 adminPerms.put("not-you"); |
10 | 303 } |
304 // delete | |
305 JSONArray deletePerms = new JSONArray(); | |
306 perms.put("delete", deletePerms); | |
307 Actor deletePerm = annot.getDeletePermission(); | |
308 if (deletePerm != null) { | |
309 deletePerms.put(deletePerm.getIdString()); | |
14
629e15b345aa
permissions mostly work. need more server-side checking.
casties
parents:
10
diff
changeset
|
310 } else if (forAnonymous) { |
629e15b345aa
permissions mostly work. need more server-side checking.
casties
parents:
10
diff
changeset
|
311 // set something because its not allowed for anonymous |
629e15b345aa
permissions mostly work. need more server-side checking.
casties
parents:
10
diff
changeset
|
312 deletePerms.put("not-you"); |
10 | 313 } |
314 // update | |
315 JSONArray updatePerms = new JSONArray(); | |
316 perms.put("update", updatePerms); | |
317 Actor updatePerm = annot.getUpdatePermission(); | |
318 if (updatePerm != null) { | |
319 updatePerms.put(updatePerm.getIdString()); | |
14
629e15b345aa
permissions mostly work. need more server-side checking.
casties
parents:
10
diff
changeset
|
320 } else if (forAnonymous) { |
629e15b345aa
permissions mostly work. need more server-side checking.
casties
parents:
10
diff
changeset
|
321 // set something because its not allowed for anonymous |
629e15b345aa
permissions mostly work. need more server-side checking.
casties
parents:
10
diff
changeset
|
322 updatePerms.put("not-you"); |
10 | 323 } |
324 // read | |
325 JSONArray readPerms = new JSONArray(); | |
326 perms.put("read", readPerms); | |
327 Actor readPerm = annot.getReadPermission(); | |
328 if (readPerm != null) { | |
329 readPerms.put(readPerm.getIdString()); | |
330 } | |
61 | 331 |
16 | 332 /* |
333 * tags | |
334 */ | |
61 | 335 Set<String> tagset = annot.getTags(); |
16 | 336 if (tagset != null) { |
337 JSONArray tags = new JSONArray(); | |
338 jo.put("tags", tags); | |
339 for (String tag : tagset) { | |
340 tags.put(tag); | |
341 } | |
342 } | |
61 | 343 |
16 | 344 /* |
345 * id | |
346 */ | |
3 | 347 // encode Annotation URL (=id) in base64 |
4 | 348 String annotUrl = annot.getUri(); |
3 | 349 String annotId = encodeJsonId(annotUrl); |
350 jo.put("id", annotId); | |
351 return jo; | |
352 } catch (JSONException e) { | |
75 | 353 logger.severe("Unable to create AnnotatorJSON! "+e); |
3 | 354 } |
355 return null; | |
356 } | |
357 | |
358 private JSONArray transformToRanges(List<String> xpointers) { | |
359 JSONArray ja = new JSONArray(); | |
360 Pattern rg = Pattern | |
4 | 361 .compile("xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)/range-to\\(end-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)\\)"); |
362 Pattern rg1 = Pattern.compile("xpointer\\(start-point\\(string-range\\(\"([^\"]*)\",([^,]*),1\\)\\)\\)"); | |
3 | 363 try { |
364 for (String xpointer : xpointers) { | |
10 | 365 // String decoded = URLDecoder.decode(xpointer, "utf-8"); |
5 | 366 String decoded = xpointer; |
3 | 367 Matcher m = rg.matcher(decoded); |
368 if (m.find()) { | |
61 | 369 JSONObject jo = new JSONObject(); |
370 jo.put("start", m.group(1)); | |
371 jo.put("startOffset", m.group(2)); | |
372 jo.put("end", m.group(3)); | |
373 jo.put("endOffset", m.group(4)); | |
374 ja.put(jo); | |
3 | 375 } |
376 m = rg1.matcher(xpointer); | |
377 if (m.find()) { | |
378 JSONObject jo = new JSONObject(); | |
379 jo.put("start", m.group(1)); | |
380 jo.put("startOffset", m.group(2)); | |
381 ja.put(jo); | |
382 } | |
383 } | |
384 } catch (JSONException e) { | |
75 | 385 logger.severe("Unable to transform to ranges! "+e); |
3 | 386 } |
387 return ja; | |
388 } | |
389 | |
84 | 390 private JSONArray transformToShapes(List<String> fragments) { |
3 | 391 JSONArray ja = new JSONArray(); |
84 | 392 Pattern xywhPattern = Pattern.compile("xywh=(\\w*):([\\d\\.]+),([\\d\\.]+),([\\d\\.]+),([\\d\\.]+)"); |
393 Pattern wktPattern = Pattern.compile("wkt=(\\w+)\\(+([\\d\\.\\,\\ ]+)\\)+"); | |
3 | 394 try { |
84 | 395 for (String fragment : fragments) { |
396 Matcher xywhMatch = xywhPattern.matcher(fragment); | |
397 Matcher wktMatch = wktPattern.matcher(fragment); | |
398 if (xywhMatch.find()) { | |
399 // xywh rectangle fragment | |
400 String units = xywhMatch.group(1); | |
401 float x = getFloat(xywhMatch.group(2)); | |
402 float y = getFloat(xywhMatch.group(3)); | |
403 float width = getFloat(xywhMatch.group(4)); | |
404 float height = getFloat(xywhMatch.group(5)); | |
61 | 405 JSONObject shape = new JSONObject(); |
406 JSONObject geom = new JSONObject(); | |
407 geom.put("units", units); | |
408 geom.put("x", x); | |
409 geom.put("y", y); | |
410 if (width == 0 || height == 0) { | |
411 shape.put("type", "point"); | |
412 shape.put("geometry", geom); | |
413 } else { | |
414 shape.put("type", "rectangle"); | |
415 geom.put("width", width); | |
416 geom.put("height", height); | |
417 shape.put("geometry", geom); | |
3 | 418 } |
61 | 419 ja.put(shape); |
84 | 420 } else if (wktMatch.find()) { |
421 // wkt shape fragment | |
422 String type = wktMatch.group(1); | |
423 String coordString = wktMatch.group(2); | |
424 JSONObject shape = new JSONObject(); | |
425 JSONObject geom = new JSONObject(); | |
426 shape.put("type", type.toLowerCase()); | |
427 // TODO: add units/crs to fragment? | |
428 geom.put("units", "fraction"); | |
429 JSONArray coords = new JSONArray(); | |
430 String[] coordPairs = coordString.split(", *"); | |
431 for (String coordPairString : coordPairs) { | |
432 String[] coordPair = coordPairString.split(" +"); | |
433 coords.put(new JSONArray(coordPair)); | |
434 } | |
435 geom.put("coordinates", coords); | |
436 shape.put("geometry", geom); | |
437 ja.put(shape); | |
3 | 438 } |
439 } | |
440 } catch (JSONException e) { | |
75 | 441 logger.severe("Unable to transform to shapes! "+e); |
3 | 442 } |
443 return ja; | |
444 } | |
445 | |
61 | 446 protected String parseShape(JSONObject shape) throws JSONException { |
447 String fragment = null; | |
448 String type = shape.getString("type"); | |
449 JSONObject geom = shape.getJSONObject("geometry"); | |
450 if (type.equalsIgnoreCase("point")) { | |
84 | 451 // point shape |
61 | 452 String x = geom.getString("x"); |
453 String y = geom.getString("y"); | |
454 fragment = String.format("xywh=fraction:%s,%s,0,0", x, y); | |
63
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
455 } else if (type.equalsIgnoreCase("rectangle")) { |
84 | 456 // rectangle shape |
61 | 457 String x = geom.getString("x"); |
458 String y = geom.getString("y"); | |
63
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
459 String width = geom.getString("width"); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
460 String height = geom.getString("height"); |
61 | 461 fragment = String.format("xywh=fraction:%s,%s,%s,%s", x, y, width, height); |
84 | 462 } else if (type.equalsIgnoreCase("polygon")) { |
463 // polygon shape | |
464 JSONArray coordArray = geom.getJSONArray("coordinates"); | |
465 StringBuilder coords = new StringBuilder(); | |
466 int numCoords = coordArray.length(); | |
467 for (int i = 0; i < numCoords; ++i) { | |
468 JSONArray coordPair = coordArray.getJSONArray(i); | |
469 coords.append(coordPair.getString(0)); | |
470 coords.append(" "); | |
471 coords.append(coordPair.getString(1)); | |
472 if (i < numCoords-1) { | |
473 coords.append(", "); | |
474 } | |
475 } | |
476 // TODO: add units/crs to wkt | |
85 | 477 // assume polygon with outer ring |
84 | 478 fragment = String.format("wkt=POLYGON((%s))", coords); |
85 | 479 } else if (type.equalsIgnoreCase("linestring")) { |
480 // linestring (polyline) shape | |
481 JSONArray coordArray = geom.getJSONArray("coordinates"); | |
482 StringBuilder coords = new StringBuilder(); | |
483 int numCoords = coordArray.length(); | |
484 for (int i = 0; i < numCoords; ++i) { | |
485 JSONArray coordPair = coordArray.getJSONArray(i); | |
486 coords.append(coordPair.getString(0)); | |
487 coords.append(" "); | |
488 coords.append(coordPair.getString(1)); | |
489 if (i < numCoords-1) { | |
490 coords.append(", "); | |
491 } | |
492 } | |
493 // TODO: add units/crs to wkt | |
494 fragment = String.format("wkt=LINESTRING(%s)", coords); | |
61 | 495 } else { |
75 | 496 logger.severe("Unable to parse this shape: " + shape); |
61 | 497 } |
498 return fragment; | |
499 } | |
500 | |
5 | 501 protected String parseArea(JSONObject area) throws JSONException { |
4 | 502 String x = area.getString("x"); |
503 String y = area.getString("y"); | |
504 String width = "0"; | |
505 String height = "0"; | |
506 if (area.has("width")) { | |
507 width = area.getString("width"); | |
508 height = area.getString("height"); | |
509 } | |
5 | 510 String fragment = String.format("xywh=fraction:%s,%s,%s,%s", x, y, width, height); |
4 | 511 return fragment; |
512 } | |
513 | |
5 | 514 protected String parseRange(JSONObject range) throws JSONException { |
4 | 515 String start = range.getString("start"); |
516 String end = range.getString("end"); | |
517 String startOffset = range.getString("startOffset"); | |
518 String endOffset = range.getString("endOffset"); | |
5 | 519 String fragment = String.format( |
4 | 520 "xpointer(start-point(string-range(\"%s\",%s,1))/range-to(end-point(string-range(\"%s\",%s,1))))", start, |
5 | 521 startOffset, end, endOffset); |
4 | 522 return fragment; |
523 } | |
524 | |
3 | 525 /** |
5 | 526 * Creates an Annotation object with data from JSON. |
3 | 527 * |
4 | 528 * uses the specification from the annotator project: {@link https |
529 * ://github.com/okfn/annotator/wiki/Annotation-format} | |
3 | 530 * |
4 | 531 * The username will be transformed to an URI if not given already as URI, |
532 * if not it will set to the MPIWG namespace defined in | |
3 | 533 * de.mpiwg.itgroup.annotationManager.Constants.NS |
534 * | |
535 * @param jo | |
536 * @return | |
537 * @throws JSONException | |
4 | 538 * @throws UnsupportedEncodingException |
3 | 539 */ |
4 | 540 public Annotation createAnnotation(JSONObject jo, Representation entity) throws JSONException, UnsupportedEncodingException { |
3 | 541 return updateAnnotation(new Annotation(), jo, entity); |
542 } | |
543 | |
5 | 544 /** |
545 * Updates an Annotation object with data from JSON. | |
546 * | |
547 * uses the specification from the annotator project: {@link https | |
548 * ://github.com/okfn/annotator/wiki/Annotation-format} | |
549 * | |
550 * The username will be transformed to an URI if not given already as URI, | |
551 * if not it will set to the MPIWG namespace defined in | |
552 * de.mpiwg.itgroup.annotationManager.Constants.NS | |
553 * | |
554 * @param annot | |
555 * @param jo | |
556 * @return | |
557 * @throws JSONException | |
558 * @throws UnsupportedEncodingException | |
559 */ | |
4 | 560 public Annotation updateAnnotation(Annotation annot, JSONObject jo, Representation entity) throws JSONException, |
561 UnsupportedEncodingException { | |
16 | 562 /* |
563 * target uri | |
564 */ | |
3 | 565 if (jo.has("uri")) { |
48
0e00bf8e27fb
targets and resources of Annotation object are objects now.
casties
parents:
40
diff
changeset
|
566 annot.setTarget(new Target(jo.getString("uri"))); |
3 | 567 } |
16 | 568 /* |
40
03e0f7574224
saving and loading resource targets should work now (no searching yet)
casties
parents:
22
diff
changeset
|
569 * resource uri |
03e0f7574224
saving and loading resource targets should work now (no searching yet)
casties
parents:
22
diff
changeset
|
570 */ |
03e0f7574224
saving and loading resource targets should work now (no searching yet)
casties
parents:
22
diff
changeset
|
571 if (jo.has("resource")) { |
48
0e00bf8e27fb
targets and resources of Annotation object are objects now.
casties
parents:
40
diff
changeset
|
572 annot.setResource(new Resource(jo.getString("resource"))); |
40
03e0f7574224
saving and loading resource targets should work now (no searching yet)
casties
parents:
22
diff
changeset
|
573 } |
03e0f7574224
saving and loading resource targets should work now (no searching yet)
casties
parents:
22
diff
changeset
|
574 /* |
16 | 575 * annotation text |
576 */ | |
3 | 577 if (jo.has("text")) { |
4 | 578 annot.setBodyText(jo.getString("text")); |
3 | 579 } |
16 | 580 /* |
76 | 581 * annotation quote |
582 */ | |
583 if (jo.has("quote")) { | |
584 annot.setQuote(jo.getString("quote")); | |
585 } | |
586 /* | |
16 | 587 * check authentication |
588 */ | |
88 | 589 Person authUser = getUserFromAuthToken(entity); |
3 | 590 if (authUser == null) { |
4 | 591 /* |
592 * // try http auth User httpUser = getHttpAuthUser(entity); if | |
593 * (httpUser == null) { | |
594 */ | |
595 setStatus(Status.CLIENT_ERROR_FORBIDDEN); | |
596 return null; | |
597 /* | |
598 * } authUser = httpUser.getIdentifier(); | |
599 */ | |
3 | 600 } |
16 | 601 /* |
602 * get or create creator object | |
603 */ | |
9 | 604 Actor creator = annot.getCreator(); |
605 if (creator == null) { | |
10 | 606 creator = new Person(); |
9 | 607 annot.setCreator(creator); |
608 } | |
3 | 609 // username not required, if no username given authuser will be used |
610 String username = null; | |
10 | 611 String userUri = creator.getUri(); |
3 | 612 if (jo.has("user")) { |
613 if (jo.get("user") instanceof String) { | |
614 // user is just a String | |
615 username = jo.getString("user"); | |
10 | 616 creator.setId(username); |
3 | 617 // TODO: what if username and authUser are different? |
618 } else { | |
619 // user is an object | |
620 JSONObject user = jo.getJSONObject("user"); | |
621 if (user.has("id")) { | |
10 | 622 String id = user.getString("id"); |
623 creator.setId(id); | |
624 username = id; | |
3 | 625 } |
626 if (user.has("uri")) { | |
627 userUri = user.getString("uri"); | |
628 } | |
629 } | |
630 } | |
631 if (username == null) { | |
88 | 632 username = authUser.getName(); |
3 | 633 } |
5 | 634 // try to get full name |
9 | 635 if (creator.getName() == null && username != null) { |
18 | 636 BaseRestlet restServer = (BaseRestlet) getApplication(); |
86 | 637 String fullName = restServer.getFullNameForId(username); |
9 | 638 creator.setName(fullName); |
5 | 639 } |
640 // userUri should be a URI, if not it will set to the MPIWG namespace | |
3 | 641 if (userUri == null) { |
642 if (username.startsWith("http")) { | |
643 userUri = username; | |
644 } else { | |
58 | 645 userUri = BaseRestlet.PERSONS_URI_PREFIX + username; |
3 | 646 } |
647 } | |
648 // TODO: should we overwrite the creator? | |
9 | 649 if (creator.getUri() == null) { |
650 creator.setUri(userUri); | |
5 | 651 } |
16 | 652 /* |
653 * creation date | |
654 */ | |
5 | 655 if (annot.getCreated() == null) { |
656 // set creation date | |
657 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); | |
658 String ct = format.format(Calendar.getInstance().getTime()); | |
659 annot.setCreated(ct); | |
660 } | |
3 | 661 |
16 | 662 /* |
61 | 663 * create fragment from the first range/area |
16 | 664 */ |
52 | 665 try { |
666 if (jo.has("ranges")) { | |
63
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
667 JSONArray ranges = jo.getJSONArray("ranges"); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
668 if (ranges.length() > 0) { |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
669 JSONObject range = ranges.getJSONObject(0); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
670 annot.setFragmentType(FragmentTypes.XPOINTER); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
671 String fragment = parseRange(range); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
672 annot.setTargetFragment(fragment); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
673 } |
52 | 674 } |
675 } catch (JSONException e) { | |
676 // nothing to do | |
3 | 677 } |
52 | 678 try { |
61 | 679 if (jo.has("shapes")) { |
63
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
680 JSONArray shapes = jo.getJSONArray("shapes"); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
681 if (shapes.length() > 0) { |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
682 JSONObject shape = shapes.getJSONObject(0); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
683 String fragment = parseShape(shape); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
684 annot.setTargetFragment(fragment); |
84 | 685 if (fragment.startsWith("wkt=")) { |
686 annot.setFragmentType(FragmentTypes.WKT); | |
687 } else { | |
688 annot.setFragmentType(FragmentTypes.AREA); | |
689 } | |
63
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
690 } |
61 | 691 } |
692 } catch (JSONException e) { | |
693 // nothing to do | |
694 } | |
695 // deprecated areas type | |
696 try { | |
52 | 697 if (jo.has("areas")) { |
63
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
698 JSONArray areas = jo.getJSONArray("areas"); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
699 if (areas.length() > 0) { |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
700 JSONObject area = areas.getJSONObject(0); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
701 annot.setFragmentType(FragmentTypes.AREA); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
702 String fragment = parseArea(area); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
703 annot.setTargetFragment(fragment); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
704 } |
52 | 705 } |
706 } catch (JSONException e) { | |
707 // nothing to do | |
3 | 708 } |
63
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
709 // no fragment is an error |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
710 if (annot.getFragmentType() == null || annot.getTargetFragment() == null) { |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
711 throw new JSONException("Annotation has no valid target fragment!"); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
712 } |
64 | 713 |
16 | 714 /* |
715 * permissions | |
716 */ | |
10 | 717 if (jo.has("permissions")) { |
718 JSONObject permissions = jo.getJSONObject("permissions"); | |
719 if (permissions.has("admin")) { | |
720 JSONArray perms = permissions.getJSONArray("admin"); | |
721 Actor actor = getActorFromPermissions(perms); | |
722 annot.setAdminPermission(actor); | |
723 } | |
724 if (permissions.has("delete")) { | |
725 JSONArray perms = permissions.getJSONArray("delete"); | |
726 Actor actor = getActorFromPermissions(perms); | |
727 annot.setDeletePermission(actor); | |
728 } | |
729 if (permissions.has("update")) { | |
730 JSONArray perms = permissions.getJSONArray("update"); | |
731 Actor actor = getActorFromPermissions(perms); | |
732 annot.setUpdatePermission(actor); | |
733 } | |
734 if (permissions.has("read")) { | |
735 JSONArray perms = permissions.getJSONArray("read"); | |
736 Actor actor = getActorFromPermissions(perms); | |
737 annot.setReadPermission(actor); | |
738 } | |
739 } | |
740 | |
16 | 741 /* |
742 * tags | |
743 */ | |
744 if (jo.has("tags")) { | |
745 HashSet<String> tagset = new HashSet<String>(); | |
746 JSONArray tags = jo.getJSONArray("tags"); | |
747 for (int i = 0; i < tags.length(); ++i) { | |
748 tagset.add(tags.getString(i)); | |
749 } | |
750 annot.setTags(tagset); | |
751 } | |
752 | |
4 | 753 return annot; |
3 | 754 } |
755 | |
61 | 756 @SuppressWarnings("unused") |
757 // i in for loop | |
10 | 758 protected Actor getActorFromPermissions(JSONArray perms) throws JSONException { |
759 Actor actor = null; | |
760 for (int i = 0; i < perms.length(); ++i) { | |
761 String perm = perms.getString(i); | |
762 if (perm.toLowerCase().startsWith("group:")) { | |
763 String groupId = perm.substring(6); | |
764 actor = new Group(groupId); | |
765 } else { | |
766 actor = new Person(perm); | |
767 } | |
768 // we just take the first one | |
769 break; | |
770 } | |
771 return actor; | |
772 } | |
773 | |
63
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
774 public static float getFloat(String s) { |
61 | 775 try { |
776 return Float.parseFloat(s); | |
777 } catch (NumberFormatException e) { | |
778 } | |
779 return 0f; | |
780 } | |
63
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
781 |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
782 public static int getInt(String s) { |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
783 try { |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
784 return Integer.parseInt(s); |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
785 } catch (NumberFormatException e) { |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
786 } |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
787 return 0; |
9f8c9611848a
fixed bug with new rectangle shapes. added limit, offset and sortBy parameters to annotator/ and annotator/search.
casties
parents:
61
diff
changeset
|
788 } |
3 | 789 } |