forked from spdx/Spdx-Java-Library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ModelObject.java
1439 lines (1334 loc) · 59.3 KB
/
ModelObject.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
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
/**
* Copyright (c) 2019 Source Auditor Inc.
*
* SPDX-License-Identifier: Apache-2.0
*
* 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.spdx.library.model;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spdx.library.DefaultModelStore;
import org.spdx.library.InvalidSPDXAnalysisException;
import org.spdx.library.ModelCopyManager;
import org.spdx.library.SpdxConstants;
import org.spdx.library.SpdxVerificationHelper;
import org.spdx.library.Version;
import org.spdx.library.model.enumerations.AnnotationType;
import org.spdx.library.model.enumerations.ChecksumAlgorithm;
import org.spdx.library.model.enumerations.ReferenceCategory;
import org.spdx.library.model.enumerations.RelationshipType;
import org.spdx.library.model.enumerations.SpdxEnumFactory;
import org.spdx.library.model.license.*;
import org.spdx.library.model.license.CrossRef.CrossRefBuilder;
import org.spdx.library.model.pointer.ByteOffsetPointer;
import org.spdx.library.model.pointer.LineCharPointer;
import org.spdx.library.model.pointer.SinglePointer;
import org.spdx.library.model.pointer.StartEndPointer;
import org.spdx.storage.IModelStore;
import org.spdx.storage.IModelStore.IModelStoreLock;
import org.spdx.storage.IModelStore.IdType;
import org.spdx.storage.IModelStore.ModelUpdate;
/**
* @author Gary O'Neall
*
* Superclass for all SPDX model objects
*
* Provides the primary interface to the storage class that access and stores the data for
* the model objects.
*
* This class includes several helper methods to manage the storage and retrieval of properties.
*
* Each model object is in itself stateless. All state is maintained in the Model Store.
* The Document URI uniquely identifies the document containing the model object.
*
* The concrete classes are expected to implements getters for the model class properties which translate
* into calls to the getTYPEPropertyValue where TYPE is the type of value to be returned and the property name
* is passed as a parameter.
*
* There are 2 methods of setting values:
* - call the setPropertyValue, clearValueCollection or addValueToCollection methods - this will call the modelStore and store the
* value immediately
* - Gather a list of updates by calling the updatePropertyValue, updateClearValueList, or updateAddPropertyValue
* methods. These methods return a ModelUpdate which can be applied later by calling the <code>apply()</code> method.
* A convenience method <code>Write.applyUpdatesInOneTransaction</code> will perform all updates within
* a single transaction. This method may result in higher performance updates for some Model Store implementations.
* Note that none of the updates will be applied until the storage manager update method is invoked.
*
* Property values are restricted to the following types:
* - String - Java Strings
* - Booolean - Java Boolean or primitive boolean types
* - ModelObject - A concrete subclass of this type
* - {@literal Collection<T>} - A Collection of type T where T is one of the supported non-collection types
*
* This class also handles the conversion of a ModelObject to and from a TypeValue for storage in the ModelStore.
*
*/
public abstract class ModelObject {
static final Logger logger = LoggerFactory.getLogger(ModelObject.class);
private IModelStore modelStore;
private String documentUri;
private String id;
/**
* If non null, a reference made to a model object stored in a different modelStore and/or
* document will be copied to this modelStore and documentUri
*/
private ModelCopyManager copyManager = null;
/**
* if true, checks input values for setters to verify valid SPDX inputs
*/
protected boolean strict = true;
// the following fields are for debugging when equivalent returns false
enum NotEquivalent {
DIFFERENT_CLASS, MISSING_PROPERTY, PROPERTY_NOT_EQUIVALENT, COMPARE_PROPERTY_MISSING};
static class NotEquivalentReason {
NotEquivalent reason;
String property = null;
public NotEquivalentReason(NotEquivalent reason) {
this.reason = reason;
}
public NotEquivalentReason(NotEquivalent reason, String property) {
this(reason);
this.property = property;
}
/**
* @return the reason
*/
public NotEquivalent getReason() {
return reason;
}
/**
* @param reason the reason to set
*/
public void setReason(NotEquivalent reason) {
this.reason = reason;
}
/**
* @return the property
*/
public String getProperty() {
return property;
}
/**
* @param property the property to set
*/
public void setProperty(String property) {
this.property = property;
}
}
NotEquivalentReason lastNotEquivalentReason = null;
/**
* Create a new Model Object using an Anonymous ID with the defualt store and default document URI
* @throws InvalidSPDXAnalysisException
*/
public ModelObject() throws InvalidSPDXAnalysisException {
this(DefaultModelStore.getDefaultModelStore().getNextId(IdType.Anonymous, DefaultModelStore.getDefaultDocumentUri()));
}
/**
* Open or create a model object with the default store and default document URI
* @param id ID for this object - must be unique within the SPDX document
* @throws InvalidSPDXAnalysisException
*/
public ModelObject(String id) throws InvalidSPDXAnalysisException {
this(DefaultModelStore.getDefaultModelStore(), DefaultModelStore.getDefaultDocumentUri(), id,
DefaultModelStore.getDefaultCopyManager(), true);
}
/**
* @param modelStore Storage for the model objects
* @param documentUri SPDX Document URI for a document associated with this model
* @param id ID for this object - must be unique within the SPDX document
* @param copyManager - if supplied, model objects will be implictly copied into this model store and document URI when referenced by setting methods
* @param create - if true, the object will be created in the store if it is not already present
* @throws InvalidSPDXAnalysisException
*/
public ModelObject(IModelStore modelStore, String documentUri, String id, @Nullable ModelCopyManager copyManager,
boolean create) throws InvalidSPDXAnalysisException {
Objects.requireNonNull(modelStore, "Model Store can not be null");
Objects.requireNonNull(documentUri, "Document URI can not be null");
Objects.requireNonNull(id, "ID can not be null");
this.modelStore = modelStore;
this.documentUri = documentUri;
this.id = id;
this.copyManager = copyManager;
Optional<TypedValue> existing = modelStore.getTypedValue(documentUri, id);
if (existing.isPresent()) {
if (create && !existing.get().getType().equals(getType())) {
throw new SpdxIdInUseException("Can not create "+id+". It is already in use with type "+existing.get().getType()+" which is incompatible with type "+getType());
}
} else {
if (create) {
IModelStoreLock lock = enterCriticalSection(false);
// re-check since previous check was done outside of the lock
try {
if (!modelStore.exists(documentUri, id)) {
modelStore.create(documentUri, id, getType());
}
} finally {
lock.unlock();
}
} else {
throw new SpdxIdNotFoundException(id+" does not exist in document "+documentUri);
}
}
}
// Abstract methods that must be implemented in the subclasses
/**
* @return The class name for this object. Class names are defined in the constants file
*/
public abstract String getType();
/**
* Implementation of the specific verifications for this model object
* @param specVersion Version of the SPDX spec to verify against
* @param verifiedElementIds list of all Element Id's which have already been verified - prevents infinite recursion
* @return Any verification errors or warnings associated with this object
*/
protected abstract List<String> _verify(Set<String> verifiedElementIds, String specVersion);
/**
* @param specVersion Version of the SPDX spec to verify against
* @param verifiedIElementds list of all element Id's which have already been verified - prevents infinite recursion
* @return Any verification errors or warnings associated with this object
*/
public List<String> verify(Set<String> verifiedIElementds, String specVersion) {
if (verifiedIElementds.contains(this.id)) {
return new ArrayList<>();
} else {
// The verifiedElementId is added in the SpdxElement._verify method
return _verify(verifiedIElementds, specVersion);
}
}
/**
* Verifies against the more recent supported specification version
* @return Any verification errors or warnings associated with this object
*/
public List<String> verify() {
return verify(Version.CURRENT_SPDX_VERSION);
}
/**
* @param specVersion Version of the SPDX spec to verify against
* @return Any verification errors or warnings associated with this object
*/
public List<String> verify(String specVersion) {
return verify(new HashSet<String>(), specVersion);
}
/**
* @return the Document URI for this object
*/
public String getDocumentUri() {
return this.documentUri;
}
/**
* @return ID for the object
*/
public String getId() {
return id;
}
/**
* @return the model store for this object
*/
public IModelStore getModelStore() {
return this.modelStore;
}
/**
* @return if strict input checking is enabled
*/
public boolean isStrict() {
return strict;
}
/**
* @param strict if true, inputs will be validated against the SPDX spec
*/
public void setStrict(boolean strict) {
this.strict = strict;
}
/**
* Enter a critical section. leaveCriticialSection must be called.
* @param readLockRequested true implies a read lock, false implies write lock.
* @throws InvalidSPDXAnalysisException
*/
public IModelStoreLock enterCriticalSection(boolean readLockRequested) throws InvalidSPDXAnalysisException {
return this.getModelStore().enterCriticalSection(this.getDocumentUri(), readLockRequested);
}
/**
* Leave a critical section. Releases the lock form the matching enterCriticalSection
*/
public void leaveCriticalSection(IModelStoreLock lock) {
this.getModelStore().leaveCriticalSection(lock);
}
//The following methods are to manage the properties associated with the model object
/**
* @return all names of property values currently associated with this object
* @throws InvalidSPDXAnalysisException
*/
public List<String> getPropertyValueNames() throws InvalidSPDXAnalysisException {
return modelStore.getPropertyValueNames(documentUri, id);
}
/**
* Get an object value for a property
* @param propertyName Name of the property
* @return value associated with a property
*/
protected Optional<Object> getObjectPropertyValue(String propertyName) throws InvalidSPDXAnalysisException {
Optional<Object> retval = getObjectPropertyValue(modelStore, documentUri, id, propertyName, copyManager);
if (retval.isPresent() && retval.get() instanceof ModelObject && !strict) {
((ModelObject)retval.get()).setStrict(strict);
}
return retval;
}
/**
* Get an object value for a property
* @param stModelStore
* @param stDocumentUri
* @param stId
* @param propertyName
* @param copyManager if non null, any ModelObject property value not stored in the stModelStore under the stDocumentUri will be copied to make it available
* @return value associated with a property
* @throws InvalidSPDXAnalysisException
*/
protected static Optional<Object> getObjectPropertyValue(IModelStore stModelStore, String stDocumentUri,
String stId, String propertyName, ModelCopyManager copyManager) throws InvalidSPDXAnalysisException {
IModelStoreLock lock = stModelStore.enterCriticalSection(stDocumentUri, false);
// NOTE: we use a write lock since the ModelStorageClassConverter may end up creating objects in the store
try {
if (!stModelStore.exists(stDocumentUri, stId)) {
return Optional.empty();
} else if (stModelStore.isCollectionProperty(stDocumentUri, stId, propertyName)) {
return Optional.of(new ModelCollection<>(stModelStore, stDocumentUri, stId, propertyName, copyManager, null));
} else {
return ModelStorageClassConverter.optionalStoredObjectToModelObject(stModelStore.getValue(stDocumentUri, stId, propertyName),
stDocumentUri, stModelStore, copyManager);
}
} finally {
lock.unlock();
}
}
/**
* Set a property value for a property name, creating the property if necessary
* @param stModelStore Model store for the properties
* @param stDocumentUri Unique document URI
* @param stId ID of the item to associate the property with
* @param propertyName Name of the property associated with this object
* @param value Value to associate with the property
* @param copyManager if non null, any ModelObject property value not stored in the stModelStore under the stDocumentUri will be copied to make it available
* @throws InvalidSPDXAnalysisException
*/
protected static void setPropertyValue(IModelStore stModelStore, String stDocumentUri,
String stId, String propertyName, @Nullable Object value, ModelCopyManager copyManager) throws InvalidSPDXAnalysisException {
Objects.requireNonNull(stModelStore, "Model Store can not be null");
Objects.requireNonNull(stDocumentUri, "Document Uri can not be null");
Objects.requireNonNull(stId, "ID can not be null");
Objects.requireNonNull(propertyName, "Property name can not be null");
if (value == null) {
// we just remove the value
removeProperty(stModelStore, stDocumentUri, stId, propertyName);
} else if (value instanceof Collection) {
replacePropertyValueCollection(stModelStore, stDocumentUri, stId, propertyName, (Collection<?>)value, copyManager);
} else {
stModelStore.setValue(stDocumentUri, stId, propertyName, ModelStorageClassConverter.modelObjectToStoredObject(
value, stDocumentUri, stModelStore, copyManager));
}
}
/**
* Set a property value for a property name, creating the property if necessary
* @param propertyName Name of the property associated with this object
* @param value Value to associate with the property
* @throws InvalidSPDXAnalysisException
*/
protected void setPropertyValue(String propertyName, @Nullable Object value) throws InvalidSPDXAnalysisException {
if (this instanceof IndividualUriValue) {
throw new InvalidSPDXAnalysisException("Can not set a property for the literal value "+((IndividualUriValue)this).getIndividualURI());
}
setPropertyValue(this.modelStore, this.documentUri, this.id, propertyName, value, copyManager);
}
/**
* Create an update when, when applied by the ModelStore, sets a property value for a property name, creating the property if necessary
* @param propertyName Name of the property associated with this object
* @param value Value to associate with the property
* @return an update which can be applied by invoking the apply method
*/
protected ModelUpdate updatePropertyValue(String propertyName, Object value) {
return () ->{
setPropertyValue(this.modelStore, this.documentUri, this.id, propertyName, value, copyManager);
};
}
/**
* @param propertyName Name of a property
* @return the Optional String value associated with a property, null if no value is present
* @throws SpdxInvalidTypeException
*/
protected Optional<String> getStringPropertyValue(String propertyName) throws InvalidSPDXAnalysisException {
Optional<Object> result = getObjectPropertyValue(propertyName);
if (result.isPresent()) {
if (result.get() instanceof String) {
return Optional.of((String)result.get());
} else if (result.get() instanceof IndividualUriValue) {
String uri = ((IndividualUriValue)result.get()).getIndividualURI();
if (SpdxConstants.URI_VALUE_NONE.equals(uri)) {
return Optional.of(SpdxConstants.NONE_VALUE);
} else if (SpdxConstants.URI_VALUE_NOASSERTION.equals(uri)) {
return Optional.of(SpdxConstants.NOASSERTION_VALUE);
} else {
logger.error("Can not convert a URI value to String: "+uri);
throw new SpdxInvalidTypeException("Can not convert a URI value to String: "+uri);
}
} else {
logger.error("Property "+propertyName+" is not of type String");
throw new SpdxInvalidTypeException("Property "+propertyName+" is not of type String");
}
} else {
return Optional.empty();
}
}
/**
* @param propertyName Name of a property
* @return the Optional Integer value associated with a property, null if no value is present
* @throws InvalidSPDXAnalysisException
*/
protected Optional<Integer> getIntegerPropertyValue(String propertyName) throws InvalidSPDXAnalysisException {
Optional<Object> result = getObjectPropertyValue(propertyName);
Optional<Integer> retval;
if (result.isPresent()) {
if (!(result.get() instanceof Integer)) {
throw new SpdxInvalidTypeException("Property "+propertyName+" is not of type Integer");
}
retval = Optional.of((Integer)result.get());
} else {
retval = Optional.empty();
}
return retval;
}
@SuppressWarnings("unchecked")
protected Optional<Enum<?>> getEnumPropertyValue(String propertyName) throws InvalidSPDXAnalysisException {
Optional<Object> result = getObjectPropertyValue(propertyName);
if (!result.isPresent()) {
return Optional.empty();
}
if (result.get() instanceof Enum) {
return (Optional<Enum<?>>)(Optional<?>)result;
}
if (!(result.get() instanceof IndividualUriValue)) {
throw new SpdxInvalidTypeException("Property "+propertyName+" is not of type Individual Value or enum");
}
Enum<?> retval = SpdxEnumFactory.uriToEnum.get(((IndividualUriValue)result.get()).getIndividualURI());
if (Objects.isNull(retval)) {
logger.error("Unknown individual value for enum: "+((IndividualUriValue)result.get()).getIndividualURI());
throw new InvalidSPDXAnalysisException("Unknown individual value for enum: "+((IndividualUriValue)result.get()).getIndividualURI());
} else {
return Optional.of(retval);
}
}
/**
* @param propertyName Name of the property
* @return the Optional Boolean value for a property
* @throws SpdxInvalidTypeException
*/
protected Optional<Boolean> getBooleanPropertyValue(String propertyName) throws InvalidSPDXAnalysisException {
Optional<Object> result = getObjectPropertyValue(propertyName);
if (result.isPresent()) {
if (result.get() instanceof Boolean) {
return Optional.of((Boolean)result.get());
} else if (result.get() instanceof String) {
// try to convert
String sResult = ((String)result.get()).toLowerCase();
if ("true".equals(sResult)) {
return Optional.of(Boolean.valueOf(true));
} else if ("false".equals(sResult)) {
return Optional.of(Boolean.valueOf(false));
} else {
throw new SpdxInvalidTypeException("Property "+propertyName+" is not of type Boolean");
}
} else {
throw new SpdxInvalidTypeException("Property "+propertyName+" is not of type Boolean");
}
} else {
return Optional.empty();
}
}
/**
* Converts property values to an AnyLicenseInfo if possible - if NONE or NOASSERTION URI value, convert to the appropriate license
* @param propertyName
* @return AnyLicenseInfo
* @throws InvalidSPDXAnalysisException
*/
@SuppressWarnings("unchecked")
protected Optional<AnyLicenseInfo> getAnyLicenseInfoPropertyValue(String propertyName) throws InvalidSPDXAnalysisException {
Optional<Object> result = getObjectPropertyValue(propertyName);
if (!result.isPresent()) {
return Optional.empty();
} else if (result.get() instanceof AnyLicenseInfo) {
return (Optional<AnyLicenseInfo>)(Optional<?>)result;
} else if (result.get() instanceof IndividualUriValue) {
String uri = ((IndividualUriValue)result.get()).getIndividualURI();
if (SpdxConstants.URI_VALUE_NONE.equals(uri)) {
return Optional.of(new SpdxNoneLicense());
} else if (SpdxConstants.URI_VALUE_NOASSERTION.equals(uri)) {
return Optional.of(new SpdxNoAssertionLicense());
} else {
logger.error("Can not convert a URI value to a license: "+uri);
throw new SpdxInvalidTypeException("Can not convert a URI value to a license: "+uri);
}
} else {
logger.error("Invalid type for AnyLicenseInfo property: "+result.get().getClass().toString());
throw new SpdxInvalidTypeException("Invalid type for AnyLicenseInfo property: "+result.get().getClass().toString());
}
}
/**
* Converts property values to an SpdxElement if possible - if NONE or NOASSERTION URI value, convert to the appropriate SpdxElement
* @param propertyName name of the property
* @return SpdxElement stored
* @throws InvalidSPDXAnalysisException
*/
@SuppressWarnings("unchecked")
protected Optional<SpdxElement> getElementPropertyValue(String propertyName) throws InvalidSPDXAnalysisException {
Optional<Object> result = getObjectPropertyValue(propertyName);
if (!result.isPresent()) {
return Optional.empty();
} else if (result.get() instanceof SpdxElement) {
return (Optional<SpdxElement>)(Optional<?>)result;
} else if (result.get() instanceof IndividualUriValue) {
String uri = ((IndividualUriValue)result.get()).getIndividualURI();
if (SpdxConstants.URI_VALUE_NONE.equals(uri)) {
return Optional.of(new SpdxNoneElement());
} else if (SpdxConstants.URI_VALUE_NOASSERTION.equals(uri)) {
return Optional.of(new SpdxNoAssertionElement());
} else {
logger.error("Can not convert a URI value to an SPDX element: "+uri);
throw new SpdxInvalidTypeException("Can not convert a URI value to an SPDX element: "+uri);
}
} else {
logger.error("Invalid type for SpdxElement property: "+result.get().getClass().toString());
throw new SpdxInvalidTypeException("Invalid type for SpdxElement property: "+result.get().getClass().toString());
}
}
/**
* Removes a property and its value from the model store if it exists
* @param stModelStore Model store for the properties
* @param stDocumentUri Unique document URI
* @param stId ID of the item to associate the property with
* @param propertyName Name of the property associated with this object to be removed
* @throws InvalidSPDXAnalysisException
*/
protected static void removeProperty(IModelStore stModelStore, String stDocumentUri, String stId, String propertyName) throws InvalidSPDXAnalysisException {
stModelStore.removeProperty(stDocumentUri, stId, propertyName);
}
/**
* Removes a property and its value from the model store if it exists
* @param propertyName Name of the property associated with this object to be removed
* @throws InvalidSPDXAnalysisException
*/
protected void removeProperty(String propertyName) throws InvalidSPDXAnalysisException {
removeProperty(modelStore, documentUri, id, propertyName);
}
/**
* Create an update when, when applied by the ModelStore, removes a property and its value from the model store if it exists
* @param propertyName Name of the property associated with this object to be removed
* @return an update which can be applied by invoking the apply method
*/
protected ModelUpdate updateRemoveProperty(String propertyName) {
return () -> {
removeProperty(modelStore, documentUri, id, propertyName);
};
}
// The following methods manage collections of values associated with a property
/**
* Clears a collection of values associated with a property creating the property if it does not exist
* @param stModelStore Model store for the properties
* @param stDocumentUri Unique document URI
* @param stId ID of the item to associate the property with
* @param propertyName Name of the property
* @throws InvalidSPDXAnalysisException
*/
protected static void clearValueCollection(IModelStore stModelStore, String stDocumentUri, String stId, String propertyName) throws InvalidSPDXAnalysisException {
stModelStore.clearValueCollection(stDocumentUri, stId, propertyName);
}
/**
* Clears a collection of values associated with a property
* @param propertyName Name of the property
*/
protected void clearValueCollection(String propertyName) throws InvalidSPDXAnalysisException {
clearValueCollection(modelStore, documentUri, id, propertyName);
}
/**
* Create an update when, when applied by the ModelStore, clears a collection of values associated with a property
* @param propertyName Name of the property
* @return an update which can be applied by invoking the apply method
*/
protected ModelUpdate updateClearValueCollection(String propertyName) {
return () ->{
clearValueCollection(modelStore, documentUri, id, propertyName);
};
}
/**
* Add a value to a collection of values associated with a property. If a value
* is a ModelObject and does not belong to the document, it will be copied into
* the object store
*
* @param stModelStore Model store for the properties
* @param stDocumentUri Unique document URI
* @param stId ID of the item to associate the property with
* @param propertyName Name of the property
* @param value to add
* @param copyManager
* @throws InvalidSPDXAnalysisException
*/
protected static void addValueToCollection(IModelStore stModelStore, String stDocumentUri, String stId,
String propertyName, Object value, ModelCopyManager copyManager) throws InvalidSPDXAnalysisException {
Objects.requireNonNull(value, "Value can not be null");
stModelStore.addValueToCollection(stDocumentUri, stId, propertyName,
ModelStorageClassConverter.modelObjectToStoredObject(value, stDocumentUri, stModelStore, copyManager));
}
/**
* Add a value to a collection of values associated with a property. If a value is a ModelObject and does not
* belong to the document, it will be copied into the object store
* @param propertyName Name of the property
* @param value to add
* @throws InvalidSPDXAnalysisException
*/
protected void addPropertyValueToCollection(String propertyName, Object value) throws InvalidSPDXAnalysisException {
addValueToCollection(modelStore, documentUri, id, propertyName, value, copyManager);
}
/**
* Create an update when, when applied, adds a value to a collection of values associated with a property. If a value is a ModelObject and does not
* belong to the document, it will be copied into the object store
* @param propertyName Name of the property
* @param value to add
* @return an update which can be applied by invoking the apply method
*/
protected ModelUpdate updateAddPropertyValueToCollection(String propertyName, Object value) {
return () ->{
addValueToCollection(modelStore, documentUri, id, propertyName, value, copyManager);
};
}
/**
* Replace the entire value collection for a property. If a value is a ModelObject and does not
* belong to the document, it will be copied into the object store
* @param stModelStore Model store for the properties
* @param stDocumentUri Unique document URI
* @param stId ID of the item to associate the property with
* @param propertyName name of the property
* @param values collection of new properties
* @param copyManager if non-null, any ModelObject property value not stored in the stModelStore under the stDocumentUri will be copied to make it available
* @throws InvalidSPDXAnalysisException
*/
protected static void replacePropertyValueCollection(IModelStore stModelStore, String stDocumentUri, String stId,
String propertyName, Collection<?> values, ModelCopyManager copyManager) throws InvalidSPDXAnalysisException {
clearValueCollection(stModelStore, stDocumentUri, stId, propertyName);
for (Object value:values) {
addValueToCollection(stModelStore, stDocumentUri, stId, propertyName, value, copyManager);
}
}
/**
* Remove a property value from a collection
* @param stModelStore Model store for the properties
* @param stDocumentUri Unique document URI
* @param stId ID of the item to associate the property with
* @param propertyName name of the property
* @param value Value to be removed
* @throws InvalidSPDXAnalysisException
*/
protected static void removePropertyValueFromCollection(IModelStore stModelStore, String stDocumentUri, String stId,
String propertyName, Object value) throws InvalidSPDXAnalysisException {
stModelStore.removeValueFromCollection(stDocumentUri, stId, propertyName,
ModelStorageClassConverter.modelObjectToStoredObject(value, stDocumentUri, stModelStore, null));
}
/**
* Remove a property value from a collection
* @param propertyName name of the property
* @param value Value to be removed
* @throws InvalidSPDXAnalysisException
*/
protected void removePropertyValueFromCollection(String propertyName, Object value) throws InvalidSPDXAnalysisException {
removePropertyValueFromCollection(modelStore, documentUri, id, propertyName, value);
}
/**
* Create an update when, when applied, removes a property value from a collection
* @param propertyName name of the property
* @param value Value to be removed
* @return an update which can be applied by invoking the apply method
*/
protected ModelUpdate updateRemovePropertyValueFromCollection(String propertyName, Object value) {
return () -> {
removePropertyValueFromCollection(modelStore, documentUri, id, propertyName, value);
};
}
/**
* @param propertyName Name of the property
* @return Set of values associated with a property
*/
protected ModelSet<?> getObjectPropertyValueSet(String propertyName, Class<?> type) throws InvalidSPDXAnalysisException {
return new ModelSet<Object>(this.modelStore, this.documentUri, this.id, propertyName, this.copyManager, type);
}
/**
* @param propertyName Name of the property
* @return Collection of values associated with a property
*/
protected ModelCollection<?> getObjectPropertyValueCollection(String propertyName, Class<?> type) throws InvalidSPDXAnalysisException {
return new ModelCollection<Object>(this.modelStore, this.documentUri, this.id, propertyName, this.copyManager, type);
}
/**
* @param propertyName Name of property
* @return Collection of Strings associated with the property
* @throws SpdxInvalidTypeException
*/
@SuppressWarnings("unchecked")
protected Collection<String> getStringCollection(String propertyName) throws InvalidSPDXAnalysisException {
if (!isCollectionMembersAssignableTo(propertyName, String.class)) {
throw new SpdxInvalidTypeException("Property "+propertyName+" does not contain a collection of Strings");
}
return (Collection<String>)(Collection<?>)getObjectPropertyValueSet(propertyName, String.class);
}
protected boolean isCollectionMembersAssignableTo(String propertyName, Class<?> clazz) throws InvalidSPDXAnalysisException {
return modelStore.isCollectionMembersAssignableTo(this.documentUri, this.id, propertyName,
ModelStorageClassConverter.modelClassToStoredClass(clazz));
}
/**
* @param compare
* @return true if all the properties have the same or equivalent values
*/
public boolean equivalent(ModelObject compare) throws InvalidSPDXAnalysisException {
return equivalent(compare, false);
}
/**
* @param compare
* @param ignoreRelatedElements if true, do not compare properties relatedSpdxElement - used to prevent infinite recursion
* @return true if all the properties have the same or equivalent values
*/
public boolean equivalent(ModelObject compare, boolean ignoreRelatedElements) throws InvalidSPDXAnalysisException {
if (!this.getClass().equals(compare.getClass())) {
lastNotEquivalentReason = new NotEquivalentReason(NotEquivalent.DIFFERENT_CLASS);
return false;
}
List<String> propertyValueNames = getPropertyValueNames();
List<String> comparePropertyValueNames = new ArrayList<String>(compare.getPropertyValueNames()); // create a copy since we're going to modify it
for (String propertyName:propertyValueNames) {
if (ignoreRelatedElements && isRelatedElement(propertyName)) {
continue;
}
if (comparePropertyValueNames.contains(propertyName)) {
if (!propertyValuesEquivalent(propertyName, this.getObjectPropertyValue(propertyName),
compare.getObjectPropertyValue(propertyName), ignoreRelatedElements)) {
lastNotEquivalentReason = new NotEquivalentReason(
NotEquivalent.PROPERTY_NOT_EQUIVALENT, propertyName);
return false;
}
comparePropertyValueNames.remove(propertyName);
} else {
// No property value
Optional<Object> propertyValueOptional = this.getObjectPropertyValue(propertyName);
if (propertyValueOptional.isPresent()) {
Object propertyValue = propertyValueOptional.get();
if (isEquivalentToNull(propertyValue, propertyName)) {
continue;
}
lastNotEquivalentReason = new NotEquivalentReason(
NotEquivalent.COMPARE_PROPERTY_MISSING, propertyName);
return false;
}
}
}
for (String propertyName:comparePropertyValueNames) { // check any remaining property values
if (ignoreRelatedElements && isRelatedElement(propertyName)) {
continue;
}
Optional<Object> comparePropertyValueOptional = compare.getObjectPropertyValue(propertyName);
if (!comparePropertyValueOptional.isPresent()) {
continue;
}
Object comparePropertyValue = comparePropertyValueOptional.get();
if (isEquivalentToNull(comparePropertyValue, propertyName)) {
continue;
}
lastNotEquivalentReason = new NotEquivalentReason(
NotEquivalent.MISSING_PROPERTY, propertyName);
return false;
}
return true;
}
// Some values are treated like null in comparisons - in particular empty model collections and
// "no assertion" values and a filesAnalyzed filed with a value of true
private boolean isEquivalentToNull(Object propertyValue, String propertyName) {
if (propertyValue instanceof ModelCollection) {
return ((ModelCollection<?>) propertyValue).size() == 0;
} else if (isNoAssertion(propertyValue)) {
return true;
} else if (SpdxConstants.PROP_PACKAGE_FILES_ANALYZED.equals(propertyName)) {
return propertyValue instanceof Boolean && (Boolean)(propertyValue);
} else {
return false;
}
}
private boolean isRelatedElement(String propertyName) {
return SpdxConstants.PROP_RELATED_SPDX_ELEMENT.equals(propertyName);
}
private boolean isEmptyModelCollection(Object value) {
return (value instanceof ModelCollection)
&& (((ModelCollection<?>) value).size() == 0);
}
private boolean isNoAssertion(Object propertyValue) {
return propertyValue instanceof SpdxNoAssertionLicense ||
propertyValue.equals(SpdxConstants.NOASSERTION_VALUE);
}
/**
* @param propertyName Name of the property
* @param valueA value to compare
* @param valueB value to compare
* @param ignoreRelatedElements if true, do not compare properties relatedSpdxElement - used to prevent infinite recursion
* @return true if the property values are equivalent
* @throws InvalidSPDXAnalysisException
*/
private boolean propertyValuesEquivalent(String propertyName, Optional<Object> valueA,
Optional<Object> valueB, boolean ignoreRelatedElements) throws InvalidSPDXAnalysisException {
if (!valueA.isPresent()) {
if (valueB.isPresent()) {
return isEmptyModelCollection(valueB.get());
}
} else if (!valueB.isPresent()) {
return isEmptyModelCollection(valueA.get());
} else if (valueA.get() instanceof ModelCollection && valueB.get() instanceof ModelCollection) {
List<?> myList = ((ModelCollection<?>)valueA.get()).toImmutableList();
List<?> compareList = ((ModelCollection<?>)valueB.get()).toImmutableList();
if (!areEquivalent(myList, compareList, ignoreRelatedElements)) {
return false;
}
} else if (valueA.get() instanceof List && valueB.get() instanceof List) {
if (!areEquivalent((List<?>)valueA.get(), (List<?>)valueB.get(), ignoreRelatedElements)) {
return false;
}
} else if (valueA.get() instanceof IndividualUriValue && valueB.get() instanceof IndividualUriValue) {
if (!Objects.equals(((IndividualUriValue)valueA.get()).getIndividualURI(), ((IndividualUriValue)valueB.get()).getIndividualURI())) {
return false;
}
// Note: we must check the IndividualValue before the ModelObject types since the IndividualValue takes precedence
} else if (valueA.get() instanceof ModelObject && valueB.get() instanceof ModelObject) {
if (!((ModelObject)valueA.get()).equivalent(((ModelObject)valueB.get()),
isRelatedElement(propertyName) ? true : ignoreRelatedElements)) {
return false;
}
} else if (!OptionalObjectsEquivalent(valueA, valueB)) { // Present, not a list, and not a TypedValue
return false;
}
return true;
}
/**
* Compares 2 simple optional objects considering NONE and NOASSERTION values which are equivalent to their strings
* @param valueA
* @param valueB
* @return
*/
private boolean OptionalObjectsEquivalent(Optional<Object> valueA, Optional<Object> valueB) {
if (Objects.equals(valueA, valueB)) {
return true;
}
if (!valueA.isPresent()) {
return false;
}
if (!valueB.isPresent()) {
return false;
}
if (valueA.get() instanceof IndividualUriValue) {
if (SpdxConstants.URI_VALUE_NONE.equals(((IndividualUriValue)valueA.get()).getIndividualURI()) && SpdxConstants.NONE_VALUE.equals(valueB.get())) {
return true;
}
if (SpdxConstants.URI_VALUE_NOASSERTION.equals(((IndividualUriValue)valueA.get()).getIndividualURI()) && SpdxConstants.NOASSERTION_VALUE.equals(valueB.get())) {
return true;
}
}
if (valueB.get() instanceof IndividualUriValue) {
if (SpdxConstants.URI_VALUE_NONE.equals(((IndividualUriValue)valueB.get()).getIndividualURI()) && SpdxConstants.NONE_VALUE.equals(valueA.get())) {
return true;
}
if (SpdxConstants.URI_VALUE_NOASSERTION.equals(((IndividualUriValue)valueB.get()).getIndividualURI()) && SpdxConstants.NOASSERTION_VALUE.equals(valueA.get())) {
return true;
}
}
if (valueA.get() instanceof String && valueB.get() instanceof String) {
return normalizeString((String)valueA.get()).equals(normalizeString((String)valueB.get()));
}
return false;
}
/**
* Normalize a string for dos and linux linefeeds
* @param s
* @return linux style only linefeeds
*/
private Object normalizeString(String s) {
return s.replaceAll("\r\n", "\n").trim();
}
/**
* Checks if for each item on either list, there is an item in the other list that is equivalent.
* @param ignoreRelatedElements Whether related elements should be ignored in the comparison
*/
private boolean areEquivalent(List<?> firstList, List<?> secondList,
boolean ignoreRelatedElements) throws InvalidSPDXAnalysisException {
if (firstList.size() != secondList.size()) {
return false;
}
for (Object item : firstList) {
if (!containsEqualOrEquivalentItem(secondList, item, ignoreRelatedElements)) {
return false;
}
}
for (Object item : secondList) {
if (!containsEqualOrEquivalentItem(firstList, item, ignoreRelatedElements)) {
return false;
}
}
return true;
}
private boolean containsEqualOrEquivalentItem(List<?> list, Object itemToFind,
boolean ignoreRelatedElements) throws InvalidSPDXAnalysisException {
if (list.contains(itemToFind)) {
return true;
} else if (itemToFind instanceof IndividualUriValue && list.contains(new SimpleUriValue((IndividualUriValue) itemToFind))) {
// Two IndividualUriValues are considered equal if their URI coincides
return true;
}
if (!(itemToFind instanceof ModelObject)) {
return false;
}
ModelObject objectToFind = (ModelObject) itemToFind;
for (Object objectToCompare : list) {
if (!(objectToCompare instanceof ModelObject)) {
continue;
}
if (objectToFind.equivalent((ModelObject) objectToCompare, ignoreRelatedElements)) {
return true;
}
}
return false;
}
@Override
public int hashCode() {
if (this.id != null) {
return this.id.toLowerCase().hashCode() ^ this.documentUri.hashCode();
} else {
return 0;
}