-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathContext.java
More file actions
1285 lines (1203 loc) · 53.5 KB
/
Copy pathContext.java
File metadata and controls
1285 lines (1203 loc) · 53.5 KB
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.github.jsonldjava.core;
import static com.github.jsonldjava.core.JsonLdUtils.compareShortestLeast;
import static com.github.jsonldjava.utils.Obj.newMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.github.jsonldjava.core.JsonLdError.Error;
import com.github.jsonldjava.utils.JsonLdUrl;
import com.github.jsonldjava.utils.Obj;
/**
* A helper class which still stores all the values in a map but gives member
* variables easily access certain keys
*
* @author tristan
*
*/
public class Context extends LinkedHashMap<String, Object> {
private static final long serialVersionUID = 2894534897574805571L;
private JsonLdOptions options;
private Map<String, Object> termDefinitions;
public Map<String, Object> inverse = null;
public Context() {
this(new JsonLdOptions());
}
public Context(JsonLdOptions opts) {
super();
init(opts);
}
public Context(Map<String, Object> map, JsonLdOptions opts) {
super(map);
checkEmptyKey(map);
init(opts);
}
public Context(Map<String, Object> map) {
super(map);
checkEmptyKey(map);
init(new JsonLdOptions());
}
public Context(Object context, JsonLdOptions opts) {
// TODO: load remote context
super(context instanceof Map ? (Map<String, Object>) context : null);
init(opts);
}
private void init(JsonLdOptions options) {
this.options = options;
if (options.getBase() != null) {
this.put(JsonLdConsts.BASE, options.getBase());
}
this.termDefinitions = newMap();
}
/**
* Value Compaction Algorithm
*
* http://json-ld.org/spec/latest/json-ld-api/#value-compaction
*
* @param activeProperty
* The Active Property
* @param value
* The value to compact
* @return The compacted value
*/
public Object compactValue(String activeProperty, Map<String, Object> value) {
// 1)
int numberMembers = value.size();
// 2)
if (value.containsKey(JsonLdConsts.INDEX)
&& JsonLdConsts.INDEX.equals(this.getContainer(activeProperty))) {
numberMembers--;
}
// 3)
if (numberMembers > 2) {
return value;
}
// 4)
final String typeMapping = getTypeMapping(activeProperty);
final String languageMapping = getLanguageMapping(activeProperty);
if (value.containsKey(JsonLdConsts.ID)) {
// 4.1)
if (numberMembers == 1 && JsonLdConsts.ID.equals(typeMapping)) {
return compactIri((String) value.get(JsonLdConsts.ID));
}
// 4.2)
if (numberMembers == 1 && JsonLdConsts.VOCAB.equals(typeMapping)) {
return compactIri((String) value.get(JsonLdConsts.ID), true);
}
// 4.3)
return value;
}
final Object valueValue = value.get(JsonLdConsts.VALUE);
// 5)
if (value.containsKey(JsonLdConsts.TYPE)
&& Obj.equals(value.get(JsonLdConsts.TYPE), typeMapping)) {
return valueValue;
}
// 6)
if (value.containsKey(JsonLdConsts.LANGUAGE)) {
// TODO: SPEC: doesn't specify to check default language as well
if (Obj.equals(value.get(JsonLdConsts.LANGUAGE), languageMapping) || Obj
.equals(value.get(JsonLdConsts.LANGUAGE), this.get(JsonLdConsts.LANGUAGE))) {
return valueValue;
}
}
// 7)
if (numberMembers == 1 && (!(valueValue instanceof String)
|| !this.containsKey(JsonLdConsts.LANGUAGE)
|| (termDefinitions.containsKey(activeProperty)
&& getTermDefinition(activeProperty).containsKey(JsonLdConsts.LANGUAGE)
&& languageMapping == null))) {
return valueValue;
}
// 8)
return value;
}
/**
* Context Processing Algorithm
*
* http://json-ld.org/spec/latest/json-ld-api/#context-processing-algorithms
*
* @param localContext
* The Local Context object.
* @param remoteContexts
* The list of Strings denoting the remote Context URLs.
* @return The parsed and merged Context.
* @throws JsonLdError
* If there is an error parsing the contexts.
*/
@SuppressWarnings("unchecked")
public Context parse(Object localContext, List<String> remoteContexts) throws JsonLdError {
return parse(localContext, remoteContexts, false);
}
/**
* Helper method used to work around logic errors related to the recursive
* nature of the JSONLD-API Context Processing Algorithm.
*
* @param localContext
* The Local Context object.
* @param remoteContexts
* The list of Strings denoting the remote Context URLs.
* @param parsingARemoteContext
* True if localContext represents a remote context that has been
* parsed and sent into this method and false otherwise. This
* must be set to know whether to propagate the @code{@base} key
* from the context to the result.
* @return The parsed and merged Context.
* @throws JsonLdError
* If there is an error parsing the contexts.
*/
// GK: Note that parsing may also depend on some options: `override protected and `propagate`
private Context parse(Object localContext, List<String> remoteContexts,
boolean parsingARemoteContext) throws JsonLdError {
if (remoteContexts == null) {
remoteContexts = new ArrayList<String>();
}
// 1. Initialize result to the result of cloning active context.
Context result = this.clone(); // TODO: clone?
// GK: note if localContext is a Map containing `@propagate` that value overrides the `propagate` option.
// 2)
if (!(localContext instanceof List)) {
final Object temp = localContext;
localContext = new ArrayList<Object>();
((List<Object>) localContext).add(temp);
}
// 3)
for (final Object context : ((List<Object>) localContext)) {
// 3.1)
if (context == null) {
// GK: Note, if active context has any protected terms, and `override protected` is not true, this should fail with 'invalid context nullification'.
// GK: Note, if `propagate` is false, the previous context should be associated with this new (null) context for potential rollback.
result = new Context(this.options);
continue;
} else if (context instanceof Context) {
result = ((Context) context).clone();
}
// 3.2)
else if (context instanceof String) {
String uri = (String) result.get(JsonLdConsts.BASE);
// GK: Note, the context needs to be resolved against the location of the file containing the reference, not the base association from the context. The spec defines a `context base` for this purpose.
uri = JsonLdUrl.resolve(uri, (String) context);
// 3.2.2
if (remoteContexts.contains(uri)) {
throw new JsonLdError(Error.RECURSIVE_CONTEXT_INCLUSION, uri);
}
remoteContexts.add(uri);
// 3.2.3: Dereference context
final RemoteDocument rd = this.options.getDocumentLoader().loadDocument(uri);
final Object remoteContext = rd.getDocument();
if (!(remoteContext instanceof Map) || !((Map<String, Object>) remoteContext)
.containsKey(JsonLdConsts.CONTEXT)) {
// If the dereferenced document has no top-level JSON object
// with an @context member
throw new JsonLdError(Error.INVALID_REMOTE_CONTEXT, context);
}
final Object tempContext = ((Map<String, Object>) remoteContext)
.get(JsonLdConsts.CONTEXT);
// 3.2.4
result = result.parse(tempContext, remoteContexts, true);
// 3.2.5
continue;
} else if (!(context instanceof Map)) {
// 3.3
throw new JsonLdError(Error.INVALID_LOCAL_CONTEXT, context);
}
// 5.5 in 1.1 (https://w3c.github.io/json-ld-api/#context-processing-algorithm)
if (((Map<String, Object>) context).containsKey(JsonLdConsts.VERSION)) {
final Object version = ((Map<String, Object>) context).get(JsonLdConsts.VERSION);
// 5.5.1
if(!version.equals(Double.valueOf(1.1))) {
throw new JsonLdError(Error.INVALID_VERSION_VALUE, context);
}
// 5.5.2
if(options.getProcessingMode().equals(JsonLdOptions.JSON_LD_1_0)) {
throw new JsonLdError(Error.PROCESSING_MODE_CONFLICT, context);
}
}
checkEmptyKey((Map<String, Object>) context);
// 3.4
if (!parsingARemoteContext
&& ((Map<String, Object>) context).containsKey(JsonLdConsts.BASE)) {
// 3.4.1
final Object value = ((Map<String, Object>) context).get(JsonLdConsts.BASE);
// 3.4.2
if (value == null) {
result.remove(JsonLdConsts.BASE);
} else if (value instanceof String) {
// 3.4.3
if (JsonLdUtils.isAbsoluteIri((String) value)) {
result.put(JsonLdConsts.BASE, value);
} else {
// 3.4.4
final String baseUri = (String) result.get(JsonLdConsts.BASE);
if (!JsonLdUtils.isAbsoluteIri(baseUri)) {
throw new JsonLdError(Error.INVALID_BASE_IRI, baseUri);
}
result.put(JsonLdConsts.BASE, JsonLdUrl.resolve(baseUri, (String) value));
}
} else {
// 3.4.5
throw new JsonLdError(JsonLdError.Error.INVALID_BASE_IRI,
"@base must be a string");
}
}
// 3.5
if (((Map<String, Object>) context).containsKey(JsonLdConsts.VOCAB)) {
final Object value = ((Map<String, Object>) context).get(JsonLdConsts.VOCAB);
if (value == null) {
result.remove(JsonLdConsts.VOCAB);
}
// jsonld 1.1: 5.8.3 in https://w3c.github.io/json-ld-api/#algorithm
else if (value instanceof String) {
if (JsonLdUtils.isBlankNode((String) value)
|| JsonLdUtils.isAbsoluteIri((String) value) || JsonLdUtils.isRelativeIri((String) value)) {
result.put(JsonLdConsts.VOCAB,
expandIri((String) value, true, true, ((Map<String, Object>) result), null));
} else {
throw new JsonLdError(Error.INVALID_VOCAB_MAPPING,
"@value must be an IRI or a blank node, but was: "+value);
}
} else {
throw new JsonLdError(Error.INVALID_VOCAB_MAPPING,
"@vocab must be a string or null");
}
}
// 3.6
if (((Map<String, Object>) context).containsKey(JsonLdConsts.LANGUAGE)) {
final Object value = ((Map<String, Object>) context).get(JsonLdConsts.LANGUAGE);
if (value == null) {
result.remove(JsonLdConsts.LANGUAGE);
} else if (value instanceof String) {
result.put(JsonLdConsts.LANGUAGE, ((String) value).toLowerCase());
} else {
throw new JsonLdError(Error.INVALID_DEFAULT_LANGUAGE, value);
}
}
// GK: There are more keys to be checked: `@import`, `@direction`, `@propagate` and `@version`.
// GK: You'll want some `processingMode` method to use when doing conditional checks; default value is `json-ld-1.1`, but can be overridden using an API option.
// 3.7
final Map<String, Boolean> defined = new LinkedHashMap<String, Boolean>();
for (final String key : ((Map<String, Object>) context).keySet()) {
// jsonld 1.1: 5.13 in https://w3c.github.io/json-ld-api/#algorithm
if (Arrays
.asList(JsonLdConsts.BASE, JsonLdConsts.DIRECTION, JsonLdConsts.IMPORT,
JsonLdConsts.LANGUAGE, JsonLdConsts.PROPAGATE,
JsonLdConsts.PROTECTED, JsonLdConsts.VERSION, JsonLdConsts.VOCAB)
.contains(key)) {
continue;
}
// TODO: passing result for active context and the value of the @protected entry from context, if any
result.createTermDefinition((Map<String, Object>) context, key, defined);
}
}
return result;
}
private void checkEmptyKey(final Map<String, Object> map) {
if (map.containsKey("")) {
// the term MUST NOT be an empty string ("")
// https://www.w3.org/TR/json-ld/#h3_terms
throw new JsonLdError(Error.INVALID_TERM_DEFINITION,
String.format("empty key for value '%s'", map.get("")));
}
}
public Context parse(Object localContext) throws JsonLdError {
return this.parse(localContext, new ArrayList<String>());
}
/**
* Create Term Definition Algorithm
*
* http://json-ld.org/spec/latest/json-ld-api/#create-term-definition
*
* @param result
* @param context
* @param key
* @param defined
* @throws JsonLdError
*/
private void createTermDefinition(Map<String, Object> context, String term,
Map<String, Boolean> defined) throws JsonLdError {
if (defined.containsKey(term)) {
if (Boolean.TRUE.equals(defined.get(term))) {
return;
}
throw new JsonLdError(Error.CYCLIC_IRI_MAPPING, term);
}
defined.put(term, false);
// GK: Note, `@type` can also contain `@protected` in addition to `@container`. If `@container` is there, its value can only be `@set` (or `['@set']`).
if (JsonLdUtils.isKeyword(term)
&& !(options.getAllowContainerSetOnType() && JsonLdConsts.TYPE.equals(term)
&& !(context.get(term)).toString().contains(JsonLdConsts.ID))) {
throw new JsonLdError(Error.KEYWORD_REDEFINITION, term);
}
// GK: Note, you'll need to retain any previous definition to make sure, if protected, that any new definition is compatible with it before ending this method.
this.termDefinitions.remove(term);
Object value = context.get(term);
if (value == null || (value instanceof Map
&& ((Map<String, Object>) value).containsKey(JsonLdConsts.ID)
&& ((Map<String, Object>) value).get(JsonLdConsts.ID) == null)) {
this.termDefinitions.put(term, null);
defined.put(term, true);
return;
}
if (value instanceof String) {
value = newMap(JsonLdConsts.ID, value);
}
if (!(value instanceof Map)) {
throw new JsonLdError(Error.INVALID_TERM_DEFINITION, value);
}
// casting the value so it doesn't have to be done below everytime
final Map<String, Object> val = (Map<String, Object>) value;
// 9) create a new term definition
final Map<String, Object> definition = newMap();
// 10)
if (val.containsKey(JsonLdConsts.TYPE)) {
if (!(val.get(JsonLdConsts.TYPE) instanceof String)) {
throw new JsonLdError(Error.INVALID_TYPE_MAPPING, val.get(JsonLdConsts.TYPE));
}
String type = (String) val.get(JsonLdConsts.TYPE);
try {
type = this.expandIri((String) val.get(JsonLdConsts.TYPE), false, true, context,
defined);
} catch (final JsonLdError error) {
if (error.getType() != Error.INVALID_IRI_MAPPING) {
throw error;
}
throw new JsonLdError(Error.INVALID_TYPE_MAPPING, type, error);
}
// jsonld 1.1: 13.3 in https://w3c.github.io/json-ld-api/#algorithm-0
if (JsonLdOptions.JSON_LD_1_0.equals(options.getProcessingMode())
&& (JsonLdConsts.NONE.equals(type) || JsonLdConsts.JSON.equals(type))) {
throw new JsonLdError(Error.INVALID_TYPE_MAPPING, type);
}
// TODO: fix check for absoluteIri (blank nodes shouldn't count, at
// least not here!)
else if (!JsonLdConsts.ID.equals(type) && !JsonLdConsts.VOCAB.equals(type)
&& !JsonLdConsts.JSON.equals(type) && !JsonLdConsts.NONE.equals(type)
&& (!JsonLdUtils.isAbsoluteIri(type) || type.startsWith(JsonLdConsts.BLANK_NODE_PREFIX))) {
throw new JsonLdError(Error.INVALID_TYPE_MAPPING, type);
}
definition.put(JsonLdConsts.TYPE, type);
}
// 11)
if (val.containsKey(JsonLdConsts.REVERSE)) {
if (val.containsKey(JsonLdConsts.ID)) {
throw new JsonLdError(Error.INVALID_REVERSE_PROPERTY, val);
}
if (!(val.get(JsonLdConsts.REVERSE) instanceof String)) {
throw new JsonLdError(Error.INVALID_IRI_MAPPING,
"Expected String for @reverse value. got "
+ (val.get(JsonLdConsts.REVERSE) == null ? "null"
: val.get(JsonLdConsts.REVERSE).getClass()));
}
final String reverse = this.expandIri((String) val.get(JsonLdConsts.REVERSE), false,
true, context, defined);
if (!JsonLdUtils.isAbsoluteIri(reverse)) {
throw new JsonLdError(Error.INVALID_IRI_MAPPING,
"Non-absolute @reverse IRI: " + reverse);
}
definition.put(JsonLdConsts.ID, reverse);
// jsonld 1.1: 14.5 in https://w3c.github.io/json-ld-api/#algorithm-0
if (val.containsKey(JsonLdConsts.CONTAINER)) {
final Object containerObject = val.get(JsonLdConsts.CONTAINER);
final String container = selectContainer(checkValidContainerEntry(containerObject));
if (container == null || JsonLdConsts.SET.equals(container)
|| JsonLdConsts.INDEX.equals(container)) {
definition.put(JsonLdConsts.CONTAINER, container);
} else {
throw new JsonLdError(Error.INVALID_REVERSE_PROPERTY,
"reverse properties only support set- and index-containers, but was: "
+ containerObject);
}
}
definition.put(JsonLdConsts.REVERSE, true);
this.termDefinitions.put(term, definition);
defined.put(term, true);
return;
}
// 12)
definition.put(JsonLdConsts.REVERSE, false);
// 13)
// GK: Note, there are some required checks to be sure that if the associated term expands to an IRI, it is compatible with `@id` and some other checks.
if (val.get(JsonLdConsts.ID) != null && !term.equals(val.get(JsonLdConsts.ID))) {
if (!(val.get(JsonLdConsts.ID) instanceof String)) {
throw new JsonLdError(Error.INVALID_IRI_MAPPING,
"expected value of @id to be a string");
}
// jsonld 1.1: 16.4 in https://w3c.github.io/json-ld-api/#algorithm-0
final String res = this.expandIri((String) val.get(JsonLdConsts.ID), false, true,
context, defined);
if (JsonLdUtils.isKeyword(res) || JsonLdUtils.isAbsoluteIri(res) || JsonLdUtils.isBlankNode(res)) {
if (JsonLdConsts.CONTEXT.equals(res)) {
throw new JsonLdError(Error.INVALID_KEYWORD_ALIAS, "cannot alias @context");
}
definition.put(JsonLdConsts.ID, res);
} else {
throw new JsonLdError(Error.INVALID_IRI_MAPPING,
"resulting IRI mapping should be a keyword, absolute IRI or blank node, but was: " + res);
}
}
// 14)
else if (term.indexOf(":") >= 0) {
final int colIndex = term.indexOf(":");
final String prefix = term.substring(0, colIndex);
final String suffix = term.substring(colIndex + 1);
if (context.containsKey(prefix)) {
this.createTermDefinition(context, prefix, defined);
}
if (termDefinitions.containsKey(prefix)) {
definition.put(JsonLdConsts.ID,
((Map<String, Object>) termDefinitions.get(prefix)).get(JsonLdConsts.ID)
+ suffix);
} else {
definition.put(JsonLdConsts.ID, term);
}
// 15)
} else if (this.containsKey(JsonLdConsts.VOCAB)) {
definition.put(JsonLdConsts.ID, this.get(JsonLdConsts.VOCAB) + term);
} else if (!JsonLdConsts.TYPE.equals(term)) {
throw new JsonLdError(Error.INVALID_IRI_MAPPING,
"relative term definition without vocab mapping");
}
// 16)
// jsonld 1.1: 21 in https://w3c.github.io/json-ld-api/#algorithm-0
// GK: Note, `@container` can take on many more values, and be an array. Best always cast to an array and check to see if the container includes any useful value. There are also some checks to make sure that the content of `@context` is consistent.
if (val.containsKey(JsonLdConsts.CONTAINER)) {
Object containerObject = val.get(JsonLdConsts.CONTAINER);
final List<?> allContainers = checkValidContainerEntry(containerObject);
if (allContainers.isEmpty()) {
throw new JsonLdError(Error.INVALID_CONTAINER_MAPPING, containerObject);
}
String container = selectContainer(allContainers);
if (container == null) {
throw new JsonLdError(Error.INVALID_CONTAINER_MAPPING,
"@container must be either @graph, @id, @index, @language, @list, @set or @type, but was: "
+ allContainers);
}
definition.put(JsonLdConsts.CONTAINER, container);
if (JsonLdConsts.TYPE.equals(term)) {
definition.put(JsonLdConsts.ID, "type");
}
}
// 17)
if (val.containsKey(JsonLdConsts.LANGUAGE) && !val.containsKey(JsonLdConsts.TYPE)) {
if (val.get(JsonLdConsts.LANGUAGE) == null
|| val.get(JsonLdConsts.LANGUAGE) instanceof String) {
final String language = (String) val.get(JsonLdConsts.LANGUAGE);
definition.put(JsonLdConsts.LANGUAGE,
language != null ? language.toLowerCase() : null);
} else {
throw new JsonLdError(Error.INVALID_LANGUAGE_MAPPING,
"@language must be a string or null");
}
}
// GK: Note, other keys to check for are `@index`, `@context` (which requires a recursive call to Context.parse to make sure it's valid), `@direction`, `@nest`, and `@prefix`.
// GK: Note, this is where to check if the previous definition exists and is protected, and we're not overriding protected, that the two definitions are essentially compatible.
// 18)
this.termDefinitions.put(term, definition);
defined.put(term, true);
}
private String selectContainer(final List<?> allContainers) {
Optional<?> supportedContainer = allContainers.stream()
.filter(c -> Arrays.asList(JsonLdConsts.LIST, JsonLdConsts.SET, JsonLdConsts.INDEX,
JsonLdConsts.LANGUAGE, JsonLdConsts.GRAPH).contains(c))
.findFirst();
return (String) supportedContainer.orElse(null);
}
// jsonld 1.1: 22.1 in https://w3c.github.io/json-ld-api/#create-term-definition
private List<?> checkValidContainerEntry(final Object containerObject) {
List<?> container = (List<?>) (containerObject instanceof List ? containerObject
: Arrays.asList(containerObject));
boolean anyOneOf = Arrays.asList(JsonLdConsts.GRAPH, JsonLdConsts.ID, JsonLdConsts.INDEX,
JsonLdConsts.LANGUAGE, JsonLdConsts.LIST, JsonLdConsts.SET, JsonLdConsts.TYPE)
.stream().anyMatch(v -> container.contains(v)) && container.size() == 1;
boolean graphWithOthers = container.contains(JsonLdConsts.GRAPH)
&& (container.contains(JsonLdConsts.ID) || container.contains(JsonLdConsts.INDEX)
|| container.contains(JsonLdConsts.SET));
boolean setWithOthers = container.contains(JsonLdConsts.SET)
&& Arrays
.asList(JsonLdConsts.INDEX, JsonLdConsts.ID, JsonLdConsts.TYPE,
JsonLdConsts.LANGUAGE)
.stream().anyMatch(v -> container.contains(v));
if (anyOneOf || graphWithOthers || setWithOthers) {
return container;
} else
return Collections.emptyList();
}
/**
* IRI Expansion Algorithm
*
* http://json-ld.org/spec/latest/json-ld-api/#iri-expansion
*
* @param value
* @param relative
* @param vocab
* @param context
* @param defined
* @return
* @throws JsonLdError
*/
String expandIri(String value, boolean relative, boolean vocab, Map<String, Object> context,
Map<String, Boolean> defined) throws JsonLdError {
// 1)
if (value == null || JsonLdUtils.isKeyword(value)) {
return value;
}
// 2)
if (context != null && context.containsKey(value)
&& !Boolean.TRUE.equals(defined.get(value))) {
this.createTermDefinition(context, value, defined);
}
// 3)
if (vocab && this.termDefinitions.containsKey(value)) {
final Map<String, Object> td = (Map<String, Object>) this.termDefinitions.get(value);
if (td != null) {
return (String) td.get(JsonLdConsts.ID);
} else {
return null;
}
}
// 4)
final int colIndex = value.indexOf(":");
if (colIndex >= 0) {
// 4.1)
final String prefix = value.substring(0, colIndex);
final String suffix = value.substring(colIndex + 1);
// 4.2)
if ("_".equals(prefix) || suffix.startsWith("//")) {
return value;
}
// 4.3)
if (context != null && context.containsKey(prefix)
&& (!defined.containsKey(prefix) || defined.get(prefix) == false)) {
this.createTermDefinition(context, prefix, defined);
}
// 4.4)
if (this.termDefinitions.containsKey(prefix)) {
return (String) ((Map<String, Object>) this.termDefinitions.get(prefix))
.get(JsonLdConsts.ID) + suffix;
}
// 4.5)
return value;
}
// 5)
if (vocab && this.containsKey(JsonLdConsts.VOCAB)) {
return this.get(JsonLdConsts.VOCAB) + value;
}
// 6)
else if (relative) {
return JsonLdUrl.resolve((String) this.get(JsonLdConsts.BASE), value);
}
// 7)
return value;
}
/**
* IRI Compaction Algorithm
*
* http://json-ld.org/spec/latest/json-ld-api/#iri-compaction
*
* Compacts an IRI or keyword into a term or prefix if it can be. If the IRI
* has an associated value it may be passed.
*
* @param iri
* the IRI to compact.
* @param value
* the value to check or null.
* @param relativeTo
* options for how to compact IRIs: vocab: true to split
* after @vocab, false not to.
* @param reverse
* true if a reverse property is being compacted, false if not.
*
* @return the compacted term, prefix, keyword alias, or the original IRI.
*/
String compactIri(String iri, Object value, boolean relativeToVocab, boolean reverse) {
// 1)
if (iri == null) {
return null;
}
// 2)
if (relativeToVocab && getInverse().containsKey(iri)) {
// GK: Sadly, term selection has become much more involved in 1.1.
// 2.1)
String defaultLanguage = (String) this.get(JsonLdConsts.LANGUAGE);
if (defaultLanguage == null) {
defaultLanguage = JsonLdConsts.NONE;
}
// 2.2)
final List<String> containers = new ArrayList<String>();
// 2.3)
String typeLanguage = JsonLdConsts.LANGUAGE;
String typeLanguageValue = JsonLdConsts.NULL;
// 2.4)
if (value instanceof Map
&& ((Map<String, Object>) value).containsKey(JsonLdConsts.INDEX)) {
containers.add(JsonLdConsts.INDEX);
}
// 2.5)
if (reverse) {
typeLanguage = JsonLdConsts.TYPE;
typeLanguageValue = JsonLdConsts.REVERSE;
containers.add(JsonLdConsts.SET);
}
// 2.6)
else if (value instanceof Map
&& ((Map<String, Object>) value).containsKey(JsonLdConsts.LIST)) {
// 2.6.1)
if (!((Map<String, Object>) value).containsKey(JsonLdConsts.INDEX)) {
containers.add(JsonLdConsts.LIST);
}
// 2.6.2)
final List<Object> list = (List<Object>) ((Map<String, Object>) value)
.get(JsonLdConsts.LIST);
// 2.6.3)
String commonLanguage = (list.size() == 0) ? defaultLanguage : null;
String commonType = null;
// 2.6.4)
for (final Object item : list) {
// 2.6.4.1)
String itemLanguage = JsonLdConsts.NONE;
String itemType = JsonLdConsts.NONE;
// 2.6.4.2)
if (JsonLdUtils.isValue(item)) {
// 2.6.4.2.1)
if (((Map<String, Object>) item).containsKey(JsonLdConsts.LANGUAGE)) {
itemLanguage = (String) ((Map<String, Object>) item)
.get(JsonLdConsts.LANGUAGE);
}
// 2.6.4.2.2)
else if (((Map<String, Object>) item).containsKey(JsonLdConsts.TYPE)) {
itemType = (String) ((Map<String, Object>) item).get(JsonLdConsts.TYPE);
}
// 2.6.4.2.3)
else {
itemLanguage = JsonLdConsts.NULL;
}
}
// 2.6.4.3)
else {
itemType = JsonLdConsts.ID;
}
// 2.6.4.4)
if (commonLanguage == null) {
commonLanguage = itemLanguage;
}
// 2.6.4.5)
else if (!commonLanguage.equals(itemLanguage) && JsonLdUtils.isValue(item)) {
commonLanguage = JsonLdConsts.NONE;
}
// 2.6.4.6)
if (commonType == null) {
commonType = itemType;
}
// 2.6.4.7)
else if (!commonType.equals(itemType)) {
commonType = JsonLdConsts.NONE;
}
// 2.6.4.8)
if (JsonLdConsts.NONE.equals(commonLanguage)
&& JsonLdConsts.NONE.equals(commonType)) {
break;
}
}
// 2.6.5)
commonLanguage = (commonLanguage != null) ? commonLanguage : JsonLdConsts.NONE;
// 2.6.6)
commonType = (commonType != null) ? commonType : JsonLdConsts.NONE;
// 2.6.7)
if (!JsonLdConsts.NONE.equals(commonType)) {
typeLanguage = JsonLdConsts.TYPE;
typeLanguageValue = commonType;
}
// 2.6.8)
else {
typeLanguageValue = commonLanguage;
}
}
// 2.7)
else {
// 2.7.1)
if (value instanceof Map
&& ((Map<String, Object>) value).containsKey(JsonLdConsts.VALUE)) {
// 2.7.1.1)
if (((Map<String, Object>) value).containsKey(JsonLdConsts.LANGUAGE)
&& !((Map<String, Object>) value).containsKey(JsonLdConsts.INDEX)) {
containers.add(JsonLdConsts.LANGUAGE);
typeLanguageValue = (String) ((Map<String, Object>) value)
.get(JsonLdConsts.LANGUAGE);
}
// 2.7.1.2)
else if (((Map<String, Object>) value).containsKey(JsonLdConsts.TYPE)) {
typeLanguage = JsonLdConsts.TYPE;
typeLanguageValue = (String) ((Map<String, Object>) value)
.get(JsonLdConsts.TYPE);
}
}
// 2.7.2)
else {
typeLanguage = JsonLdConsts.TYPE;
typeLanguageValue = JsonLdConsts.ID;
}
// 2.7.3)
containers.add(JsonLdConsts.SET);
}
// 2.8)
containers.add(JsonLdConsts.NONE);
// 2.9)
if (typeLanguageValue == null) {
typeLanguageValue = JsonLdConsts.NULL;
}
// 2.10)
final List<String> preferredValues = new ArrayList<String>();
// 2.11)
if (JsonLdConsts.REVERSE.equals(typeLanguageValue)) {
preferredValues.add(JsonLdConsts.REVERSE);
}
// 2.12)
if ((JsonLdConsts.REVERSE.equals(typeLanguageValue)
|| JsonLdConsts.ID.equals(typeLanguageValue)) && (value instanceof Map)
&& ((Map<String, Object>) value).containsKey(JsonLdConsts.ID)) {
// 2.12.1)
final String result = this.compactIri(
(String) ((Map<String, Object>) value).get(JsonLdConsts.ID), null, true,
true);
if (termDefinitions.containsKey(result)
&& ((Map<String, Object>) termDefinitions.get(result))
.containsKey(JsonLdConsts.ID)
&& ((Map<String, Object>) value).get(JsonLdConsts.ID)
.equals(((Map<String, Object>) termDefinitions.get(result))
.get(JsonLdConsts.ID))) {
preferredValues.add(JsonLdConsts.VOCAB);
preferredValues.add(JsonLdConsts.ID);
}
// 2.12.2)
else {
preferredValues.add(JsonLdConsts.ID);
preferredValues.add(JsonLdConsts.VOCAB);
}
}
// 2.13)
else {
preferredValues.add(typeLanguageValue);
}
preferredValues.add(JsonLdConsts.NONE);
// 2.14)
final String term = selectTerm(iri, containers, typeLanguage, preferredValues);
// 2.15)
if (term != null) {
return term;
}
}
// 3)
if (relativeToVocab && this.containsKey(JsonLdConsts.VOCAB)) {
// determine if vocab is a prefix of the iri
final String vocab = (String) this.get(JsonLdConsts.VOCAB);
// 3.1)
if (iri.indexOf(vocab) == 0 && !iri.equals(vocab)) {
// use suffix as relative iri if it is not a term in the
// active context
final String suffix = iri.substring(vocab.length());
if (!termDefinitions.containsKey(suffix)) {
return suffix;
}
}
}
// 4)
String compactIRI = null;
// 5)
for (final String term : termDefinitions.keySet()) {
final Map<String, Object> termDefinition = (Map<String, Object>) termDefinitions
.get(term);
// 5.1)
if (term.contains(":")) {
continue;
}
// 5.2)
if (termDefinition == null || iri.equals(termDefinition.get(JsonLdConsts.ID))
|| !iri.startsWith((String) termDefinition.get(JsonLdConsts.ID))) {
continue;
}
// 5.3)
final String candidate = term + ":"
+ iri.substring(((String) termDefinition.get(JsonLdConsts.ID)).length());
// 5.4)
compactIRI = _iriCompactionStep5point4(iri, value, compactIRI, candidate,
termDefinitions);
}
// 6)
if (compactIRI != null) {
return compactIRI;
}
// 7)
if (!relativeToVocab) {
return JsonLdUrl.removeBase(this.get(JsonLdConsts.BASE), iri);
}
// 8)
return iri;
}
/*
* This method is only visible for testing.
*/
public static String _iriCompactionStep5point4(String iri, Object value, String compactIRI,
final String candidate, Map<String, Object> termDefinitions) {
final boolean condition1 = (compactIRI == null
|| compareShortestLeast(candidate, compactIRI) < 0);
final boolean condition2 = (!termDefinitions.containsKey(candidate) || (iri
.equals(((Map<String, Object>) termDefinitions.get(candidate)).get(JsonLdConsts.ID))
&& value == null));
if (condition1 && condition2) {
compactIRI = candidate;
}
return compactIRI;
}
/**
* Return a map of potential RDF prefixes based on the JSON-LD Term
* Definitions in this context.
* <p>
* No guarantees of the prefixes are given, beyond that it will not contain
* ":".
*
* @param onlyCommonPrefixes
* If <code>true</code>, the result will not include "not so
* useful" prefixes, such as "term1": "http://example.com/term1",
* e.g. all IRIs will end with "/" or "#". If <code>false</code>,
* all potential prefixes are returned.
*
* @return A map from prefix string to IRI string
*/
public Map<String, String> getPrefixes(boolean onlyCommonPrefixes) {
final Map<String, String> prefixes = new LinkedHashMap<String, String>();
for (final String term : termDefinitions.keySet()) {
if (term.contains(":")) {
continue;
}
final Map<String, Object> termDefinition = (Map<String, Object>) termDefinitions
.get(term);
if (termDefinition == null) {
continue;
}
final String id = (String) termDefinition.get(JsonLdConsts.ID);
if (id == null) {
continue;
}
if (term.startsWith("@") || id.startsWith("@")) {
continue;
}
if (!onlyCommonPrefixes || id.endsWith("/") || id.endsWith("#")) {
prefixes.put(term, id);
}
}
return prefixes;
}
String compactIri(String iri, boolean relativeToVocab) {
return compactIri(iri, null, relativeToVocab, false);
}
String compactIri(String iri) {
return compactIri(iri, null, false, false);
}
@Override
public Context clone() {
final Context rval = (Context) super.clone();
// TODO: is this shallow copy enough? probably not, but it passes all
// the tests!
rval.termDefinitions = new LinkedHashMap<String, Object>(this.termDefinitions);
return rval;
}
/**
* Inverse Context Creation
*
* http://json-ld.org/spec/latest/json-ld-api/#inverse-context-creation
*
* Generates an inverse context for use in the compaction algorithm, if not
* already generated for the given active context.
*
* @return the inverse context.
*/
public Map<String, Object> getInverse() {
// lazily create inverse
if (inverse != null) {
return inverse;
}
// 1)
inverse = newMap();
// 2)
String defaultLanguage = (String) this.get(JsonLdConsts.LANGUAGE);
if (defaultLanguage == null) {
defaultLanguage = JsonLdConsts.NONE;
}
// create term selections for each mapping in the context, ordererd by
// shortest and then lexicographically least
final List<String> terms = new ArrayList<String>(termDefinitions.keySet());
Collections.sort(terms, new Comparator<String>() {