diff --git a/.gitignore b/.gitignore
index 2b8eef46..c9f5dff3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,4 +20,5 @@ buildNumber.properties
.settings/
# IntelliJ IDE files
-.idea/
\ No newline at end of file
+.idea/
+*.iml
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 2d549f90..72828062 100644
--- a/pom.xml
+++ b/pom.xml
@@ -148,17 +148,17 @@
org.spdx
spdx-java-model-2_X
- 0.1.0-Alpha
+ 1.0.0-RC1
org.spdx
spdx-java-core
- 0.1.0-Alpha
+ 1.0.0-RC1
org.spdx
spdx-java-model-3_0
- 0.1.0-Alpha
+ 1.0.0-RC1
diff --git a/src/main/java/org/spdx/Configuration.java b/src/main/java/org/spdx/Configuration.java
index 4e648ddf..00a0030c 100644
--- a/src/main/java/org/spdx/Configuration.java
+++ b/src/main/java/org/spdx/Configuration.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2023 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.
@@ -27,9 +27,9 @@
/**
* The configuration class for the Spdx-Java-Library. When a caller attempts to retrieve a configuration property, it
* will first be checked in the Java system properties (i.e. set via `-D` command line options to the JVM, or by
- * programmatic calls to `System.setProperty()` in code), and will then fallback on a properties file in the classpath.
+ * programmatic calls to `System.setProperty()` in code), and will then fall back on a properties file in the classpath.
* That file must be called `/resources/spdx-java-library.properties`.
- *
+ *
* Please see the documentation for specifics on what configuration options Spdx-Java-Library supports, and how they
* impact the library's behavior.
*/
@@ -100,7 +100,7 @@ private static Properties loadProperties(final String propertiesFileName) {
}
} catch (IOException e) {
// Ignore it and fall through
- logger.warn("IO Exception reading configuration properties file '" + propertiesFileName + "': " + e.getMessage(), e);
+ logger.warn("IO Exception reading configuration properties file '{}': {}", propertiesFileName, e.getMessage(), e);
result = null;
} finally {
if (in != null) {
@@ -108,7 +108,7 @@ private static Properties loadProperties(final String propertiesFileName) {
in.close();
} catch (IOException e) {
// Ignore it and fall through
- logger.warn("Unable to close configuration properties file '" + propertiesFileName + "': " + e.getMessage(), e);
+ logger.warn("Unable to close configuration properties file '{}': {}", propertiesFileName, e.getMessage(), e);
}
}
}
diff --git a/src/main/java/org/spdx/library/LicenseInfoFactory.java b/src/main/java/org/spdx/library/LicenseInfoFactory.java
index f9580b29..408fb674 100644
--- a/src/main/java/org/spdx/library/LicenseInfoFactory.java
+++ b/src/main/java/org/spdx/library/LicenseInfoFactory.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -44,9 +44,11 @@
* Factory for creating SPDXLicenseInfo objects from a Jena model
* @author Gary O'Neall
*/
+@SuppressWarnings("unused")
public class LicenseInfoFactory {
- static final Logger logger = LoggerFactory.getLogger(LicenseInfoFactory.class.getName());
+ @SuppressWarnings("unused")
+ static final Logger logger = LoggerFactory.getLogger(LicenseInfoFactory.class.getName());
public static final String NOASSERTION_LICENSE_NAME = "NOASSERTION";
public static final String NONE_LICENSE_NAME = "NONE";
@@ -192,8 +194,8 @@ public static AnyLicenseInfo parseSPDXLicenseString(String licenseString) throws
* A licenseID must NOT be "AND" or "OR"
* @param licenseString String conforming to the syntax
* @return an SPDXLicenseInfo created from the string
- * @throws InvalidLicenseStringException
- * @throws DefaultStoreNotInitialized
+ * @throws InvalidLicenseStringException On invalid license expression
+ * @throws DefaultStoreNotInitialized On the model store not being initialized - see DefaultModelStore in SPDX core package
*/
public static org.spdx.library.model.v2.license.AnyLicenseInfo parseSPDXLicenseStringCompatV2(String licenseString) throws InvalidLicenseStringException, DefaultStoreNotInitialized {
return parseSPDXLicenseStringCompatV2(licenseString, null, null, null);
@@ -210,7 +212,7 @@ public static boolean isSpdxListedLicenseId(String licenseID) {
}
/**
- * @return Array of all SPDX listed license IDs
+ * @return List of all SPDX listed license IDs
*/
public static List getSpdxListedLicenseIds() {
return ListedLicenses.getListedLicenses().getSpdxListedLicenseIds();
@@ -234,7 +236,7 @@ public static boolean isSpdxListedExceptionId(String id) {
/**
* @param id ID for the listed exception
* @return the standard SPDX license exception or null if the ID is not in the SPDX license list
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException On SPDX parsing errors
*/
public static ListedLicenseException getListedExceptionById(String id) throws InvalidSPDXAnalysisException {
return ListedLicenses.getListedLicenses().getListedExceptionById(id);
@@ -243,7 +245,7 @@ public static ListedLicenseException getListedExceptionById(String id) throws In
/**
* @param id ID for the listed exception
* @return the standard SPDX license exception in SPDX Spec V2.X format or null if the ID is not in the SPDX license list
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException On SPDX parsing errors
*/
public static org.spdx.library.model.v2.license.ListedLicenseException getListedExceptionV2ById(String id) throws InvalidSPDXAnalysisException {
return ListedLicenses.getListedLicenses().getListedExceptionByIdCompatV2(id);
diff --git a/src/main/java/org/spdx/library/ListedLicenses.java b/src/main/java/org/spdx/library/ListedLicenses.java
index 19974659..00f1eaf6 100644
--- a/src/main/java/org/spdx/library/ListedLicenses.java
+++ b/src/main/java/org/spdx/library/ListedLicenses.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -50,6 +50,7 @@
* @author Gary O'Neall
*
*/
+@SuppressWarnings({"UnusedReturnValue", "unused"})
public class ListedLicenses {
static final Logger logger = LoggerFactory.getLogger(ListedLicenses.class.getName());
@@ -95,13 +96,13 @@ private static Properties loadLicenseProperties() {
}
} catch (IOException e) {
// Ignore it and fall through
- logger.warn("IO Exception reading listed license properties file: " + e.getMessage());
+ logger.warn("IO Exception reading listed license properties file: {}", e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
- logger.warn("Unable to close listed license properties file: " + e.getMessage());
+ logger.warn("Unable to close listed license properties file: {}", e.getMessage());
}
}
}
@@ -118,8 +119,7 @@ private void initializeLicenseModelStore() {
try {
baseModelStore = new SpdxListedLicenseWebStore();
} catch(InvalidSPDXAnalysisException ex) {
- logger.warn("Unable to access the most current listed licenses from https://spdx.org/licenses - using locally cached licenses: "+ex.getMessage()+
- " Note: you can set the org.spdx.useJARLicenseInfoOnly property to true to avoid this warning.");
+ logger.warn("Unable to access the most current listed licenses from https://spdx.org/licenses - using locally cached licenses: {} Note: you can set the org.spdx.useJARLicenseInfoOnly property to true to avoid this warning.", ex.getMessage());
baseModelStore = null;
}
}
@@ -142,7 +142,7 @@ private void initializeLicenseModelStore() {
public static ListedLicenses getListedLicenses() {
- ListedLicenses retval = null;
+ ListedLicenses retval;
listedLicenseModificationLock.readLock().lock();
try {
retval = listedLicenses;
@@ -167,7 +167,7 @@ public static ListedLicenses getListedLicenses() {
* Resets all of the cached license information and reloads the license IDs
* NOTE: This method should be used with caution, it will negatively impact
* performance.
- * @return
+ * @return a new instance of this class
*/
public static ListedLicenses resetListedLicenses() {
listedLicenseModificationLock.writeLock().lock();
@@ -199,7 +199,7 @@ public boolean isSpdxListedExceptionId(String exceptionId) {
/**
* @param licenseId SPDX Listed License ID
* @return an SPDX spec version 2 SPDX listed license or null if the ID is not in the SPDX license list
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing error
*/
public SpdxListedLicense getListedLicenseByIdCompatV2(String licenseId) throws InvalidSPDXAnalysisException {
try {
@@ -214,7 +214,7 @@ public SpdxListedLicense getListedLicenseByIdCompatV2(String licenseId) throws I
/**
* @param exceptionId SPDX Listed License Exception ID
* @return an SPDX spec version 2 SPDX listed license exception or null if the ID is not in the SPDX license list
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing error
*/
public org.spdx.library.model.v2.license.ListedLicenseException getListedExceptionByIdCompatV2(String exceptionId) throws InvalidSPDXAnalysisException {
try {
@@ -229,7 +229,7 @@ public org.spdx.library.model.v2.license.ListedLicenseException getListedExcepti
/**
* @param licenseId SPDX Listed License ID
* @return SPDX listed license or null if the ID is not in the SPDX license list
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing error
*/
public ListedLicense getListedLicenseById(String licenseId) throws InvalidSPDXAnalysisException {
try {
@@ -265,7 +265,7 @@ public List getSpdxListedLicenseIds() {
/**
* @return The version of the loaded license list in the form M.N, where M is the major release and N is the minor release.
- * If no license list is loaded, returns {@link org.spdx.storage.listedlicense.SpdxListedLicenseModelStore#DEFAULT_LICENSE_LIST_VERSION}.
+ * If no license list is loaded, returns the default license list version.
*/
public String getLicenseListVersion() {
return this.baseModelStore.getLicenseListVersion();
diff --git a/src/main/java/org/spdx/library/ModelCopyManager.java b/src/main/java/org/spdx/library/ModelCopyManager.java
index 4fb03354..b54cfd0c 100644
--- a/src/main/java/org/spdx/library/ModelCopyManager.java
+++ b/src/main/java/org/spdx/library/ModelCopyManager.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -43,15 +43,16 @@
/**
* This class helps facilitate copying objects from one model to another.
- *
+ *
* In addition to the copy functions (methods), this object keeps track of
* what was copied where so that the same object is not copied twice.
- *
+ *
* This object can be passed into the constructor for ModelObjects to allow the objects to be copied.
*
* @author Gary O'Neall
*
*/
+@SuppressWarnings("unused")
public class ModelCopyManager implements IModelCopyManager {
static final Logger logger = LoggerFactory.getLogger(ModelCopyManager.class);
@@ -60,13 +61,13 @@ public class ModelCopyManager implements IModelCopyManager {
* Map of copied ID's fromModelStore, toModelStore, fromObjectUri, toObjectUri
* Used to keep track of copied ID's to make sure we don't copy them more than once
*/
- private ConcurrentHashMap>> copiedIds =
+ private final ConcurrentHashMap>> copiedIds =
new ConcurrentHashMap<>();
/**
* Map of fromModelStore, toModelStore, fromSpecMajorVersion, toSpecMajorVersion to a converter
*/
- private ConcurrentHashMap>>> spdxConverters = new ConcurrentHashMap<>();
@@ -128,7 +129,7 @@ public boolean canConvert(String fromSpecVersion,
* @param toSpecVersion spec version converting to
* @param create if true, create the spec converter if it does not already exist
* @return a converter for the fromStore fromSpecVersion to the toStore toSpecVersion
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException On SPDX parsing errors
*/
public @Nullable ISpdxConverter getSpecConverter(IModelStore fromStore, IModelStore toStore,
String fromSpecVersion, String toSpecVersion, boolean create) throws InvalidSPDXAnalysisException {
@@ -200,7 +201,8 @@ public boolean canConvert(String fromSpecVersion,
//TODO: Add a creation info and uri prefix
ISpdxConverter previous = toVersionMap.putIfAbsent(toMajorVersion, retval);
if (Objects.nonNull(previous)) {
- retval = previous;
+ //noinspection UnusedAssignment
+ retval = previous;
}
throw new InvalidSPDXAnalysisException("Not completely implemented - need to add creation info");
} else {
@@ -230,7 +232,7 @@ public String putCopiedId(IModelStore fromStore, String fromObjectUri, IModelSto
}
if (toStoreMap.containsKey(fromObjectUri)) {
- logger.warn("Object URI already exists for the originating "+ fromObjectUri);
+ logger.warn("Object URI already exists for the originating {}", fromObjectUri);
}
return toStoreMap.put(fromObjectUri, toObjectUri);
}
@@ -316,14 +318,14 @@ private void copyCompatible(IModelStore toStore, String toObjectUri,
* @param propDescriptor Descriptor for the property
* @param toSpecVersion Version of the SPDX spec the to value complies with
* @param toNamespace Namespace to use if an ID needs to be generated for the to object
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
private void copyIndividualProperty(IModelStore toStore, String toObjectUri, IModelStore fromStore,
String fromObjectUri, PropertyDescriptor propDescriptor,
String toSpecVersion, @Nullable String toNamespace) throws InvalidSPDXAnalysisException {
IModelStoreLock fromStoreLock = fromStore.enterCriticalSection(false);
//Note: we use a write lock since the RDF store may end up creating a property to check if it is a collection
- Optional result = Optional.empty();
+ Optional result;
try {
if (fromStore.isCollectionProperty(fromObjectUri, propDescriptor)) {
throw new InvalidSPDXAnalysisException("Property "+propDescriptor+" is a collection type");
@@ -354,18 +356,18 @@ private void copyIndividualProperty(IModelStore toStore, String toObjectUri, IMo
* @param toStore Model Store to copy to
* @param toObjectUri URI to copy to
* @param fromStore Model Store containing the source item
- * @param fromDocumentUri Object URI to copy from
+ * @param fromObjectUri Object URI to copy from
* @param propDescriptor Descriptor for the property
* @param toSpecVersion Version of the SPDX spec the to value complies with
* @param toNamespace Namespace to use if an ID needs to be generated for the to object
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
private void copyCollectionProperty(IModelStore toStore, String toObjectUri, IModelStore fromStore,
String fromObjectUri, PropertyDescriptor propDescriptor,
String toSpecVersion, @Nullable String toNamespace) throws InvalidSPDXAnalysisException {
IModelStoreLock fromStoreLock = fromStore.enterCriticalSection(false);
//Note: we use a write lock since the RDF store may end up creating a property to check if it is a collection
- Iterator fromListIter = null;
+ Iterator fromListIter;
try {
if (!fromStore.isCollectionProperty(fromObjectUri, propDescriptor)) {
throw new InvalidSPDXAnalysisException("Property "+propDescriptor+" is not a collection type");
@@ -402,7 +404,7 @@ private void copyCollectionProperty(IModelStore toStore, String toObjectUri, IMo
* @param toSpecVersion Version of the SPDX spec the to value complies with
* @param toNamespace Namespace to use if an ID needs to be generated for the to object - must be a unique prefix to the store
* @return Object URI for the copied object
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public TypedValue copy(IModelStore toStore, IModelStore fromStore,
String sourceUri, String toSpecVersion, @Nullable String toNamespace) throws InvalidSPDXAnalysisException {
@@ -422,8 +424,12 @@ public TypedValue copy(IModelStore toStore, IModelStore fromStore,
sourceUriToObjectUri(sourceUri, fromStore.getIdType(sourceUri), toStore, toNamespace);
copy(toStore, toObjectUri, fromStore, sourceUri, toSpecVersion, toNamespace);
}
- return toStore.getTypedValue(toObjectUri).get();
- }
+ Optional retval = toStore.getTypedValue(toObjectUri);
+ if (retval.isPresent()) {
+ return retval.get();
+ }
+ throw new InvalidSPDXAnalysisException("Unable to retrieve typed value from toStore");
+ }
/**
* @param sourceUri source URI copied from
@@ -431,7 +437,7 @@ public TypedValue copy(IModelStore toStore, IModelStore fromStore,
* @param toStore model store to store the copied item
* @param toNamespace namespace for the generated elements for "to"
* @return an object URI suitable for SPDX V3 and later
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
private String sourceUriToObjectUri(String sourceUri, IdType idType, IModelStore toStore,
String toNamespace) throws InvalidSPDXAnalysisException {
@@ -443,7 +449,7 @@ private String sourceUriToObjectUri(String sourceUri, IdType idType, IModelStore
}
if (Objects.isNull(toNamespace) || toNamespace.isEmpty() ||
sourceUri.startsWith(toNamespace)) {
- logger.warn(sourceUri + " already exists - possibly overwriting properties due to a copy from a different model store.");
+ logger.warn("{} already exists - possibly overwriting properties due to a copy from a different model store.", sourceUri);
return sourceUri;
}
switch (idType) {
@@ -464,7 +470,7 @@ private String sourceUriToObjectUri(String sourceUri, IdType idType, IModelStore
* @param toNamespace namespace for the generated elements for "to"
* @param isExternalDocRef true if the type of the value to be copied is an ExternalDocRef
* @return an object URI suitable for SPDX V2
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
private String sourceUriToObjectUriV2Compat(String sourceUri, IdType idType,
IModelStore toStore, String toNamespace, boolean isExternalDocRef) throws InvalidSPDXAnalysisException {
@@ -480,11 +486,9 @@ private String sourceUriToObjectUriV2Compat(String sourceUri, IdType idType,
return sourceUri;
}
String toUri = null;
- if (Objects.nonNull(toNamespace)) {
- int poundIndex = sourceUri.lastIndexOf('#');
- if (poundIndex > 0) {
- toUri = toNamespace + sourceUri.substring(poundIndex + 1);
- }
+ int poundIndex = sourceUri.lastIndexOf('#');
+ if (poundIndex > 0) {
+ toUri = toNamespace + sourceUri.substring(poundIndex + 1);
}
boolean notNullAndNotExists = Objects.nonNull(toUri) && !toStore.exists(toUri); // notExists and nonNull
diff --git a/src/main/java/org/spdx/library/SpdxConversionException.java b/src/main/java/org/spdx/library/SpdxConversionException.java
index 661a5bda..e658456c 100644
--- a/src/main/java/org/spdx/library/SpdxConversionException.java
+++ b/src/main/java/org/spdx/library/SpdxConversionException.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2024 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.
@@ -23,6 +23,7 @@
* @author gary
*
*/
+@SuppressWarnings("unused")
public class SpdxConversionException extends InvalidSPDXAnalysisException {
diff --git a/src/main/java/org/spdx/library/SpdxModelFactory.java b/src/main/java/org/spdx/library/SpdxModelFactory.java
index 4ea1aac5..df291f44 100644
--- a/src/main/java/org/spdx/library/SpdxModelFactory.java
+++ b/src/main/java/org/spdx/library/SpdxModelFactory.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2024 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.
@@ -36,21 +36,22 @@
/**
* Main entrypoint for the SPDX Java Library
- *
+ *
* This is a static class used to manage the different versions of the SPDX spec by
* creating different model classes based on the version of the spec.
- *
+ *
* Since the release of the SPDX spec version 3.0, the Java classes were generated.
- *
+ *
* Each generated set of classes generated for a specific version are in a separate library / Jar file.
- *
+ *
* These generated classes are registered in the Core model registry
- *
+ *
* The inflateModelObject
methods will create an initial object based on the name of the type
*
* @author Gary O'Neall
*
*/
+@SuppressWarnings("unused")
public class SpdxModelFactory {
static {
@@ -108,7 +109,7 @@ public static String getLatestSpecVersion() {
/**
* This static method is a convenience to load this class and initialize the supported model versions.
- *
+ *
* It should be called before using any other functionality from the library
*/
public static void init() {
@@ -127,7 +128,7 @@ public static void init() {
* @param create if true, create the model object ONLY if it does not already exist
* @param idPrefix optional prefix used for any new object URI's created in support of this model object
* @return model object of type type
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public static CoreModelObject inflateModelObject(IModelStore modelStore, String objectUri,
String type, IModelCopyManager copyManager,
@@ -148,7 +149,7 @@ public static CoreModelObject inflateModelObject(IModelStore modelStore, String
* @param create if true, create the model object ONLY if it does not already exist
* @param idPrefix optional prefix used for any new object URI's created in support of this model object
* @return model object of type type
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public static CoreModelObject inflateModelObject(IModelStore modelStore, String objectUri,
String type, IModelCopyManager copyManager, boolean create, @Nullable String idPrefix) throws InvalidSPDXAnalysisException {
@@ -162,7 +163,7 @@ public static CoreModelObject inflateModelObject(IModelStore modelStore, String
* @param type type hint for creating the correct external element
* @param specVersion version of the SPDX spec the object complies with
* @return a java object representing an SPDX element external to model store, collection or document
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public static Object getExternalElement(IModelStore store, String uri,
@Nullable IModelCopyManager copyManager, Class> type,
@@ -176,7 +177,7 @@ public static Object getExternalElement(IModelStore store, String uri,
* @param copyManager if non-null, implicitly copy any referenced properties from other model stores
* @param type type hint for creating the correct external element
* @return a java object representing an SPDX element external to model store, collection or document for the most recent version of the spec supported
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public static Object getExternalElement(IModelStore store, String uri,
@Nullable IModelCopyManager copyManager, Class> type) throws InvalidSPDXAnalysisException {
@@ -211,7 +212,7 @@ public static Object getExternalElement(IModelStore store, String uri,
* @param objectUriPrefixFilter only return objects with URI's starting with this string
* @param idPrefix optional prefix used for any new object URI's created in support of this model object
* @return stream of objects stored in the model store - an object being any non primitive type
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public static Stream> getSpdxObjects(IModelStore store, @Nullable IModelCopyManager copyManager,
@Nullable String typeFilter, @Nullable String objectUriPrefixFilter, @Nullable String idPrefix) throws InvalidSPDXAnalysisException {
diff --git a/src/main/java/org/spdx/library/conversion/ExternalMapInfo.java b/src/main/java/org/spdx/library/conversion/ExternalMapInfo.java
index bf8804ed..b7c60593 100644
--- a/src/main/java/org/spdx/library/conversion/ExternalMapInfo.java
+++ b/src/main/java/org/spdx/library/conversion/ExternalMapInfo.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2024 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.
@@ -38,14 +38,16 @@
* Information about an ExternalMap captured from an ExternalDocumentRef
*
*/
+@SuppressWarnings("unused")
public class ExternalMapInfo {
- private String docRefId;
- private String externalDocumentUri;
- private Optional externalDocumentHash;
- private Collection docImports;
+ private final String docRefId;
+ private final String externalDocumentUri;
+ @SuppressWarnings("OptionalUsedAsFieldOrParameterType")
+ private final Optional externalDocumentHash;
+ private final Collection docImports;
- private Map existingExternalMap = Collections.synchronizedMap(new HashMap<>());
+ private final Map existingExternalMap = Collections.synchronizedMap(new HashMap<>());
/**
* @param docRefId ID of the ExternalDocRef from the SPDX Spec version 2 SPDX Document containing the reference
@@ -53,8 +55,8 @@ public class ExternalMapInfo {
* @param externalDocumentHash Optional Hash of the external SPDX document
* @param docImports SPDX Spec version 3 collection of doc imports
*/
- public ExternalMapInfo(String docRefId, String externalDocumentUri, Optional externalDocumentHash,
- Collection docImports) {
+ public ExternalMapInfo(String docRefId, String externalDocumentUri, @SuppressWarnings("OptionalUsedAsFieldOrParameterType") Optional externalDocumentHash,
+ Collection docImports) {
this.docRefId = docRefId;
this.externalDocumentUri = externalDocumentUri;
this.externalDocumentHash = externalDocumentHash;
diff --git a/src/main/java/org/spdx/library/conversion/ISpdxConverter.java b/src/main/java/org/spdx/library/conversion/ISpdxConverter.java
index fc206f47..10f35622 100644
--- a/src/main/java/org/spdx/library/conversion/ISpdxConverter.java
+++ b/src/main/java/org/spdx/library/conversion/ISpdxConverter.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2024 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.
diff --git a/src/main/java/org/spdx/library/conversion/Spdx2to3Converter.java b/src/main/java/org/spdx/library/conversion/Spdx2to3Converter.java
index c4d454e5..5906b8ae 100644
--- a/src/main/java/org/spdx/library/conversion/Spdx2to3Converter.java
+++ b/src/main/java/org/spdx/library/conversion/Spdx2to3Converter.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2024 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.
@@ -17,16 +17,7 @@
*/
package org.spdx.library.conversion;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Optional;
-import java.util.Set;
-import java.util.StringTokenizer;
+import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -97,11 +88,12 @@
/**
* @author Gary O'Neall
- *
+ *
* Converts SPDX spec version 2.X objects to SPDX spec version 3.X and stores the result in the
* toModelStore
*
*/
+@SuppressWarnings({"OptionalGetWithoutIsPresent", "LoggingSimilarMessage"})
public class Spdx2to3Converter implements ISpdxConverter {
static final Logger logger = LoggerFactory.getLogger(Spdx2to3Converter.class);
@@ -300,11 +292,11 @@ public class Spdx2to3Converter implements ISpdxConverter {
*/
Map, ExternalMapInfo>> docUriToExternalMap = Collections.synchronizedMap(new HashMap<>());
- private IModelCopyManager copyManager;
+ private final IModelCopyManager copyManager;
private int documentIndex = 0;
- private boolean complexLicenses = false;
+ private final boolean complexLicenses;
/**
* @param creationInfoV2 SPDX Spec version 2 creation info
@@ -404,7 +396,7 @@ public static Agent stringToAgent(String spdx2personOrgString, CreationInfo crea
}
return organization;
} else {
- logger.warn("Incorrect person or organization format: " + spdx2personOrgString);
+ logger.warn("Incorrect person or organization format: {}", spdx2personOrgString);
// return a generic Agent
Agent agent = (Agent)SpdxModelClassFactoryV3.getModelObject(creationInfo.getModelStore(),
creationInfo.getIdPrefix() + creationInfo.getModelStore().getNextId(IdType.SpdxId),
@@ -422,8 +414,9 @@ public static Agent stringToAgent(String spdx2personOrgString, CreationInfo crea
* @param toSpecVersion specific spec version to convert to
* @param defaultUriPrefix URI prefix to use when creating new elements
*/
- public Spdx2to3Converter(IModelStore toModelStore, IModelCopyManager copyManager, CreationInfo defaultCreationInfo,
- String toSpecVersion, String defaultUriPrefix) {
+ @SuppressWarnings("unused")
+ public Spdx2to3Converter(IModelStore toModelStore, IModelCopyManager copyManager, CreationInfo defaultCreationInfo,
+ String toSpecVersion, String defaultUriPrefix) {
this(toModelStore, copyManager, defaultCreationInfo, toSpecVersion, defaultUriPrefix, true);
}
@@ -464,8 +457,8 @@ private boolean equivalentCreationInfo(SpdxCreatorInformation spdx2CreatorInfo,
if (!Objects.equals(spdx2CreatorInfo.getCreated(), spdx3CreationInfo.getCreated())) {
return false;
}
- List tools = spdx3CreationInfo.getCreatedUsings().stream().collect(Collectors.toList());
- List agents = spdx3CreationInfo.getCreatedBys().stream().collect(Collectors.toList());
+ List tools = new ArrayList<>(spdx3CreationInfo.getCreatedUsings());
+ List agents = new ArrayList<>(spdx3CreationInfo.getCreatedBys());
for (String creator:spdx2CreatorInfo.getCreators()) {
if (creator.startsWith(SpdxConstantsCompatV2.CREATOR_PREFIX_TOOL)) {
String toolName = creator.substring(SpdxConstantsCompatV2.CREATOR_PREFIX_TOOL.length()).trim();
@@ -573,16 +566,17 @@ public Relationship convertAndStore(org.spdx.library.model.v2.Relationship fromR
org.spdx.library.model.v2.enumerations.RelationshipType fromRelationshipType = fromRelationship.getRelationshipType();
LifecycleScopeType scope = LIFECYCLE_SCOPE_MAP.get(fromRelationshipType);
String fromUri = fromRelationship.getObjectUri();
- Optional existing = getExistingObject(fromUri,
- Objects.isNull(scope) ? SpdxConstantsV3.CORE_RELATIONSHIP : SpdxConstantsV3.CORE_LIFECYCLE_SCOPED_RELATIONSHIP);
+ String relationshipType = Objects.isNull(scope) ? SpdxConstantsV3.CORE_RELATIONSHIP : SpdxConstantsV3.CORE_LIFECYCLE_SCOPED_RELATIONSHIP;
+ Optional existing = getExistingObject(fromUri,
+ relationshipType);
if (existing.isPresent()) {
return (Relationship)existing.get();
}
String toObjectUri = defaultUriPrefix + toModelStore.getNextId(IdType.SpdxId);
String exitingUri = alreadyConverted.putIfAbsent(fromUri, toObjectUri);
if (Objects.nonNull(exitingUri)) {
- return (Relationship)getExistingObject(fromUri,
- Objects.isNull(scope) ? SpdxConstantsV3.CORE_RELATIONSHIP : SpdxConstantsV3.CORE_LIFECYCLE_SCOPED_RELATIONSHIP).get();
+ return (Relationship)getExistingObject(fromUri,
+ relationshipType).get();
}
Relationship toRelationship;
if (Objects.isNull(scope)) {
@@ -682,7 +676,7 @@ public SpdxDocument convertAndStore(org.spdx.library.model.v2.SpdxDocument fromD
toDoc.getNamespaceMaps().add(convertAndStore(externalDocRef, toDoc.getSpdxImports()));
}
convertElementProperties(fromDoc, toDoc);
- if (!equivalentCreationInfo(fromDoc.getCreationInfo(), defaultCreationInfo)) {
+ if (!equivalentCreationInfo(Objects.requireNonNull(fromDoc.getCreationInfo()), defaultCreationInfo)) {
toDoc.setCreationInfo(convertCreationInfo(fromDoc.getCreationInfo(), this.toModelStore, this.defaultUriPrefix));
}
toDoc.setDataLicense(convertAndStore(fromDoc.getDataLicense()));
@@ -947,7 +941,7 @@ public LicenseAddition convertAndStore(org.spdx.library.model.v2.license.License
/**
* Convert and add properties from the fromException to the toAddition
* @param fromException SPDX spec verion 2 LicenseException to copy properties from
- * @param toAddtion SPDX spec version 3 LicenseAddition to copy properties to
+ * @param toAddition SPDX spec version 3 LicenseAddition to copy properties to
* @throws InvalidSPDXAnalysisException on any errors converting
*/
private void convertLicenseAdditionProperties(
@@ -1047,8 +1041,7 @@ public AnyLicenseInfo convertAndStore(org.spdx.library.model.v2.license.AnyLicen
return convertAndStore((org.spdx.library.model.v2.license.DisjunctiveLicenseSet)fromLicense);
} else if (fromLicense instanceof org.spdx.library.model.v2.license.ExternalExtractedLicenseInfo) {
String externalUri = ((org.spdx.library.model.v2.license.ExternalExtractedLicenseInfo)fromLicense).getIndividualURI();
- logger.warn("Referencing an external SPDX 2 element with URI " + externalUri +
- " while converting from SPDX 2 to 3");
+ logger.warn("Referencing an external SPDX 2 element with URI {} while converting from SPDX 2 to 3", externalUri);
addExternalMapInfo(externalUri);
return new ExternalCustomLicense(externalUri);
} else if (fromLicense instanceof org.spdx.library.model.v2.license.ExtractedLicenseInfo) {
@@ -1086,8 +1079,7 @@ public Element convertAndStore(org.spdx.library.model.v2.SpdxElement fromElement
return new NoneElement();
} else if (fromElement instanceof org.spdx.library.model.v2.ExternalSpdxElement) {
String externalUri = ((org.spdx.library.model.v2.ExternalSpdxElement)fromElement).getIndividualURI();
- logger.warn("Referencing an external SPDX 2 element with URI " + externalUri +
- " while converting from SPDX 2 to 3");
+ logger.warn("Referencing an external SPDX 2 element with URI {} while converting from SPDX 2 to 3", externalUri);
addExternalMapInfo(externalUri);
return new ExternalElement(externalUri);
} else if (fromElement instanceof org.spdx.library.model.v2.SpdxDocument) {
@@ -1106,12 +1098,12 @@ private void addExternalMapInfo(String externalUri) throws InvalidSPDXAnalysisEx
Objects.requireNonNull(externalUri, "External URI can not be null");
String[] parts = externalUri.split("#");
if (parts.length != 2) {
- logger.warn(externalUri + " is not a valid SPDX Spec version 2 external referenced - should have a document uri + '#' + ID");
+ logger.warn("{} is not a valid SPDX Spec version 2 external referenced - should have a document uri + '#' + ID", externalUri);
return;
}
Map, ExternalMapInfo> externalMapMap = docUriToExternalMap.get(parts[0]);
if (Objects.isNull(externalMapMap)) {
- logger.warn("No corresponding ExternalDocumentRefs for "+externalUri);
+ logger.warn("No corresponding ExternalDocumentRefs for {}", externalUri);
return;
}
synchronized(externalMapMap) {
@@ -1153,10 +1145,8 @@ public SpdxFile convertAndStore(org.spdx.library.model.v2.SpdxFile spdxFile) thr
convertAndAddFileType(fileType, toFile);
}
Optional noticeText = spdxFile.getNoticeText();
-
- if (noticeText.isPresent()) {
- toFile.getAttributionTexts().add(noticeText.get());
- }
+
+ noticeText.ifPresent(s -> toFile.getAttributionTexts().add(s));
// - this is already captured in the checksums - String sha1 = spdxFile.getSha1();
return toFile;
}
@@ -1238,7 +1228,7 @@ private void convertItemProperties(org.spdx.library.model.v2.SpdxItem fromItem,
Optional licenseComments = fromItem.getLicenseComments();
if (licenseComments.isPresent()) {
Optional existingComment = toArtifact.getComment();
- toArtifact.setComment(existingComment.isPresent() ? existingComment.get() + ";" + licenseComments.get() : licenseComments.get());
+ toArtifact.setComment(existingComment.map(s -> s + ";" + licenseComments.get()).orElseGet(licenseComments::get));
}
org.spdx.library.model.v2.license.AnyLicenseInfo concludedLicense = fromItem.getLicenseConcluded();
if (Objects.nonNull(concludedLicense)) {
@@ -1354,7 +1344,7 @@ public IntegrityMethod convertAndStore(
* @param fileName Name of the File artifact
* @param toPackage package to add the file to
* @param fileChecksums checksums for the file
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
private void addPackageFileNameToPackage(String fileName,
SpdxPackage toPackage, Collection fileChecksums) throws InvalidSPDXAnalysisException {
@@ -1474,19 +1464,21 @@ public Snippet convertAndStore(org.spdx.library.model.v2.SpdxSnippet fromSnippet
convertItemProperties(fromSnippet, toSnippet);
org.spdx.library.model.v2.pointer.StartEndPointer fromByteRange = fromSnippet.getByteRange();
if (Objects.nonNull(fromByteRange)) {
- toSnippet.setByteRange(toSnippet.createPositiveIntegerRange(toModelStore.getNextId(IdType.Anonymous))
+ //noinspection DataFlowIssue
+ toSnippet.setByteRange(toSnippet.createPositiveIntegerRange(toModelStore.getNextId(IdType.Anonymous))
.setBeginIntegerRange(((org.spdx.library.model.v2.pointer.ByteOffsetPointer)fromByteRange.getStartPointer()).getOffset())
.setEndIntegerRange(((org.spdx.library.model.v2.pointer.ByteOffsetPointer)fromByteRange.getEndPointer()).getOffset())
.build());
}
Optional fromLineRange = fromSnippet.getLineRange();
if (fromLineRange.isPresent()) {
- toSnippet.setLineRange(toSnippet.createPositiveIntegerRange(toModelStore.getNextId(IdType.Anonymous))
+ //noinspection DataFlowIssue
+ toSnippet.setLineRange(toSnippet.createPositiveIntegerRange(toModelStore.getNextId(IdType.Anonymous))
.setBeginIntegerRange(((org.spdx.library.model.v2.pointer.LineCharPointer)fromLineRange.get().getStartPointer()).getLineNumber())
.setEndIntegerRange(((org.spdx.library.model.v2.pointer.LineCharPointer)fromLineRange.get().getEndPointer()).getLineNumber())
.build());
}
- toSnippet.setSnippetFromFile(convertAndStore(fromSnippet.getSnippetFromFile()));
+ toSnippet.setSnippetFromFile(convertAndStore(Objects.requireNonNull(fromSnippet.getSnippetFromFile())));
return toSnippet;
}
}
diff --git a/src/main/java/org/spdx/storage/listedlicense/CrossRefJson.java b/src/main/java/org/spdx/storage/listedlicense/CrossRefJson.java
index ed2c924a..b0764920 100644
--- a/src/main/java/org/spdx/storage/listedlicense/CrossRefJson.java
+++ b/src/main/java/org/spdx/storage/listedlicense/CrossRefJson.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2020 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.
@@ -21,7 +21,6 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
-import java.util.Optional;
import javax.annotation.Nullable;
@@ -37,7 +36,8 @@
* @author Gary O'Neall
*
*/
-class CrossRefJson {
+@SuppressWarnings("unused")
+public class CrossRefJson {
public String match;
public String url;
@@ -54,45 +54,24 @@ public CrossRefJson() {
/**
* @param crossRef cross ref to copy values from
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public CrossRefJson(CrossRef crossRef) throws InvalidSPDXAnalysisException {
this.id = crossRef.getId();
- Optional fromMatch = crossRef.getMatch();
- if (fromMatch.isPresent()) {
- match = fromMatch.get();
- }
- Optional fromUrl = crossRef.getUrl();
- if (fromUrl.isPresent()) {
- url = fromUrl.get();
- }
- Optional fromIsValid = crossRef.getValid();
- if (fromIsValid.isPresent()) {
- isValid = fromIsValid.get();
- }
- Optional fromIsLive = crossRef.getLive();
- if (fromIsLive.isPresent()) {
- isLive = fromIsLive.get();
- }
- Optional fromIsWayBackLink = crossRef.getIsWayBackLink();
- if (fromIsWayBackLink.isPresent()) {
- isWayBackLink = fromIsWayBackLink.get();
- }
- Optional fromTimestamp = crossRef.getTimestamp();
- if (fromTimestamp.isPresent()) {
- timestamp = fromTimestamp.get();
- }
- Optional fromOrder = crossRef.getOrder();
- if (fromOrder.isPresent()) {
- order = fromOrder.get();
- }
+ crossRef.getMatch().ifPresent(s -> match = s);
+ crossRef.getUrl().ifPresent(s -> url = s);
+ crossRef.getValid().ifPresent(aBoolean -> isValid = aBoolean);
+ crossRef.getLive().ifPresent(aBoolean -> isLive = aBoolean);
+ crossRef.getIsWayBackLink().ifPresent(aBoolean -> isWayBackLink = aBoolean);
+ crossRef.getTimestamp().ifPresent(s -> timestamp = s);
+ crossRef.getOrder().ifPresent(integer -> order = integer);
}
/**
* @return all valid property descriptors
*/
public List getPropertyValueDescriptors() {
- List retval = new ArrayList();
+ List retval = new ArrayList<>();
if (Objects.nonNull(match)) {
retval.add(new PropertyDescriptor("match", SpdxConstantsCompatV2.SPDX_NAMESPACE));
}
@@ -119,9 +98,9 @@ public List getPropertyValueDescriptors() {
/**
* Sets the value to the property name
- * @param propertyDescriptor
- * @param value
- * @throws InvalidSpdxPropertyException
+ * @param propertyDescriptor descriptor for the property to set
+ * @param value Value to set
+ * @throws InvalidSpdxPropertyException on SPDX parsing errors
*/
public void setPrimativeValue(PropertyDescriptor propertyDescriptor, Object value) throws InvalidSpdxPropertyException {
switch (propertyDescriptor.getName()) {
@@ -185,18 +164,18 @@ public void setId(String crossRefId) {
}
/**
- * @param propertyDescriptor
+ * @param propertyDescriptor descriptor for the property to set
* @return the list associated with the property
- * @throws InvalidSpdxPropertyException
+ * @throws InvalidSpdxPropertyException on SPDX parsing errors
*/
public List> getValueList(PropertyDescriptor propertyDescriptor) throws InvalidSpdxPropertyException {
throw new InvalidSpdxPropertyException(propertyDescriptor + " is not a list type.");
}
/**
- * @param propertyDescriptor
+ * @param propertyDescriptor descriptor for the property to set
* @return the value associated with the property - null if not assigned or not present
- * @throws InvalidSpdxPropertyException
+ * @throws InvalidSpdxPropertyException on SPDX parsing errors
*/
public @Nullable Object getValue(PropertyDescriptor propertyDescriptor) throws InvalidSpdxPropertyException {
switch (propertyDescriptor.getName()) {
@@ -213,8 +192,8 @@ public List> getValueList(PropertyDescriptor propertyDescriptor) throws Invali
/**
* sets the property to null (no way to remove in this store)
- * @param propertyDescriptor
- * @throws InvalidSpdxPropertyException
+ * @param propertyDescriptor descriptor for the property to set
+ * @throws InvalidSpdxPropertyException on SPDX parsing errors
*/
public void removeProperty(PropertyDescriptor propertyDescriptor) throws InvalidSpdxPropertyException {
switch (propertyDescriptor.getName()) {
@@ -230,8 +209,8 @@ public void removeProperty(PropertyDescriptor propertyDescriptor) throws Invalid
}
/**
- * @param propertyDescriptor
- * @param clazz
+ * @param propertyDescriptor descriptor for the property to set
+ * @param clazz target class
* @return true if the members can be assigned from clazz
*/
public boolean isCollectionMembersAssignableTo(PropertyDescriptor propertyDescriptor, Class> clazz) {
@@ -239,10 +218,10 @@ public boolean isCollectionMembersAssignableTo(PropertyDescriptor propertyDescri
}
/**
- * @param propertyDescriptor
- * @param clazz
+ * @param propertyDescriptor descriptor for the property to set
+ * @param clazz target class
* @return true if the property can be assigned from clazz
- * @throws InvalidSpdxPropertyException
+ * @throws InvalidSpdxPropertyException on SPDX parsing errors
*/
public boolean isPropertyValueAssignableTo(PropertyDescriptor propertyDescriptor, Class> clazz) throws InvalidSpdxPropertyException {
switch (propertyDescriptor.getName()) {
@@ -259,8 +238,8 @@ public boolean isPropertyValueAssignableTo(PropertyDescriptor propertyDescriptor
}
/**
- * @param propertyName
- * @return if the property is a colloection
+ * @param propertyName Name of the property
+ * @return if the property is a collection
*/
public boolean isCollectionProperty(String propertyName) {
return false;
diff --git a/src/main/java/org/spdx/storage/listedlicense/ExceptionJson.java b/src/main/java/org/spdx/storage/listedlicense/ExceptionJson.java
index 60bb4a9c..ff712820 100644
--- a/src/main/java/org/spdx/storage/listedlicense/ExceptionJson.java
+++ b/src/main/java/org/spdx/storage/listedlicense/ExceptionJson.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -37,12 +37,13 @@
/**
* Simple POJO to hold the license exception data loaded from a JSON file
- *
+ *
* Licenses in the JSON format can be found at spdx.org/licenses/[exceptionid].json
*
* @author Gary O'Neall
*
*/
+@SuppressWarnings("unused")
public class ExceptionJson {
/**
@@ -78,7 +79,6 @@ public class ExceptionJson {
descriptorsToValue.put(SpdxConstantsCompatV2.PROP_LIC_DEPRECATED_VERSION, "deprecatedVersion");
descriptorsToValue.put(SpdxConstantsV3.PROP_COMMENT, "comment");
descriptorsToValue.put(SpdxConstantsCompatV2.RDFS_PROP_COMMENT, "comment");
- descriptorsToValue.put(SpdxConstantsCompatV2.PROP_LICENSE_EXCEPTION_ID, "licenseExceptionId");
descriptorsToValue.put(SpdxConstantsV3.PROP_SEE_ALSO, "seeAlso");
collectionProperties.add(SpdxConstantsV3.PROP_SEE_ALSO);
descriptorsToValue.put(SpdxConstantsCompatV2.RDFS_PROP_SEE_ALSO, "seeAlso");
@@ -261,7 +261,7 @@ public void addValueToList(String propertyName, String valueId, String type) thr
* @param propertyDescriptor descriptor for the property
* @param value Value to set
* @return true if the value was added
- * @throws InvalidSpdxPropertyException
+ * @throws InvalidSpdxPropertyException on SPDX parsing errors
*/
public boolean addPrimitiveValueToList(PropertyDescriptor propertyDescriptor, Object value) throws InvalidSpdxPropertyException {
if (!"seeAlso".equals(PROPERTY_DESCRIPTOR_TO_VALUE_NAME.get(propertyDescriptor))) {
@@ -363,7 +363,7 @@ public void copyFrom(ListedLicenseException fromException) throws InvalidSPDXAna
this.licenseExceptionTemplate = fromException.getStandardAdditionTemplate().orElse(null);
this.licenseExceptionText = fromException.getAdditionText();
this.name = fromException.getName().orElse(null);
- this.seeAlso = new ArrayList(fromException.getSeeAlsos());
+ this.seeAlso = new ArrayList<>(fromException.getSeeAlsos());
this.obsoletedBy = fromException.getObsoletedBy().orElse(null);
this.listVersionAdded = fromException.getListVersionAdded().orElse(null);
this.licenseXml = fromException.getLicenseXml().orElse(null);
@@ -403,7 +403,7 @@ public void copyFrom(org.spdx.library.model.v2.license.ListedLicenseException fr
if (Objects.nonNull(this.name) && this.name.isEmpty()) {
this.name = null;
}
- this.seeAlso = new ArrayList(fromException.getSeeAlso());
+ this.seeAlso = new ArrayList<>(fromException.getSeeAlso());
this.exceptionTextHtml = fromException.getExceptionTextHtml();
if (Objects.nonNull(this.exceptionTextHtml) && this.exceptionTextHtml.isEmpty()) {
this.exceptionTextHtml = null;
@@ -420,7 +420,8 @@ public boolean removePrimitiveValueToList(PropertyDescriptor propertyDescriptor,
if (!"seeAlso".equals(PROPERTY_DESCRIPTOR_TO_VALUE_NAME.get(propertyDescriptor))) {
throw new InvalidSpdxPropertyException(propertyDescriptor + "is not a list type");
}
- return seeAlso.remove(value);
+ //noinspection SuspiciousMethodCalls
+ return seeAlso.remove(value);
}
/**
diff --git a/src/main/java/org/spdx/storage/listedlicense/ExceptionJsonTOC.java b/src/main/java/org/spdx/storage/listedlicense/ExceptionJsonTOC.java
index a5ed8de8..63761565 100644
--- a/src/main/java/org/spdx/storage/listedlicense/ExceptionJsonTOC.java
+++ b/src/main/java/org/spdx/storage/listedlicense/ExceptionJsonTOC.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -36,7 +36,7 @@
*
*/
public class ExceptionJsonTOC {
- static class ExceptionJson {
+ public static class ExceptionJson {
private String reference;
private boolean isDeprecatedLicenseId;
private String detailsUrl;
@@ -132,7 +132,7 @@ public void setSeeAlso(List seeAlso) {
private String licenseListVersion;
- private List exceptions;
+ private final List exceptions;
private String releaseDate;
/**
@@ -174,9 +174,6 @@ public List getExceptions() {
*/
public Map getExceptionIds() {
Map retval = new HashMap<>();
- if (exceptions == null) {
- return retval;
- }
for (ExceptionJson licenseException:exceptions) {
retval.put(licenseException.licenseExceptionId.toLowerCase(), licenseException.licenseExceptionId);
}
@@ -214,11 +211,7 @@ public void addException(ListedLicenseException exception, String exceptionHTMLR
}
referenceNumber++;
ej.setReferenceNumber(referenceNumber);
- List seeAlso = new ArrayList<>();
- for (String sa:exception.getSeeAlso()) {
- seeAlso.add(sa);
- }
- ej.setSeeAlso(seeAlso);
+ ej.setSeeAlso(new ArrayList<>(exception.getSeeAlso()));
this.exceptions.add(ej);
}
diff --git a/src/main/java/org/spdx/storage/listedlicense/IListedLicenseStore.java b/src/main/java/org/spdx/storage/listedlicense/IListedLicenseStore.java
index e3f3900a..4b79da4c 100644
--- a/src/main/java/org/spdx/storage/listedlicense/IListedLicenseStore.java
+++ b/src/main/java/org/spdx/storage/listedlicense/IListedLicenseStore.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -63,12 +63,12 @@ public interface IListedLicenseStore extends IModelStore {
/**
* @param licenseId case insensitive license ID
- * @return the case sensitive license ID
+ * @return the case-sensitive license ID
*/
Optional listedLicenseIdCaseSensitive(String licenseId);
/**
- * @param exceptionId case insensitive exception ID
+ * @param exceptionId case-insensitive exception ID
* @return case sensitive ID
*/
Optional listedExceptionIdCaseSensitive(String exceptionId);
diff --git a/src/main/java/org/spdx/storage/listedlicense/LicenseCreationInfo.java b/src/main/java/org/spdx/storage/listedlicense/LicenseCreationInfo.java
index 44cc24a0..46b3c036 100644
--- a/src/main/java/org/spdx/storage/listedlicense/LicenseCreationInfo.java
+++ b/src/main/java/org/spdx/storage/listedlicense/LicenseCreationInfo.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2024 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.
@@ -19,7 +19,6 @@
import java.text.SimpleDateFormat;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
@@ -57,12 +56,12 @@ public class LicenseCreationInfo {
ptosv.put(SpdxConstantsV3.PROP_SPEC_VERSION, SpdxConstantsV3.MODEL_SPEC_VERSION);
PROPERTY_TO_STATIC_VALUE = Collections.unmodifiableMap(ptosv);
ALL_PROPERTY_DESCRIPTORS = Collections.unmodifiableList(new ArrayList<>(ptosv.keySet()));
- };
-
- private static List EMPTY = Collections.unmodifiableList(new ArrayList<>());
+ }
+
+ private static final List EMPTY = Collections.unmodifiableList(new ArrayList<>());
- private String created;
- private List creators;
+ private final String created;
+ private final List creators;
TypedValue typedValue;
@@ -77,7 +76,7 @@ public LicenseCreationInfo(LicenseCreatorAgent licenseListCreator,
String licenseListReleaseDate) throws SpdxInvalidIdException, SpdxInvalidTypeException, ModelRegistryException {
this.created = Pattern.matches("^\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\dZ$", licenseListReleaseDate) ?
licenseListReleaseDate : new SimpleDateFormat(SpdxConstantsCompatV2.SPDX_DATE_FORMAT).format(new Date());
- this.creators = Collections.unmodifiableList(Arrays.asList(licenseListCreator.getTypedValue()));
+ this.creators = Collections.singletonList(licenseListCreator.getTypedValue());
this.typedValue = new TypedValue(LicenseCreationInfo.CREATION_INFO_URI, SpdxConstantsV3.CORE_CREATION_INFO, SpdxConstantsV3.MODEL_SPEC_VERSION);
}
@@ -89,7 +88,7 @@ public TypedValue getTypedValue() {
}
/**
- * @param propertyDescriptor
+ * @param propertyDescriptor descriptor for the property
* @return true if it is a collection property
*/
public boolean isCollectionProperty(PropertyDescriptor propertyDescriptor) {
diff --git a/src/main/java/org/spdx/storage/listedlicense/LicenseCreatorAgent.java b/src/main/java/org/spdx/storage/listedlicense/LicenseCreatorAgent.java
index 056bfc23..5be83445 100644
--- a/src/main/java/org/spdx/storage/listedlicense/LicenseCreatorAgent.java
+++ b/src/main/java/org/spdx/storage/listedlicense/LicenseCreatorAgent.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2024 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.
@@ -38,6 +38,7 @@
* Storage for the creator agent of the license list
*
*/
+@SuppressWarnings("unused")
public class LicenseCreatorAgent {
static final String OBJECT_URI_PREFIX = "https://spdx.org/licenses/creatoragent/";
@@ -46,9 +47,9 @@ public class LicenseCreatorAgent {
static final List EMPTY = Collections.unmodifiableList(new ArrayList<>());
static final String NAME = "SPDX Legal Team";
static final String DESCRIPTION = "This object is created and maintained by the SPDX legal team (https://spdx.dev/engage/participate/legal-team/)";
- private String objectUri;
- private TypedValue typedValue;
- private TypedValue creationInfoTV;
+ private final String objectUri;
+ private final TypedValue typedValue;
+ private final TypedValue creationInfoTV;
public LicenseCreatorAgent(String licenseListVersion) throws SpdxInvalidIdException, SpdxInvalidTypeException, ModelRegistryException {
this.objectUri = OBJECT_URI_PREFIX + licenseListVersion.replace('.','_');
@@ -61,24 +62,24 @@ public String getObjectUri() {
}
/**
- * @return
+ * @return the TypedValue
*/
public TypedValue getTypedValue() {
return this.typedValue;
}
/**
- * @param propertyDescriptor
- * @return
+ * @param propertyDescriptor descriptor for the property
+ * @return all values for the property
*/
public List> getValueList(PropertyDescriptor propertyDescriptor) {
return EMPTY;
}
/**
- * @param propertyDescriptor
+ * @param propertyDescriptor descriptor for the property
* @return value if present, otherwise null
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public Object getValue(PropertyDescriptor propertyDescriptor) throws InvalidSPDXAnalysisException {
if (SpdxConstantsV3.PROP_CREATION_INFO.equals(propertyDescriptor)) {
@@ -93,9 +94,9 @@ public Object getValue(PropertyDescriptor propertyDescriptor) throws InvalidSPDX
}
/**
- * @param propertyDescriptor
- * @param clazz
- * @return
+ * @param propertyDescriptor descriptor for the property
+ * @param clazz target class
+ * @return true if the collection members can be assigned to the class
*/
public boolean isCollectionMembersAssignableTo(
PropertyDescriptor propertyDescriptor, Class> clazz) {
@@ -117,9 +118,9 @@ public boolean isCollectionMembersAssignableTo(
}
/**
- * @param propertyDescriptor
- * @param clazz
- * @return
+ * @param propertyDescriptor descriptor for the property
+ * @param clazz target class
+ * @return true if the property can be assigned to the class
*/
public boolean isPropertyValueAssignableTo(
PropertyDescriptor propertyDescriptor, Class> clazz) {
@@ -131,8 +132,8 @@ public boolean isPropertyValueAssignableTo(
}
/**
- * @param propertyDescriptor
- * @return
+ * @param propertyDescriptor descriptor for the property
+ * @return true if the property is a collection
*/
public boolean isCollectionProperty(PropertyDescriptor propertyDescriptor) {
return false;
diff --git a/src/main/java/org/spdx/storage/listedlicense/LicenseJson.java b/src/main/java/org/spdx/storage/listedlicense/LicenseJson.java
index a36c9836..78e205b4 100644
--- a/src/main/java/org/spdx/storage/listedlicense/LicenseJson.java
+++ b/src/main/java/org/spdx/storage/listedlicense/LicenseJson.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -38,12 +38,13 @@
/**
* Simple POJO to hold the license data loaded from a JSON file
- *
+ *
* Licenses in the JSON format can be found at spdx.org/licenses/[licenseid].json
*
* @author Gary O'Neall
*
*/
+@SuppressWarnings("unused")
public class LicenseJson {
static final Map PROPERTY_DESCRIPTOR_TO_VALUE_NAME;
@@ -268,11 +269,11 @@ public void clearPropertyValueList(PropertyDescriptor propertyDescriptor) throws
}
/**
- * Add a cross reference to a value list
- * @param propertyDescriptor
- * @param value
+ * Add a cross-reference to a value list
+ * @param propertyDescriptor descriptor for the property
+ * @param value cross ref value to add
* @return true as specified by Collections.add
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public boolean addCrossRefValueToList(PropertyDescriptor propertyDescriptor, CrossRefJson value) throws InvalidSPDXAnalysisException {
if (SpdxConstantsCompatV2.PROP_CROSS_REF.equals(propertyDescriptor)) {
@@ -284,10 +285,10 @@ public boolean addCrossRefValueToList(PropertyDescriptor propertyDescriptor, Cro
/**
* Add a primitive value to a value list
- * @param propertyDescriptor
- * @param value
+ * @param propertyDescriptor descriptor for the property
+ * @param value value to add to the list
* @return true as specified by Collections.add
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public boolean addPrimitiveValueToList(PropertyDescriptor propertyDescriptor, Object value) throws InvalidSPDXAnalysisException {
String propertyName = PROPERTY_DESCRIPTOR_TO_VALUE_NAME.get(propertyDescriptor);
@@ -309,7 +310,8 @@ public boolean addPrimitiveValueToList(PropertyDescriptor propertyDescriptor, Ob
}
}
- public boolean removePrimitiveValueToList(PropertyDescriptor propertyDescriptor, Object value) throws InvalidSpdxPropertyException {
+ @SuppressWarnings("SuspiciousMethodCalls")
+ public boolean removePrimitiveValueToList(PropertyDescriptor propertyDescriptor, Object value) throws InvalidSpdxPropertyException {
String propertyName = PROPERTY_DESCRIPTOR_TO_VALUE_NAME.get(propertyDescriptor);
if (Objects.isNull(propertyName)) {
throw new InvalidSpdxPropertyException("Invalid property for SPDX listed license:"+propertyDescriptor.getName());
@@ -342,7 +344,7 @@ public List> getValueList(PropertyDescriptor propertyDescriptor) throws Invali
public Object getValue(PropertyDescriptor descriptor) throws InvalidSpdxPropertyException {
String propertyName = PROPERTY_DESCRIPTOR_TO_VALUE_NAME.get(descriptor);
if (Objects.isNull(propertyName)) {
- return null; // unsupport property type
+ return null; // unsupported property type
}
switch (propertyName) {
case "licenseText": return licenseText;
@@ -366,7 +368,7 @@ public Object getValue(PropertyDescriptor descriptor) throws InvalidSpdxProperty
case "licenseXml": return licenseXml;
case "listVersionAdded": return listVersionAdded;
case "obsoletedBy": return obsoletedBy;
- default: return null; // unsupportd property type
+ default: return null; // unsupported property type
}
}
@@ -456,7 +458,7 @@ public void copyFrom(SpdxListedLicense fromLicense) throws InvalidLicenseTemplat
this.name = null;
}
this.isOsiApproved = fromLicense.isOsiApproved();
- this.seeAlso = new ArrayList(fromLicense.getSeeAlso());
+ this.seeAlso = new ArrayList<>(fromLicense.getSeeAlso());
this.standardLicenseHeader = fromLicense.getStandardLicenseHeader();
if (Objects.nonNull(this.standardLicenseHeader) && this.standardLicenseHeader.isEmpty()) {
this.standardLicenseHeader = null;
diff --git a/src/main/java/org/spdx/storage/listedlicense/LicenseJsonTOC.java b/src/main/java/org/spdx/storage/listedlicense/LicenseJsonTOC.java
index decc9257..397af2f4 100644
--- a/src/main/java/org/spdx/storage/listedlicense/LicenseJsonTOC.java
+++ b/src/main/java/org/spdx/storage/listedlicense/LicenseJsonTOC.java
@@ -1,12 +1,12 @@
/**
* Copyright (c) 2018 Source Auditor Inc.
- *
+ *
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -37,7 +37,8 @@
*/
public class LicenseJsonTOC {
- public static class LicenseJson {
+ @SuppressWarnings("unused")
+ public static class LicenseJson {
private String reference;
private boolean isDeprecatedLicenseId;
private String detailsUrl;
@@ -159,7 +160,7 @@ public void setOsiApproved(boolean isOsiApproved) {
private String licenseListVersion;
- private List licenses;
+ private final List licenses;
private String releaseDate;
public LicenseJsonTOC(String version, String releaseDate) {
@@ -193,9 +194,6 @@ public List getLicenses() {
*/
public Map getLicenseIds() {
Map retval = new HashMap<>();
- if (licenses == null) {
- return retval;
- }
for (LicenseJson license:licenses) {
retval.put(license.licenseId.toLowerCase(), license.licenseId);
}
@@ -211,11 +209,11 @@ public String getReleaseDate() {
/**
* Add summary information about a specific license to the licenses list
- * @param license
- * @param licHTMLReference
- * @param licJSONReference
- * @param deprecated
- * @throws InvalidSPDXAnalysisException
+ * @param license license to add
+ * @param licHTMLReference HTML URL reference for the license
+ * @param licJSONReference URL reference to the JSON file
+ * @param deprecated if true, license ID is deprecated
+ * @throws InvalidSPDXAnalysisException on SPDX parsing error
*/
public void addLicense(SpdxListedLicense license, String licHTMLReference, String licJSONReference,
boolean deprecated) throws InvalidSPDXAnalysisException {
@@ -235,11 +233,7 @@ public void addLicense(SpdxListedLicense license, String licHTMLReference, Strin
}
referenceNumber++;
lj.setReferenceNumber(referenceNumber);
- List seeAlso = new ArrayList<>();
- for (String sa:license.getSeeAlso()) {
- seeAlso.add(sa);
- }
- lj.setSeeAlso(seeAlso);
+ lj.setSeeAlso(new ArrayList<>(license.getSeeAlso()));
this.licenses.add(lj);
}
diff --git a/src/main/java/org/spdx/storage/listedlicense/SpdxListedLicenseModelStore.java b/src/main/java/org/spdx/storage/listedlicense/SpdxListedLicenseModelStore.java
index 653a09c3..b726433b 100644
--- a/src/main/java/org/spdx/storage/listedlicense/SpdxListedLicenseModelStore.java
+++ b/src/main/java/org/spdx/storage/listedlicense/SpdxListedLicenseModelStore.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -22,6 +22,7 @@
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
+import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
@@ -56,9 +57,9 @@
/**
* Read-only model store for the SPDX listed licenses
- *
- * License and exception ID's can be case insensitive
- *
+ *
+ * License and exception ID's can be case-insensitive
+ *
* License information is stored in a LicenseJson file with the ID being Listed License ID
* License Exception information is stored in an ExceptionJson file with the ID being the Listed Exception ID
* CrossRef information is stored within the LicenseJson file. Id's are anonymous and generated.
@@ -66,6 +67,7 @@
* @author Gary O'Neall
*
*/
+@SuppressWarnings("LoggingSimilarMessage")
public abstract class SpdxListedLicenseModelStore implements IListedLicenseStore {
static final Logger logger = LoggerFactory.getLogger(SpdxListedLicenseModelStore.class.getName());
@@ -95,23 +97,9 @@ public abstract class SpdxListedLicenseModelStore implements IListedLicenseStore
private int nextId=0;
private final ReadWriteLock listedLicenseModificationLock = new ReentrantReadWriteLock();
- private final IModelStoreLock readLock = new IModelStoreLock() {
-
- @Override
- public void unlock() {
- listedLicenseModificationLock.readLock().unlock();
- }
-
- };
+ private final IModelStoreLock readLock = () -> listedLicenseModificationLock.readLock().unlock();
- private final IModelStoreLock writeLock = new IModelStoreLock() {
-
- @Override
- public void unlock() {
- listedLicenseModificationLock.writeLock().unlock();
- }
-
- };
+ private final IModelStoreLock writeLock = () -> listedLicenseModificationLock.writeLock().unlock();
Gson gson = new Gson(); // we should be able to reuse since all access is within write locks
@@ -134,31 +122,31 @@ public SpdxListedLicenseModelStore() throws InvalidSPDXAnalysisException {
/**
* @return InputStream for the Table of Contents of the licenses formated in JSON SPDX
- * @throws IOException
+ * @throws IOException on IO errors
*/
public abstract InputStream getTocInputStream() throws IOException;
/**
* @return InputStream for the Table of Contents of the exceptions formated in JSON SPDX
- * @throws IOException
+ * @throws IOException on IO errors
*/
public abstract InputStream getExceptionTocInputStream() throws IOException;
/**
* @return InputStream for a license formated in SPDX JSON
- * @throws IOException
+ * @throws IOException on IO errors
*/
public abstract InputStream getLicenseInputStream(String licenseId) throws IOException;
/**
* @return InputStream for an exception formated in SPDX JSON
- * @throws IOException
+ * @throws IOException on IO errors
*/
public abstract InputStream getExceptionInputStream(String exceptionId) throws IOException;
/**
* Loads all license and exception ID's from the appropriate JSON files
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
private void loadIds() throws InvalidSPDXAnalysisException {
listedLicenseModificationLock.writeLock().lock();
@@ -167,12 +155,12 @@ private void loadIds() throws InvalidSPDXAnalysisException {
listedExceptionCache = new HashMap<>();
licenseIds = new HashMap<>(); //Clear the listed license IDs to avoid stale licenses.
//NOTE: This includes deprecated licenses - should this be changed to only return non-deprecated licenses?
- InputStream tocStream = null;
+ InputStream tocStream;
BufferedReader reader = null;
try {
// read the license IDs
tocStream = getTocInputStream();
- reader = new BufferedReader(new InputStreamReader(tocStream, "UTF-8"));
+ reader = new BufferedReader(new InputStreamReader(tocStream, StandardCharsets.UTF_8));
StringBuilder tocJsonStr = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
@@ -185,7 +173,7 @@ private void loadIds() throws InvalidSPDXAnalysisException {
// read the exception ID's
tocStream = getExceptionTocInputStream();
- reader = new BufferedReader(new InputStreamReader(tocStream, "UTF-8"));
+ reader = new BufferedReader(new InputStreamReader(tocStream, StandardCharsets.UTF_8));
tocJsonStr = new StringBuilder();
while((line = reader.readLine()) != null) {
tocJsonStr.append(line);
@@ -251,8 +239,7 @@ private String objectUriToId(String objectUri) throws InvalidSPDXAnalysisExcepti
LicenseCreationInfo.CREATION_INFO_URI.equals(objectUri)) {
id = objectUri;
} else {
- logger.error("Namespace for SPDX listed licenses is expected to be "+
- LISTED_LICENSE_NAMESPACE + ". Supplied URI was "+objectUri);
+ logger.error("Namespace for SPDX listed licenses is expected to be " + LISTED_LICENSE_NAMESPACE + ". Supplied URI was {}", objectUri);
throw new SpdxIdNotFoundException("Namespace for SPDX listed licenses is expected to be "+
LISTED_LICENSE_NAMESPACE + ". Supplied URI was "+objectUri);
}
@@ -275,7 +262,7 @@ public void create(TypedValue typedValue) throws InvalidSPDXAnalysisException {
} else if ((isSpdx3 && SpdxConstantsV3.EXPANDED_LICENSING_LISTED_LICENSE.equals(typedValue.getType())) ||
(!isSpdx3 && SpdxConstantsCompatV2.CLASS_SPDX_LISTED_LICENSE.equals(typedValue.getType()))) {
if (this.licenseIds.containsKey(id.toLowerCase()) || this.exceptionIds.containsKey(id.toLowerCase())) {
- logger.error("Duplicate SPDX ID on create: "+id);
+ logger.error("Duplicate SPDX ID on create: {}", id);
throw new DuplicateSpdxIdException("ID "+id+" already exists.");
}
this.licenseIds.put(id.toLowerCase(), id);
@@ -283,7 +270,7 @@ public void create(TypedValue typedValue) throws InvalidSPDXAnalysisException {
} else if ((isSpdx3 && SpdxConstantsV3.EXPANDED_LICENSING_LISTED_LICENSE_EXCEPTION.equals(typedValue.getType())) ||
(!isSpdx3 && SpdxConstantsCompatV2.CLASS_SPDX_LISTED_LICENSE_EXCEPTION.equals(typedValue.getType()))) {
if (this.licenseIds.containsKey(id.toLowerCase()) || this.exceptionIds.containsKey(id.toLowerCase())) {
- logger.error("Duplicate SPDX ID on create: "+id);
+ logger.error("Duplicate SPDX ID on create: {}", id);
throw new DuplicateSpdxIdException("ID "+id+" already exists.");
}
this.exceptionIds.put(id.toLowerCase(), id);
@@ -322,7 +309,7 @@ public List getPropertyValueDescriptors(String objectUri) th
return crossRefs.get(id).getPropertyValueDescriptors();
// Currently, there is no SPDX 3 support for cross refs
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID. crossRef ID nor a listed exception ID");
}
} finally {
@@ -333,16 +320,16 @@ public List getPropertyValueDescriptors(String objectUri) th
/**
* @param idCaseInsensitive License ID case insensitive
* @return License JSON for the ID - reading from the input stream if needed
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
private LicenseJson fetchLicenseJson(String idCaseInsensitive) throws InvalidSPDXAnalysisException {
String idLowerCase = idCaseInsensitive.toLowerCase();
- String id = null;
+ String id;
listedLicenseModificationLock.readLock().lock();
try {
id = this.licenseIds.get(idLowerCase);
if (Objects.isNull(id)) {
- logger.error("Attemting to get property values on non-existent ID "+idCaseInsensitive);
+ logger.error("Attempting to get property values on non-existent ID {}", idCaseInsensitive);
throw new SpdxIdNotFoundException("ID "+idCaseInsensitive+" not found.");
}
if (this.listedLicenseCache.containsKey(id)) {
@@ -357,7 +344,7 @@ private LicenseJson fetchLicenseJson(String idCaseInsensitive) throws InvalidSPD
// have to retest since we were unlocked
id = this.licenseIds.get(idLowerCase);
if (Objects.isNull(id)) {
- logger.error("Attemting to get property values on non-existent ID "+idCaseInsensitive);
+ logger.error("Attempting to get property values on non-existent ID {}", idCaseInsensitive);
throw new SpdxIdNotFoundException("ID "+idCaseInsensitive+" not found.");
}
if (!this.listedLicenseCache.containsKey(id)) {
@@ -365,7 +352,7 @@ private LicenseJson fetchLicenseJson(String idCaseInsensitive) throws InvalidSPD
BufferedReader reader = null;
try {
jsonStream = getLicenseInputStream(id);
- reader = new BufferedReader(new InputStreamReader(jsonStream, "UTF-8"));
+ reader = new BufferedReader(new InputStreamReader(jsonStream, StandardCharsets.UTF_8));
StringBuilder licenseJsonStr = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
@@ -374,7 +361,7 @@ private LicenseJson fetchLicenseJson(String idCaseInsensitive) throws InvalidSPD
LicenseJson license = gson.fromJson(licenseJsonStr.toString(), LicenseJson.class);
this.listedLicenseCache.put(id, license);
} catch (MalformedURLException e) {
- logger.error("Json license invalid for ID "+id, e);
+ logger.error("Json license invalid for ID {}", id, e);
throw new SpdxListedLicenseException("JSON license URL invalid for ID "+id, e);
} catch (IOException e) {
logger.error("I/O error opening Json license URL", e);
@@ -402,18 +389,18 @@ private LicenseJson fetchLicenseJson(String idCaseInsensitive) throws InvalidSPD
}
/**
- * @param idCaseInsensitive Exception ID case insensitive
+ * @param idCaseInsensitive Exception ID case-insensitive
* @return Exception JSON for the ID - reading from the input stream if needed
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on IO errors
*/
private ExceptionJson fetchExceptionJson(String idCaseInsensitive) throws InvalidSPDXAnalysisException {
String idLower = idCaseInsensitive.toLowerCase();
- String id = null; // case sensitive ID
+ String id; // case sensitive ID
listedLicenseModificationLock.readLock().lock();
try {
id = this.exceptionIds.get(idLower);
if (Objects.isNull(id)) {
- logger.error("Attemting to get property values on non-existent ID "+idCaseInsensitive);
+ logger.error("Attempting to get property values on non-existent ID {}", idCaseInsensitive);
throw new SpdxIdNotFoundException("ID "+idCaseInsensitive+" not found.");
}
if (this.listedExceptionCache.containsKey(id)) {
@@ -428,7 +415,7 @@ private ExceptionJson fetchExceptionJson(String idCaseInsensitive) throws Invali
// have to retest since we were unlocked
id = this.exceptionIds.get(idLower);
if (Objects.isNull(id)) {
- logger.error("Attemting to get property values on non-existent ID "+idCaseInsensitive);
+ logger.error("Attempting to get property values on non-existent ID {}", idCaseInsensitive);
throw new SpdxIdNotFoundException("ID "+idCaseInsensitive+" not found.");
}
if (!this.listedExceptionCache.containsKey(id)) {
@@ -436,7 +423,7 @@ private ExceptionJson fetchExceptionJson(String idCaseInsensitive) throws Invali
BufferedReader reader = null;
try {
jsonStream = getExceptionInputStream(id);
- reader = new BufferedReader(new InputStreamReader(jsonStream, "UTF-8"));
+ reader = new BufferedReader(new InputStreamReader(jsonStream, StandardCharsets.UTF_8));
StringBuilder exceptionJsonStr = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
@@ -445,7 +432,7 @@ private ExceptionJson fetchExceptionJson(String idCaseInsensitive) throws Invali
ExceptionJson exc = gson.fromJson(exceptionJsonStr.toString(), ExceptionJson.class);
this.listedExceptionCache.put(id, exc);
} catch (MalformedURLException e) {
- logger.error("Json license invalid for ID "+id);
+ logger.error("Json license invalid for ID {}", id);
throw new SpdxListedLicenseException("JSON license URL invalid for ID "+id, e);
} catch (IOException e) {
logger.error("I/O error opening Json license URL");
@@ -479,10 +466,10 @@ private ExceptionJson fetchExceptionJson(String idCaseInsensitive) throws Invali
@Override
public void setValue(String objectUri, PropertyDescriptor propertyDescriptor, Object value) throws InvalidSPDXAnalysisException {
if (LicenseCreationInfo.CREATION_INFO_URI.equals(objectUri)) {
- logger.warn("Ignoring the setting of "+propertyDescriptor.getName()+" for license list creation info");
+ logger.warn("Ignoring the setting of {} for license list creation info", propertyDescriptor.getName());
return;
} else if (licenseCreator.getObjectUri().equals(objectUri)) {
- logger.warn("Ignoring the setting of "+propertyDescriptor.getName()+" for license list creator info");
+ logger.warn("Ignoring the setting of {} for license list creator info", propertyDescriptor.getName());
return;
}
String id = objectUriToId(objectUri);
@@ -510,7 +497,7 @@ public void setValue(String objectUri, PropertyDescriptor propertyDescriptor, Ob
} else if (Objects.nonNull(crossRef)) {
crossRef.setPrimativeValue(propertyDescriptor, value);
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
}
@@ -552,7 +539,7 @@ public void clearValueCollection(String objectUri, PropertyDescriptor propertyDe
} else if (Objects.nonNull(crossRef)) {
crossRef.clearPropertyValueList(propertyDescriptor);
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
}
@@ -589,17 +576,17 @@ public boolean addValueToCollection(String objectUri, PropertyDescriptor propert
LicenseJson license = fetchLicenseJson(id);
if (SpdxConstantsCompatV2.PROP_CROSS_REF.equals(propertyDescriptor)) {
if (!(value instanceof TypedValue)) {
- logger.error("Invalid class for CrossRef - expected TypedValue, was supplied type "+value.getClass().toString());
- throw new InvalidSPDXAnalysisException("Invalid type for CrossRef - expected TypedValue, was supplied type "+value.getClass().toString());
+ logger.error("Invalid class for CrossRef - expected TypedValue, was supplied type {}", value.getClass());
+ throw new InvalidSPDXAnalysisException("Invalid type for CrossRef - expected TypedValue, was supplied type "+ value.getClass());
}
TypedValue tv = (TypedValue)value;
if (!SpdxConstantsCompatV2.CLASS_CROSS_REF.equals(tv.getType())) {
- logger.error("Invalid type for CrossRef - expected"+SpdxConstantsCompatV2.CLASS_CROSS_REF+", was supplied type "+value.getClass().toString());
- throw new InvalidSPDXAnalysisException("Invalid type for CrossRef - expected"+SpdxConstantsCompatV2.CLASS_CROSS_REF+", was supplied type "+value.getClass().toString());
+ logger.error("Invalid type for CrossRef - expected" + SpdxConstantsCompatV2.CLASS_CROSS_REF + ", was supplied type {}", value.getClass());
+ throw new InvalidSPDXAnalysisException("Invalid type for CrossRef - expected"+SpdxConstantsCompatV2.CLASS_CROSS_REF+", was supplied type "+ value.getClass());
}
CrossRefJson crj = crossRefs.get(tv.getObjectUri());
if (Objects.isNull(crj)) {
- logger.error("CrossRef with ID "+tv.getObjectUri()+" does not exist in the store.");
+ logger.error("CrossRef with ID {} does not exist in the store.", tv.getObjectUri());
throw new InvalidSPDXAnalysisException("CrossRef with ID "+tv.getObjectUri()+" does not exist in the store.");
}
return license.addCrossRefValueToList(propertyDescriptor, crj);
@@ -612,7 +599,7 @@ public boolean addValueToCollection(String objectUri, PropertyDescriptor propert
} else if (Objects.nonNull(crossRef)) {
return crossRef.addPrimitiveValueToList(propertyDescriptor, value);
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
}
@@ -647,17 +634,17 @@ public boolean removeValueFromCollection(String objectUri, PropertyDescriptor pr
LicenseJson license = fetchLicenseJson(id);
if (SpdxConstantsCompatV2.PROP_CROSS_REF.equals(propertyDescriptor)) {
if (!(value instanceof TypedValue)) {
- logger.error("Invalid class for CrossRef - expected TypedValue, was supplied type "+value.getClass().toString());
- throw new InvalidSPDXAnalysisException("Invalid type for CrossRef - expected TypedValue, was supplied type "+value.getClass().toString());
+ logger.error("Invalid class for CrossRef - expected TypedValue, was supplied type {}", value.getClass());
+ throw new InvalidSPDXAnalysisException("Invalid type for CrossRef - expected TypedValue, was supplied type "+ value.getClass());
}
TypedValue tv = (TypedValue)value;
if (!SpdxConstantsCompatV2.CLASS_CROSS_REF.equals(tv.getType())) {
- logger.error("Invalid type for CrossRef - expected"+SpdxConstantsCompatV2.CLASS_CROSS_REF+", was supplied type "+value.getClass().toString());
- throw new InvalidSPDXAnalysisException("Invalid type for CrossRef - expected"+SpdxConstantsCompatV2.CLASS_CROSS_REF+", was supplied type "+value.getClass().toString());
+ logger.error("Invalid type for CrossRef - expected" + SpdxConstantsCompatV2.CLASS_CROSS_REF + ", was supplied type {}", value.getClass());
+ throw new InvalidSPDXAnalysisException("Invalid type for CrossRef - expected"+SpdxConstantsCompatV2.CLASS_CROSS_REF+", was supplied type "+ value.getClass());
}
CrossRefJson crj = crossRefs.get(tv.getObjectUri());
if (Objects.isNull(crj)) {
- logger.error("CrossRef with ID "+tv.getObjectUri()+" does not exist in the store.");
+ logger.error("CrossRef with ID {} does not exist in the store.", tv.getObjectUri());
throw new InvalidSPDXAnalysisException("CrossRef with ID "+tv.getObjectUri()+" does not exist in the store.");
}
return license.removePrimitiveValueToList(propertyDescriptor, crj);
@@ -670,7 +657,7 @@ public boolean removeValueFromCollection(String objectUri, PropertyDescriptor pr
} else if (Objects.nonNull(crossRef)) {
return crossRef.removePrimitiveValueToList(propertyDescriptor, value);
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
}
@@ -682,9 +669,9 @@ public boolean removeValueFromCollection(String objectUri, PropertyDescriptor pr
@Override
public Iterator listValues(String objectUri, PropertyDescriptor propertyDescriptor) throws InvalidSPDXAnalysisException {
if (LicenseCreationInfo.CREATION_INFO_URI.equals(objectUri)) {
- return ((List)(List>)licenseCreationInfo.getValueList(propertyDescriptor)).iterator();
+ return ((List) licenseCreationInfo.getValueList(propertyDescriptor)).iterator();
} else if (licenseCreator.getObjectUri().equals(objectUri)) {
- return ((List)(List>)licenseCreator.getValueList(propertyDescriptor)).iterator();
+ return ((List) licenseCreator.getValueList(propertyDescriptor)).iterator();
}
String id = objectUriToId(objectUri);
boolean isLicenseId = false;
@@ -704,7 +691,7 @@ public Iterator listValues(String objectUri, PropertyDescriptor property
}
if (isLicenseId) {
LicenseJson license = fetchLicenseJson(id);
- List valueList = (List)(List>)license.getValueList(propertyDescriptor);
+ List valueList = (List) license.getValueList(propertyDescriptor);
if (SpdxConstantsCompatV2.PROP_CROSS_REF.equals(propertyDescriptor)) {
final Iterator crossRefJsonIter = valueList.iterator();
return new Iterator() {
@@ -754,11 +741,11 @@ public Object next() {
}
} else if (isExceptionId) {
ExceptionJson exc = fetchExceptionJson(id);
- return ((List)(List>)exc.getValueList(propertyDescriptor)).iterator();
+ return ((List) exc.getValueList(propertyDescriptor)).iterator();
} else if (Objects.nonNull(crossRef)) {
- return ((List)(List>)crossRef.getValueList(propertyDescriptor)).iterator();
+ return ((List) crossRef.getValueList(propertyDescriptor)).iterator();
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
}
@@ -800,7 +787,7 @@ public Optional getValue(String objectUri, PropertyDescriptor propertyDe
} else if (Objects.nonNull(crossRef)) {
return Optional.ofNullable(crossRef.getValue(propertyDescriptor));
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
}
@@ -813,9 +800,9 @@ public String getNextId(IdType idType) throws InvalidSPDXAnalysisException {
this.listedLicenseModificationLock.writeLock().lock();
try {
if (IdType.Anonymous.equals(idType)) {
- return ANONYMOUS_ID_PREFIX + String.valueOf(this.nextId++);
+ return ANONYMOUS_ID_PREFIX + this.nextId++;
} else {
- return LISTED_LICENSE_NAMESPACE + "/" + "listedLicenseId_" + String.valueOf(this.nextId++);
+ return LISTED_LICENSE_NAMESPACE + "/" + "listedLicenseId_" + this.nextId++;
}
} finally {
this.listedLicenseModificationLock.writeLock().unlock();
@@ -826,9 +813,7 @@ public String getNextId(IdType idType) throws InvalidSPDXAnalysisException {
public List getSpdxListedLicenseIds() {
this.listedLicenseModificationLock.readLock().lock();
try {
- List retval = new ArrayList<>();
- retval.addAll(this.licenseIds.values());
- return retval;
+ return new ArrayList<>(this.licenseIds.values());
} finally {
this.listedLicenseModificationLock.readLock().unlock();
}
@@ -860,17 +845,15 @@ public String getLicenseListReleaseDate() {
public List getSpdxListedExceptionIds() {
this.listedLicenseModificationLock.readLock().lock();
try {
- List retval = new ArrayList<>();
- retval.addAll(this.exceptionIds.values());
- return retval;
+ return new ArrayList<>(this.exceptionIds.values());
} finally {
this.listedLicenseModificationLock.readLock().unlock();
}
}
/**
- * @param listedLicenseDocumentUri
- * @param licenseId
+ * @param listedLicenseDocumentUri Prefix URL for the listed license
+ * @param licenseId license ID
* @return true if the licenseId belongs to an SPDX listed license
*/
public boolean isSpdxListedLicenseId(String listedLicenseDocumentUri, String licenseId) {
@@ -883,8 +866,8 @@ public boolean isSpdxListedLicenseId(String listedLicenseDocumentUri, String lic
}
/**
- * @param listedLicenseDocumentUri
- * @param exceptionId
+ * @param listedLicenseDocumentUri prefix URL for the listed license
+ * @param exceptionId exception ID maintained by the SPDX legal team
* @return true if the exceptionId belongs to an SPDX listed exception
*/
public boolean isSpdxListedExceptionId(String listedLicenseDocumentUri, String exceptionId) {
@@ -926,10 +909,10 @@ public Optional getTypedValue(String objectUri) throws InvalidSPDXAn
@Override
public void removeProperty(String objectUri, PropertyDescriptor propertyDescriptor) throws InvalidSPDXAnalysisException {
if (LicenseCreationInfo.CREATION_INFO_URI.equals(objectUri)) {
- logger.warn("Ignoring remove property "+propertyDescriptor.getName()+" for license list creation info");
+ logger.warn("Ignoring remove property {} for license list creation info", propertyDescriptor.getName());
return;
} else if (licenseCreator.getObjectUri().equals(objectUri)) {
- logger.warn("Ignoring remove property "+propertyDescriptor.getName()+" for license list creator");
+ logger.warn("Ignoring remove property {} for license list creator", propertyDescriptor.getName());
return;
}
String id = objectUriToId(objectUri);
@@ -957,7 +940,7 @@ public void removeProperty(String objectUri, PropertyDescriptor propertyDescript
} else if (Objects.nonNull(crossRef)) {
crossRef.removeProperty(propertyDescriptor);
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
}
@@ -965,10 +948,9 @@ public void removeProperty(String objectUri, PropertyDescriptor propertyDescript
@Override
public Stream getAllItems(String documentUri, @Nullable String typeFilter)
throws InvalidSPDXAnalysisException {
- Objects.requireNonNull(typeFilter, "Type filter can not be null");
listedLicenseModificationLock.writeLock().lock();
try {
- List allItems = new ArrayList();
+ List allItems = new ArrayList<>();
if (SpdxConstantsCompatV2.CLASS_SPDX_LISTED_LICENSE.equals(typeFilter)) {
for (String licenseId:this.licenseIds.values()) {
allItems.add(new TypedValue(licenseId, SpdxConstantsCompatV2.CLASS_SPDX_LISTED_LICENSE, ModelObjectV2.LATEST_SPDX_2_VERSION));
@@ -1005,16 +987,13 @@ public Stream getAllItems(String documentUri, @Nullable String typeF
listedLicenseModificationLock.writeLock().unlock();
}
}
-
-
-
- @SuppressWarnings("unchecked")
+
@Override
public int collectionSize(String objectUri, PropertyDescriptor propertyDescriptor) throws InvalidSPDXAnalysisException {
if (LicenseCreationInfo.CREATION_INFO_URI.equals(objectUri)) {
- return ((List)(List>)licenseCreationInfo.getValueList(propertyDescriptor)).size();
+ return licenseCreationInfo.getValueList(propertyDescriptor).size();
} else if (licenseCreator.getObjectUri().equals(objectUri)) {
- return ((List)(List>)licenseCreator.getValueList(propertyDescriptor)).size();
+ return licenseCreator.getValueList(propertyDescriptor).size();
}
String id = objectUriToId(objectUri);
boolean isLicenseId = false;
@@ -1034,14 +1013,14 @@ public int collectionSize(String objectUri, PropertyDescriptor propertyDescripto
}
if (isLicenseId) {
LicenseJson license = fetchLicenseJson(id);
- return ((List)(List>)license.getValueList(propertyDescriptor)).size();
+ return license.getValueList(propertyDescriptor).size();
} else if (isExceptionId) {
ExceptionJson exc = fetchExceptionJson(id);
- return ((List)(List>)exc.getValueList(propertyDescriptor)).size();
+ return exc.getValueList(propertyDescriptor).size();
} else if (Objects.nonNull(crossRef)) {
- return ((List)(List>)crossRef.getValueList(propertyDescriptor)).size();
+ return crossRef.getValueList(propertyDescriptor).size();
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
}
@@ -1051,9 +1030,9 @@ public int collectionSize(String objectUri, PropertyDescriptor propertyDescripto
public boolean collectionContains(String objectUri, PropertyDescriptor propertyDescriptor, Object value)
throws InvalidSPDXAnalysisException {
if (LicenseCreationInfo.CREATION_INFO_URI.equals(objectUri)) {
- return ((List)(List>)licenseCreationInfo.getValueList(propertyDescriptor)).contains(value);
+ return licenseCreationInfo.getValueList(propertyDescriptor).contains(value);
} else if (licenseCreator.getObjectUri().equals(objectUri)) {
- return ((List)(List>)licenseCreator.getValueList(propertyDescriptor)).contains(value);
+ return licenseCreator.getValueList(propertyDescriptor).contains(value);
}
String id = objectUriToId(objectUri);
boolean isLicenseId = false;
@@ -1073,7 +1052,7 @@ public boolean collectionContains(String objectUri, PropertyDescriptor propertyD
}
if (isLicenseId) {
LicenseJson license = fetchLicenseJson(id);
- List valueList = (List)(List>)license.getValueList(propertyDescriptor);
+ List valueList = (List) license.getValueList(propertyDescriptor);
if (value instanceof TypedValue && SpdxConstantsCompatV2.CLASS_CROSS_REF.equals(((TypedValue)value).getType())) {
CrossRefJson compareValue = crossRefs.get(((TypedValue)value).getObjectUri());
if (Objects.isNull(compareValue)) {
@@ -1086,11 +1065,11 @@ public boolean collectionContains(String objectUri, PropertyDescriptor propertyD
}
} else if (isExceptionId) {
ExceptionJson exc = fetchExceptionJson(id);
- return ((List)(List>)exc.getValueList(propertyDescriptor)).contains(value);
+ return exc.getValueList(propertyDescriptor).contains(value);
} else if (Objects.nonNull(crossRef)) {
- return ((List)(List>)crossRef.getValueList(propertyDescriptor)).contains(value);
+ return crossRef.getValueList(propertyDescriptor).contains(value);
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
}
@@ -1128,7 +1107,7 @@ public boolean isCollectionMembersAssignableTo(String objectUri, PropertyDescrip
} else if (Objects.nonNull(crossRef)) {
return crossRef.isCollectionMembersAssignableTo(propertyDescriptor, clazz);
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
}
@@ -1167,7 +1146,7 @@ public boolean isPropertyValueAssignableTo(String objectUri, PropertyDescriptor
} else if (Objects.nonNull(crossRef)) {
return crossRef.isPropertyValueAssignableTo(propertyDescriptor, clazz);
} else {
- logger.error("ID "+id+" is not a listed license ID, CrossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, CrossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, CrossRef ID nor a listed exception ID");
}
}
@@ -1205,7 +1184,7 @@ public boolean isCollectionProperty(String objectUri, PropertyDescriptor propert
} else if (Objects.nonNull(crossRef)) {
return crossRef.isCollectionProperty(propertyDescriptor.getName());
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
}
@@ -1297,7 +1276,7 @@ public void delete(String objectUri) throws InvalidSPDXAnalysisException {
} else if (crossRefs.containsKey(id)) {
this.crossRefs.remove(id);
} else {
- logger.error("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
+ logger.error("ID {} is not a listed license ID, crossRef ID nor a listed exception ID", id);
throw new SpdxIdNotFoundException("ID "+id+" is not a listed license ID, crossRef ID nor a listed exception ID");
}
} finally {
@@ -1316,6 +1295,6 @@ public CreationInfo getListedLicenseCreationInfo() throws InvalidSPDXAnalysisExc
@Override
public void close() throws Exception {
- // Nothing to do for the either the in-memory or the web store
+ // Nothing to do for either of the in-memory or the web store
}
}
diff --git a/src/main/java/org/spdx/storage/listedlicense/SpdxListedLicenseWebStore.java b/src/main/java/org/spdx/storage/listedlicense/SpdxListedLicenseWebStore.java
index b783a3a3..88a7e7d3 100644
--- a/src/main/java/org/spdx/storage/listedlicense/SpdxListedLicenseWebStore.java
+++ b/src/main/java/org/spdx/storage/listedlicense/SpdxListedLicenseWebStore.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -33,7 +33,7 @@
public class SpdxListedLicenseWebStore extends SpdxListedLicenseModelStore {
/**
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public SpdxListedLicenseWebStore() throws InvalidSPDXAnalysisException {
super();
diff --git a/src/main/java/org/spdx/storage/listedlicense/SpdxV2ListedLicenseModelStore.java b/src/main/java/org/spdx/storage/listedlicense/SpdxV2ListedLicenseModelStore.java
index 6a59c317..81039a50 100644
--- a/src/main/java/org/spdx/storage/listedlicense/SpdxV2ListedLicenseModelStore.java
+++ b/src/main/java/org/spdx/storage/listedlicense/SpdxV2ListedLicenseModelStore.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2024 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.
@@ -66,15 +66,14 @@ public class SpdxV2ListedLicenseModelStore implements IModelStore {
// Exceptions
SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_EXCEPTION_TEXT);
SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_EXCEPTION_TEXT_HTML);
- SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_NAME);
+ // SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_NAME);
SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_LICENSE_EXCEPTION_ID);
SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_EXCEPTION_TEMPLATE);
- SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_EXAMPLE);
- SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_LIC_ID_DEPRECATED);
- SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_LIC_DEPRECATED_VERSION);
- SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.RDFS_PROP_COMMENT);
- SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_LICENSE_EXCEPTION_ID);
- SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.RDFS_PROP_SEE_ALSO);
+ // SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_EXAMPLE);
+ // SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_LIC_ID_DEPRECATED);
+ // SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.PROP_LIC_DEPRECATED_VERSION);
+ // SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.RDFS_PROP_COMMENT);
+ // SUPPORTED_V2_DESCRIPTORS.add(SpdxConstantsCompatV2.RDFS_PROP_SEE_ALSO);
// Crossrefs
SUPPORTED_V2_DESCRIPTORS.add(new PropertyDescriptor("match", SpdxConstantsCompatV2.SPDX_NAMESPACE));
SUPPORTED_V2_DESCRIPTORS.add(new PropertyDescriptor("url", SpdxConstantsCompatV2.SPDX_NAMESPACE));
diff --git a/src/main/java/org/spdx/storage/listedlicense/SpdxV3ListedLicenseModelStore.java b/src/main/java/org/spdx/storage/listedlicense/SpdxV3ListedLicenseModelStore.java
index eb323d44..d87a6ec2 100644
--- a/src/main/java/org/spdx/storage/listedlicense/SpdxV3ListedLicenseModelStore.java
+++ b/src/main/java/org/spdx/storage/listedlicense/SpdxV3ListedLicenseModelStore.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2024 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.
@@ -62,23 +62,23 @@ public class SpdxV3ListedLicenseModelStore implements IModelStore {
SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_ADDITION_TEXT);
SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_STANDARD_ADDITION_TEMPLATE);
SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_IS_DEPRECATED_ADDITION_ID);
- SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_DEPRECATED_VERSION);
- SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_COMMENT);
- SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_SEE_ALSO);
+ // SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_DEPRECATED_VERSION);
+ // SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_COMMENT);
+ // SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_SEE_ALSO);
- SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_LICENSE_XML);
- SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_OBSOLETED_BY);
- SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_LIST_VERSION_ADDED);
+ // SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_LICENSE_XML);
+ // SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_OBSOLETED_BY);
+ // SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_LIST_VERSION_ADDED);
// CreationInfo
- SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_COMMENT);
+ // SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_COMMENT);
SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_CREATED);
SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_CREATED_BY);
SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_SPEC_VERSION);
// Agent
- SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_CREATION_INFO);
- SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_NAME);
+ // SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_CREATION_INFO);
+ // SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_NAME);
SUPPORTED_V3_DESCRIPTORS.add(SpdxConstantsV3.PROP_DESCRIPTION);
// Collections created on initialization
diff --git a/src/main/java/org/spdx/storage/listedlicense/package-info.java b/src/main/java/org/spdx/storage/listedlicense/package-info.java
index 8490547d..679efe2e 100644
--- a/src/main/java/org/spdx/storage/listedlicense/package-info.java
+++ b/src/main/java/org/spdx/storage/listedlicense/package-info.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -17,9 +17,9 @@
*/
/**
* @author Gary O'Neall
- *
+ *
* Storage for SPDX listed licenses.
- *
+ *
* The SpdxListedLicenseModelStore
is the default storage which pull the data from JSON files at spdx.org/licenses
*
* The SpdxListedLicenseLocalModelStore
uses a local copy of the licenses stored in the resources/licenses directory
diff --git a/src/main/java/org/spdx/storage/simple/ExtendedSpdxStore.java b/src/main/java/org/spdx/storage/simple/ExtendedSpdxStore.java
index 028261dc..872f2ded 100644
--- a/src/main/java/org/spdx/storage/simple/ExtendedSpdxStore.java
+++ b/src/main/java/org/spdx/storage/simple/ExtendedSpdxStore.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2020 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.
@@ -31,16 +31,17 @@
/**
* A simple abstract SPDX store that stores everything in an underlying model store which is initialized in the
* constructor.
- *
+ *
* This class can be useful for subclassing and overriding specific methods and/or implementing serialization
* with a choice of underlying message stores.
*
* @author Gary O'Neall
*
*/
+@SuppressWarnings("unused")
public abstract class ExtendedSpdxStore implements IModelStore {
- private IModelStore baseStore;
+ private final IModelStore baseStore;
/**
* @param baseStore store used as the base for this extended SPDX store
diff --git a/src/main/java/org/spdx/storage/simple/InMemSpdxStore.java b/src/main/java/org/spdx/storage/simple/InMemSpdxStore.java
index 89a15bfd..c34ed6e5 100644
--- a/src/main/java/org/spdx/storage/simple/InMemSpdxStore.java
+++ b/src/main/java/org/spdx/storage/simple/InMemSpdxStore.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -48,11 +48,11 @@
/**
* @author Gary O'Neall
- *
+ *
* In memory implementation of an SPDX store.
- *
+ *
* This implementation primarily uses ConcurrentHashMaps
.
- *
+ *
* It is designed to be thread-safe and low CPU utilization. It may use significant amounts of memory
* for larger SPDX documents.
*
@@ -89,23 +89,9 @@ public class InMemSpdxStore implements IModelStore {
private final ReadWriteLock transactionLock = new ReentrantReadWriteLock();
private final ReadWriteLock referenceCountLock = new ReentrantReadWriteLock();
- private final IModelStoreLock readLock = new IModelStoreLock() {
+ private final IModelStoreLock readLock = () -> transactionLock.readLock().unlock();
- @Override
- public void unlock() {
- transactionLock.readLock().unlock();
- }
-
- };
-
- private final IModelStoreLock writeLock = new IModelStoreLock() {
-
- @Override
- public void unlock() {
- transactionLock.writeLock().unlock();
- }
-
- };
+ private final IModelStoreLock writeLock = () -> transactionLock.writeLock().unlock();
public InMemSpdxStore() {
@@ -152,7 +138,8 @@ void updateNextIds(String objectUri) {
Matcher anonRefMatcher = ANON_ID_PATTERN_GENERATED.matcher(objectUri);
if (anonRefMatcher.matches()) {
checkUpdateNextAnonId(anonRefMatcher);
- return;
+ //noinspection UnnecessaryReturnStatement
+ return;
}
}
@@ -208,7 +195,7 @@ private synchronized void checkUpdateNextLicenseId(Matcher licenseRefMatcher) {
* Gets the item from the hashmap
* @param objectUri Anonymous or URI ID
* @return the item from the hash map
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
protected StoredTypedItem getItem(String objectUri) throws InvalidSPDXAnalysisException {
StoredTypedItem item = this.typedValueMap.get(objectUri.toLowerCase());
@@ -308,8 +295,8 @@ public Iterator listValues(String objectUri, PropertyDescriptor property
public Optional getValue(String objectUri, PropertyDescriptor propertyDescriptor) throws InvalidSPDXAnalysisException {
StoredTypedItem item = getItem(objectUri);
if (item.isCollectionProperty(propertyDescriptor)) {
- logger.warn("Returning a collection for a getValue call for property "+propertyDescriptor.getName());
- return Optional.of(new ModelCollection(this, objectUri, propertyDescriptor, null, null, item.getSpecVersion(), null));
+ logger.warn("Returning a collection for a getValue call for property {}", propertyDescriptor.getName());
+ return Optional.of(new ModelCollection<>(this, objectUri, propertyDescriptor, null, null, item.getSpecVersion(), null));
} else {
return Optional.ofNullable(item.getValue(propertyDescriptor));
}
@@ -319,12 +306,12 @@ public Optional getValue(String objectUri, PropertyDescriptor propertyDe
public synchronized String getNextId(IdType idType) throws InvalidSPDXAnalysisException {
switch (idType) {
//TODO: Move the compat constants into it's own constants file
- case Anonymous: return ANON_PREFIX+GENERATED+String.valueOf(nextAnonId++);
- case LicenseRef: return SpdxConstantsCompatV2.NON_STD_LICENSE_ID_PRENUM+GENERATED+String.valueOf(nextNextLicenseId++);
- case DocumentRef: return SpdxConstantsCompatV2.EXTERNAL_DOC_REF_PRENUM+GENERATED+String.valueOf(nextNextDocumentId++);
- case SpdxId: return SpdxConstantsCompatV2.SPDX_ELEMENT_REF_PRENUM+GENERATED+String.valueOf(nextNextSpdxId++);
+ case Anonymous: return ANON_PREFIX+GENERATED+nextAnonId++;
+ case LicenseRef: return SpdxConstantsCompatV2.NON_STD_LICENSE_ID_PRENUM+GENERATED+nextNextLicenseId++;
+ case DocumentRef: return SpdxConstantsCompatV2.EXTERNAL_DOC_REF_PRENUM+GENERATED+nextNextDocumentId++;
+ case SpdxId: return SpdxConstantsCompatV2.SPDX_ELEMENT_REF_PRENUM+GENERATED+nextNextSpdxId++;
case ListedLicense: throw new InvalidSPDXAnalysisException("Can not generate a license ID for a Listed License");
- default: throw new InvalidSPDXAnalysisException("Unknown ID type for next ID: "+idType.toString());
+ default: throw new InvalidSPDXAnalysisException("Unknown ID type for next ID: "+ idType);
}
}
@@ -343,8 +330,7 @@ public void removeProperty(String objectUri, PropertyDescriptor propertyDescript
}
@Override
- public Stream getAllItems(@Nullable String nameSpace, @Nullable String typeFilter)
- throws InvalidSPDXAnalysisException {
+ public Stream getAllItems(@Nullable String nameSpace, @Nullable String typeFilter) {
Iterator valueIter = typedValueMap.values().iterator();
List allItems = new ArrayList<>();
while (valueIter.hasNext()) {
@@ -453,7 +439,7 @@ public Optional getTypedValue(String objectUri) throws InvalidSPDXAn
* Remove all existing elements, properties, and values
*/
public void clear() {
- this.typedValueMap.clear();;
+ this.typedValueMap.clear();
}
@Override
@@ -466,7 +452,7 @@ public void delete(String objectUri) throws InvalidSPDXAnalysisException {
try {
if (getItem(objectUri).getReferenceCount() > 0) {
// find the element it is used by
- logger.error("Can not object URI "+objectUri+". It is in use");
+ logger.error("Can not object URI {}. It is in use", objectUri);
throw new SpdxIdInUseException("Can not object URI "+objectUri+". It is in use");
}
List propertyDescriptors = this.getPropertyValueDescriptors(objectUri);
@@ -489,7 +475,7 @@ public void delete(String objectUri) throws InvalidSPDXAnalysisException {
}
}
if (Objects.isNull(typedValueMap.remove(objectUri.toLowerCase()))) {
- logger.error("Error deleting - object URI "+objectUri+" does not exist.");
+ logger.error("Error deleting - object URI {} does not exist.", objectUri);
throw new SpdxIdNotFoundException("Error deleting - object URI "+objectUri+" does not exist.");
}
} finally {
diff --git a/src/main/java/org/spdx/storage/simple/StoredTypedItem.java b/src/main/java/org/spdx/storage/simple/StoredTypedItem.java
index 57178276..7b951645 100644
--- a/src/main/java/org/spdx/storage/simple/StoredTypedItem.java
+++ b/src/main/java/org/spdx/storage/simple/StoredTypedItem.java
@@ -30,13 +30,14 @@
* @author Gary O'Neall
*
*/
+@SuppressWarnings({"UnusedReturnValue", "unused"})
public class StoredTypedItem extends TypedValue {
- static final Logger logger = LoggerFactory.getLogger(TypedValue.class);
+ static final Logger logger = LoggerFactory.getLogger(StoredTypedItem.class);
private static final String NO_ID_ID = "__NO_ID__"; // ID to use in list has map for non-typed values
- private ConcurrentHashMap properties = new ConcurrentHashMap<>();
+ private final ConcurrentHashMap properties = new ConcurrentHashMap<>();
private int referenceCount = 0;
@@ -63,7 +64,8 @@ public List getPropertyValueDescriptors() {
* Increment the reference count for this stored type item - the number of times this item is referenced
* @return new number of times this item is referenced
*/
- public int incReferenceCount() {
+ @SuppressWarnings("UnusedReturnValue")
+ public int incReferenceCount() {
countLock.writeLock().lock();
try {
this.referenceCount++;
@@ -76,7 +78,7 @@ public int incReferenceCount() {
/**
* Decrement the reference count for this stored type item
* @return new number of times this item is referenced
- * @throws SpdxInvalidTypeException
+ * @throws SpdxInvalidTypeException on invalid type
*/
public int decReferenceCount() throws SpdxInvalidTypeException {
countLock.writeLock().lock();
@@ -93,9 +95,8 @@ public int decReferenceCount() throws SpdxInvalidTypeException {
/**
* @return new number of times this item is referenced
- * @throws SpdxInvalidTypeException
*/
- public int getReferenceCount() throws SpdxInvalidTypeException {
+ public int getReferenceCount() {
countLock.readLock().lock();
try {
return this.referenceCount;
@@ -107,14 +108,14 @@ public int getReferenceCount() throws SpdxInvalidTypeException {
/**
* @param propertyDescriptor Descriptor for the property
* @param value Value to be set
- * @throws SpdxInvalidTypeException
+ * @throws SpdxInvalidTypeException on invalid type
*/
public void setValue(PropertyDescriptor propertyDescriptor, Object value) throws SpdxInvalidTypeException {
Objects.requireNonNull(propertyDescriptor, "Property descriptor can not be null");
Objects.requireNonNull(value, "Value can not be null");
if (value instanceof CoreModelObject) {
throw new SpdxInvalidTypeException("Can not store Model Object in store. Convert to TypedValue first");
- } else if (value instanceof List || value instanceof Collection) {
+ } else if (value instanceof Collection) {
throw new SpdxInvalidTypeException("Can not store list values directly. Use addValueToCollection.");
} else if (!value.getClass().isPrimitive() &&
!String.class.isAssignableFrom(value.getClass()) &&
@@ -122,7 +123,7 @@ public void setValue(PropertyDescriptor propertyDescriptor, Object value) throws
!Integer.class.isAssignableFrom(value.getClass()) &&
!TypedValue.class.isAssignableFrom(value.getClass()) &&
!(value instanceof IndividualUriValue)) {
- throw new SpdxInvalidTypeException(value.getClass().toString()+" is not a supported class to be stored.");
+ throw new SpdxInvalidTypeException(value.getClass() +" is not a supported class to be stored.");
}
properties.put(propertyDescriptor, value);
}
@@ -130,7 +131,7 @@ public void setValue(PropertyDescriptor propertyDescriptor, Object value) throws
/**
* Sets the value list for the property to an empty list creating the propertyDescriptor if it does not exist
* @param propertyDescriptor descriptor for the property
- * @throws SpdxInvalidTypeException
+ * @throws SpdxInvalidTypeException on invalid type
*/
public void clearPropertyValueList(PropertyDescriptor propertyDescriptor) throws SpdxInvalidTypeException {
Objects.requireNonNull(propertyDescriptor, "property descriptor can not be null");
@@ -150,7 +151,7 @@ public void clearPropertyValueList(PropertyDescriptor propertyDescriptor) throws
* Adds a value to a property list for a String or Boolean type of value creating the propertyDescriptor if it does not exist
* @param propertyDescriptor Descriptor for the property
* @param value Value to be set
- * @throws SpdxInvalidTypeException
+ * @throws SpdxInvalidTypeException on invalid type
*/
public boolean addValueToList(PropertyDescriptor propertyDescriptor, Object value) throws SpdxInvalidTypeException {
Objects.requireNonNull(propertyDescriptor, "Property descriptor can not be null");
@@ -163,7 +164,7 @@ public boolean addValueToList(PropertyDescriptor propertyDescriptor, Object valu
!Integer.class.isAssignableFrom(value.getClass()) &&
!TypedValue.class.isAssignableFrom(value.getClass()) &&
!(value instanceof IndividualUriValue)) {
- throw new SpdxInvalidTypeException(value.getClass().toString()+" is not a supported class to be stored.");
+ throw new SpdxInvalidTypeException(value.getClass() +" is not a supported class to be stored.");
}
Object map = properties.get(propertyDescriptor);
if (map == null) {
@@ -186,7 +187,7 @@ public boolean addValueToList(PropertyDescriptor propertyDescriptor, Object valu
} else {
id = NO_ID_ID;
}
- idValueMap.putIfAbsent(id, new ArrayList());
+ idValueMap.putIfAbsent(id, new ArrayList<>());
List list = idValueMap.get(id);
if (list == null) {
// handle the very small window where this may have gotten removed
@@ -230,8 +231,8 @@ public boolean removeTypedValueFromList(PropertyDescriptor propertyDescriptor, T
/**
* Removes a property from a list if it exists
* @param propertyDescriptor descriptor for the property
- * @param value
- * @throws SpdxInvalidTypeException
+ * @param value value to remove
+ * @throws SpdxInvalidTypeException on invalid type
*/
public boolean removeValueFromList(PropertyDescriptor propertyDescriptor, Object value) throws SpdxInvalidTypeException {
Objects.requireNonNull(propertyDescriptor, "property descriptor can not be null");
@@ -265,7 +266,7 @@ public boolean removeValueFromList(PropertyDescriptor propertyDescriptor, Object
/**
* @param propertyDescriptor Descriptor for the property
* @return List of values associated with the objectUri, propertyDescriptor and document
- * @throws SpdxInvalidTypeException
+ * @throws SpdxInvalidTypeException on invalid type
*/
public Iterator getValueList(PropertyDescriptor propertyDescriptor) throws SpdxInvalidTypeException {
Objects.requireNonNull(propertyDescriptor, "property descriptor can not be null");
@@ -309,12 +310,12 @@ public void removeProperty(PropertyDescriptor propertyDescriptor) {
/**
* Copy all values for this item from another store
* @param store model store to copy from
- * @throws InvalidSPDXAnalysisException
+ * @throws InvalidSPDXAnalysisException on invalid type
*/
public void copyValuesFrom(IModelStore store) throws InvalidSPDXAnalysisException {
Objects.requireNonNull(store, "Store can not be null");
- List propertyDiscriptors = store.getPropertyValueDescriptors(this.getObjectUri());
- for (PropertyDescriptor propertydescriptor:propertyDiscriptors) {
+ List propertyDescriptors = store.getPropertyValueDescriptors(this.getObjectUri());
+ for (PropertyDescriptor propertydescriptor:propertyDescriptors) {
Optional value = store.getValue(getObjectUri(), propertydescriptor);
if (value.isPresent()) {
this.setValue(propertydescriptor, value.get());
@@ -325,7 +326,7 @@ public void copyValuesFrom(IModelStore store) throws InvalidSPDXAnalysisExceptio
/**
* @param propertyDescriptor descriptor for the property
* @return Size of the collection
- * @throws SpdxInvalidTypeException
+ * @throws SpdxInvalidTypeException on invalid type
*/
@SuppressWarnings("rawtypes")
public int collectionSize(PropertyDescriptor propertyDescriptor) throws SpdxInvalidTypeException {
@@ -358,7 +359,7 @@ public int collectionSize(PropertyDescriptor propertyDescriptor) throws SpdxInva
* @param propertyDescriptor descriptor for the property
* @param value value to be checked
* @return true if value is in the list associated with the property descriptor
- * @throws SpdxInvalidTypeException
+ * @throws SpdxInvalidTypeException on invalid type
*/
public boolean collectionContains(PropertyDescriptor propertyDescriptor, Object value) throws SpdxInvalidTypeException {
Objects.requireNonNull(propertyDescriptor, "property descriptor can not be null");
@@ -395,7 +396,7 @@ public boolean collectionContains(PropertyDescriptor propertyDescriptor, Object
* @param propertyDescriptor descriptor for the property
* @param clazz class to test against
* @return true if the property with the propertyDescriptor can be assigned to clazz
- * @throws ModelRegistryException
+ * @throws ModelRegistryException On registry exception - check that it is initialized
*/
public boolean isCollectionMembersAssignableTo(PropertyDescriptor propertyDescriptor, Class> clazz) throws ModelRegistryException {
Objects.requireNonNull(propertyDescriptor, "Property descriptor can not be null");
@@ -405,7 +406,7 @@ public boolean isCollectionMembersAssignableTo(PropertyDescriptor propertyDescri
return true; // It is still assignable to since it is unassigned
}
if (!(map instanceof ConcurrentHashMap,?>)) {
- logger.warn("Checking collection properites on a non-collection stored item");
+ logger.warn("Checking collection properties on a non-collection stored item");
return false;
}
@SuppressWarnings("unchecked")
@@ -434,7 +435,8 @@ private boolean isAssignableTo(Object value, Class> clazz, String specVersion)
if (value instanceof TypedValue) {
TypedValue typedValue = (TypedValue)value;
try {
- return clazz.isAssignableFrom(ModelRegistry.getModelRegistry().typeToClass(typedValue.getType(), typedValue.getSpecVersion()));
+ Class> type = ModelRegistry.getModelRegistry().typeToClass(typedValue.getType(), typedValue.getSpecVersion());
+ return Objects.nonNull(type) && clazz.isAssignableFrom(type);
} catch (InvalidSPDXAnalysisException e) {
logger.error("Error converting typed value to class",e);
return false;
@@ -495,21 +497,19 @@ public boolean usesId(String elementId) {
if (Objects.isNull(elementId)) {
return false;
}
- Iterator allValues = this.properties.values().iterator();
- while (allValues.hasNext()) {
- Object value = allValues.next();
- if (value instanceof List && ((List>)value).size() > 0 && ((List>)value).get(0) instanceof TypedValue) {
- for (Object listValue:(List>)value) {
- if (listValue instanceof TypedValue && ((TypedValue) listValue).getObjectUri().toLowerCase().equals(elementId.toLowerCase())) {
- return true;
- }
- }
- } else if (value instanceof TypedValue) {
- if (((TypedValue)value).getObjectUri().toLowerCase().equals(elementId.toLowerCase())) {
- return true;
- }
- }
- }
+ for (Object value : this.properties.values()) {
+ if (value instanceof List && !((List>) value).isEmpty() && ((List>) value).get(0) instanceof TypedValue) {
+ for (Object listValue : (List>) value) {
+ if (listValue instanceof TypedValue && ((TypedValue) listValue).getObjectUri().equalsIgnoreCase(elementId)) {
+ return true;
+ }
+ }
+ } else if (value instanceof TypedValue) {
+ if (((TypedValue) value).getObjectUri().equalsIgnoreCase(elementId)) {
+ return true;
+ }
+ }
+ }
return false;
}
}
\ No newline at end of file
diff --git a/src/main/java/org/spdx/storage/simple/package-info.java b/src/main/java/org/spdx/storage/simple/package-info.java
index a00afbdf..6db683bc 100644
--- a/src/main/java/org/spdx/storage/simple/package-info.java
+++ b/src/main/java/org/spdx/storage/simple/package-info.java
@@ -1,14 +1,14 @@
/**
* 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.
diff --git a/src/main/java/org/spdx/utility/DownloadCache.java b/src/main/java/org/spdx/utility/DownloadCache.java
index b4d22f30..0b9d9f39 100644
--- a/src/main/java/org/spdx/utility/DownloadCache.java
+++ b/src/main/java/org/spdx/utility/DownloadCache.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2023 Peter Monks
- *
+ *
* 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.
@@ -22,8 +22,6 @@
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
@@ -57,12 +55,12 @@
/**
* This singleton class provides a flexible download cache for the rest of the library. If enabled, URLs that are
* requested using this class will have their content automatically cached locally on disk (in a directory that adheres
- * to the XDG Base Directory Specification - https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html),
+ * to the XDG Base Directory Specification - ... ),
* and any subsequent requests will be served out of that cache. Cache entries will also be automatically checked every
* so often for staleness using HTTP ETag requests (which are more efficient than full HTTP requests). The interval
* between such checks is configurable (and can even be turned off, which makes every download request re-check the URL
* for staleness).
- *
+ *
* The cache is configured via these Configuration options:
* * org.spdx.storage.listedlicense.enableCache:
* Controls whether the cache is enabled or not. Defaults to false i.e. the cache is disabled.
@@ -89,8 +87,8 @@ public final class DownloadCache {
System.getenv("XDG_CACHE_HOME")) +
File.separator + "Spdx-Java-Library";
- private final String CONFIG_PROPERTY_CACHE_ENABLED = "org.spdx.downloadCacheEnabled";
- private final String CONFIG_PROPERTY_CACHE_CHECK_INTERVAL_SECS = "org.spdx.downloadCacheCheckIntervalSecs";
+ private static final String CONFIG_PROPERTY_CACHE_ENABLED = "org.spdx.downloadCacheEnabled";
+ private static final String CONFIG_PROPERTY_CACHE_CHECK_INTERVAL_SECS = "org.spdx.downloadCacheCheckIntervalSecs";
private final boolean cacheEnabled;
private final long cacheCheckIntervalSecs;
@@ -106,7 +104,7 @@ private DownloadCache() {
final File cacheDirectory = new File(cacheDir);
Files.createDirectories(cacheDirectory.toPath());
} catch (IOException ioe) {
- logger.warn("Unable to create cache directory '" + cacheDir + "'; continuing with cache disabled.", ioe);
+ logger.warn("Unable to create cache directory '{}'; continuing with cache disabled.", cacheDir, ioe);
tmpCacheEnabled = false;
}
}
@@ -198,7 +196,7 @@ public InputStream getUrlInputStream(final URL url, final boolean restrictRedire
* @throws IOException When an IO error of some kind occurs.
*/
private InputStream getUrlInputStreamDirect(URL url, boolean restrictRedirects) throws IOException {
- InputStream result = null;
+ InputStream result;
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setReadTimeout(READ_TIMEOUT);
final URL redirectUrl = processPossibleRedirect(connection, restrictRedirects);
@@ -212,7 +210,7 @@ private InputStream getUrlInputStreamDirect(URL url, boolean restrictRedirects)
if (status == HttpURLConnection.HTTP_OK) {
result = connection.getInputStream();
} else {
- throw new IOException("Unexpected HTTP status code from " + url.toString() + ": " + status);
+ throw new IOException("Unexpected HTTP status code from " + url + ": " + status);
}
return result;
}
@@ -243,7 +241,7 @@ private InputStream getUrlInputStreamThroughCache(final URL url, boolean restric
}
// At this point the cached file definitely exists
- return new BufferedInputStream(new FileInputStream(cachedFile));
+ return new BufferedInputStream(Files.newInputStream(cachedFile.toPath()));
}
/**
@@ -264,7 +262,7 @@ private void checkCache(final URL url, boolean restrictRedirects) throws IOExcep
if (difference > cacheCheckIntervalSecs) {
// It's been a while since we checked the cached download of this URL for staleness, so make an ETag request
- logger.debug("Cache check interval exceeded; checking for updates to " + String.valueOf(url));
+ logger.debug("Cache check interval exceeded; checking for updates to {}", url);
final String eTag = cachedMetadata.get("eTag");
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(READ_TIMEOUT);
@@ -276,13 +274,13 @@ private void checkCache(final URL url, boolean restrictRedirects) throws IOExcep
cacheMiss(url, connection, restrictRedirects);
} else {
// The content hasn't changed, so just update the lastChecked metadata but otherwise do nothing
- logger.debug("Cache hit for " + String.valueOf(url));
+ logger.debug("Cache hit for {}", url);
cachedMetadata.put("lastChecked", iso8601.format(Instant.now()));
writeMetadataFile(cachedMetadataFile, cachedMetadata);
}
} else {
// We checked recently, so don't need to do anything - the cached content will be used
- logger.debug("Within cache check interval; skipping check of updates to " + String.valueOf(url));
+ logger.debug("Within cache check interval; skipping check of updates to {}", url);
}
} else {
// Metadata doesn't exist - treat it as a cache miss
@@ -300,7 +298,7 @@ private void checkCache(final URL url, boolean restrictRedirects) throws IOExcep
* @throws IOException When an IO error of some kind occurs.
*/
private void cacheMiss(URL url, HttpURLConnection connection, boolean restrictRedirects) throws IOException {
- logger.debug("Cache miss for " + String.valueOf(url));
+ logger.debug("Cache miss for {}", url);
final URL redirectUrl = processPossibleRedirect(connection, restrictRedirects);
if (redirectUrl != null) {
@@ -313,7 +311,7 @@ private void cacheMiss(URL url, HttpURLConnection connection, boolean restrictRe
final File cachedFile = new File(cacheDir, cacheKey);
writeContentFile(connection.getInputStream(), cachedFile);
final File cachedMetadataFile = new File(cacheDir, cacheKey + ".metadata.json");
- final HashMap metadata = new HashMap();
+ final HashMap metadata = new HashMap<>();
metadata.put("eTag", connection.getHeaderField("ETag"));
metadata.put("downloadedAt", iso8601.format(Instant.now()));
metadata.put("lastChecked", iso8601.format(Instant.now()));
@@ -380,7 +378,7 @@ private URL processPossibleRedirect(final HttpURLConnection connection, final bo
* it.
*/
private HashMap readMetadataFile(final File metadataFile) {
- HashMap result = null;
+ HashMap result;
try {
final Reader r = new BufferedReader(new FileReader(metadataFile));
result = new Gson().fromJson(r, new TypeToken>(){}.getType());
@@ -412,7 +410,7 @@ private void writeMetadataFile(final File metadataFile, HashMap m
* @throws IOException When an IO error of some kind occurs.
*/
private void writeContentFile(final InputStream is, final File cachedFile) throws IOException {
- try (final OutputStream cacheFileOutputStream = new BufferedOutputStream(new FileOutputStream(cachedFile))) {
+ try (final OutputStream cacheFileOutputStream = new BufferedOutputStream(Files.newOutputStream(cachedFile.toPath()))) {
byte[] ioBuffer = new byte[IO_BUFFER_SIZE];
int length;
while ((length = is.read(ioBuffer)) != -1) {
@@ -428,12 +426,13 @@ private void writeContentFile(final InputStream is, final File cachedFile) throw
* @param s The string to attempt to parse.
* @return The Instant for that ISO8601 value if parsing succeeded, or null if it didn't.
*/
- private final Instant parseISO8601String(final String s) {
+ private Instant parseISO8601String(final String s) {
Instant result = null;
if (s != null) {
try {
result = Instant.parse(s);
} catch (final DateTimeParseException dtpe) {
+ //noinspection DataFlowIssue
result = null;
}
}
diff --git a/src/main/java/org/spdx/utility/compare/CompareTemplateOutputHandler.java b/src/main/java/org/spdx/utility/compare/CompareTemplateOutputHandler.java
index 19141172..ec7336ff 100644
--- a/src/main/java/org/spdx/utility/compare/CompareTemplateOutputHandler.java
+++ b/src/main/java/org/spdx/utility/compare/CompareTemplateOutputHandler.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -101,7 +101,7 @@ public String getText() {
}
/**
- * @param optionalText the text to set
+ * @param text the text to set
*/
public void setText(String text) {
this.text = text;
@@ -109,12 +109,12 @@ public void setText(String text) {
/**
* Add the instruction to the list of sub-instructions
- * @param instruction
+ * @param instruction instruction to add
*/
public void addSubInstruction(ParseInstruction instruction) {
if (instruction.getRule() != null && RuleType.VARIABLE.equals(instruction.getRule().getType()) &&
- subInstructions.size() > 0 &&
+ !subInstructions.isEmpty() &&
subInstructions.get(subInstructions.size()-1).getRule() != null &&
RuleType.VARIABLE.equals(subInstructions.get(subInstructions.size()-1).getRule().getType())) {
// Maybe this is a little bit of a hack, but merge any var instructions so that
@@ -154,7 +154,7 @@ public List getSubInstructions() {
* @return true iff there are only text instructions as sub instructions
*/
public boolean onlyText() {
- if (this.subInstructions.size() < 1) {
+ if (this.subInstructions.isEmpty()) {
return false;
}
for (ParseInstruction subInstr:this.subInstructions) {
@@ -181,10 +181,10 @@ public String toText() {
* @param startToken Index of the tokens to start the match
* @param endToken Last index of the tokens to use in the match
* @param originalText Original text used go generate the matchTokens
- * @param differenceDescription Description of differences found
- * @param nextNormalText if there is a nextOptionalText, this would be the normal text that follows the optional text
+ * @param differences Description of differences found
+ * @param tokenToLocation Map of the location of tokens
* @return Next token index after the match or -1 if no match was found
- * @throws LicenseParserException
+ * @throws LicenseParserException On license parsing errors
*/
public int match(String[] matchTokens, int startToken, int endToken, String originalText,
DifferenceDescription differences, Map tokenToLocation) throws LicenseParserException {
@@ -197,11 +197,10 @@ public int match(String[] matchTokens, int startToken, int endToken, String orig
* @param startToken Index of the tokens to start the match
* @param endToken Last index of the tokens to use in the match
* @param originalText Original text used go generate the matchTokens
- * @param differenceDescription Description of differences found
- * @param nextNormalText if there is a nextOptionalText, this would be the normal text that follows the optional text
- * @param ignoreOptionalDifferences if true, don't record any optional differences
+ * @param differences Description of differences found
+ * @param tokenToLocation Map of the location of tokens * @param ignoreOptionalDifferences if true, don't record any optional differences
* @return Next token index after the match or -1 if no match was found
- * @throws LicenseParserException
+ * @throws LicenseParserException On license parsing errors
*/
public int match(String[] matchTokens, int startToken, int endToken, String originalText,
DifferenceDescription differences, Map tokenToLocation, boolean ignoreOptionalDifferences) throws LicenseParserException {
@@ -211,18 +210,18 @@ public int match(String[] matchTokens, int startToken, int endToken, String orig
int nextToken = startToken;
if (this.rule == null) {
if (this.text != null) {
- Map textLocations = new HashMap();
+ Map textLocations = new HashMap<>();
String[] textTokens = LicenseTextHelper.tokenizeLicenseText(text, textLocations);
if (this.skipFirstTextToken) {
textTokens = Arrays.copyOfRange(textTokens, 1, textTokens.length);
}
- nextToken = compareText(textTokens, matchTokens, nextToken, endToken, this);
+ nextToken = compareText(textTokens, matchTokens, nextToken, this);
if (nextToken < 0) {
int errorLocation = -nextToken;
differences.addDifference(tokenToLocation.get(errorLocation), LicenseTextHelper.getTokenAt(matchTokens, errorLocation),
"Normal text of license does not match", text, null, getLastOptionalDifference());
}
- if (this.subInstructions.size() > 0) {
+ if (!this.subInstructions.isEmpty()) {
throw new LicenseParserException("License template parser error. Sub expressions are not allows for plain text.");
}
} else {
@@ -257,13 +256,13 @@ public int match(String[] matchTokens, int startToken, int endToken, String orig
List matchingNormalTextStartTokens = this.parent.findNextNonVarTextStartTokens(this, matchTokens,
startToken, endToken, originalText, differences, tokenToLocation);
nextToken = matchOptional(matchingNormalTextStartTokens, matchTokens,
- nextToken, endToken, originalText, differences, tokenToLocation, ignoreOptionalDifferences);
+ nextToken, originalText, tokenToLocation, ignoreOptionalDifferences);
}
} else if (this.rule.getType().equals(RuleType.VARIABLE)) {
List matchingNormalTextStartTokens = this.parent.findNextNonVarTextStartTokens(this, matchTokens,
startToken, endToken, originalText, differences, tokenToLocation);
nextToken = matchVariable(matchingNormalTextStartTokens, matchTokens,
- nextToken, endToken, originalText, differences, tokenToLocation);
+ nextToken, originalText, differences, tokenToLocation);
} else {
throw new LicenseParserException("Unexpected parser state - instruction is not root, optional, variable or text");
}
@@ -272,21 +271,18 @@ public int match(String[] matchTokens, int startToken, int endToken, String orig
/**
* Match to an optional rule
- * @param optionalInstruction Optional Instruction
* @param matchingStartTokens List of indexes for the start tokens for the next normal text
* @param matchTokens Tokens to match against
* @param startToken Index of the first token to search for the match
- * @param endToken Index of the last token to search for the match
* @param originalText Original text used go generate the matchTokens
- * @param differences Any differences found
* @param tokenToLocation Map of token index to line/column where the token was found in the original text
* @param ignoreOptionalDifferences if true, don't record any optional differences
* @return the index of the token after the find or -1 if the text did not match
- * @throws LicenseParserException
+ * @throws LicenseParserException On license parsing errors
*/
private int matchOptional(List matchingStartTokens,
- String[] matchTokens, int startToken, int endToken, String originalText,
- DifferenceDescription differences, Map tokenToLocation, boolean ignoreOptionalDifferences) throws LicenseParserException {
+ String[] matchTokens, int startToken, String originalText,
+ Map tokenToLocation, boolean ignoreOptionalDifferences) throws LicenseParserException {
for (int matchingStartToken:matchingStartTokens) {
DifferenceDescription matchDifferences = new DifferenceDescription();
int matchLocation = startToken;
@@ -316,20 +312,20 @@ private int matchOptional(List matchingStartTokens,
* @param originalText original text that created the match tokens
* @param differences Information on any differences found
* @param tokenToLocation Map of match token indexes to line/column locations
- * @return List of indexes for the start tokens for the next non variable text that matches
- * @throws LicenseParserException
+ * @return List of indexes for the start tokens for the next non-variable text that matches
+ * @throws LicenseParserException On license parsing errors
*/
private List findNextNonVarTextStartTokens(ParseInstruction afterChild,
String[] matchTokens, int startToken, int endToken, String originalText,
DifferenceDescription differences, Map tokenToLocation) throws LicenseParserException {
- List retval = new ArrayList();
+ List retval = new ArrayList<>();
// We find the first index to start our search
int indexOfChild = subInstructions.indexOf(afterChild);
if (indexOfChild < 0) {
throw new LicenseParserException("Template Parser Error: Could not locate sub instruction");
}
- int startSubinstructionIndex = indexOfChild + 1;
- if (startSubinstructionIndex >= subInstructions.size()) {
+ int startSubInstructionIndex = indexOfChild + 1;
+ if (startSubInstructionIndex >= subInstructions.size()) {
// no start tokens found
// Set return value to the end
retval.add(endToken+1);
@@ -339,7 +335,7 @@ private List findNextNonVarTextStartTokens(ParseInstruction afterChild,
// keep track of all optional rules prior to the first solid normal text since the optional
// rules can provide a valid result
List leadingOptionalSubInstructions = new ArrayList<>();
- int i = startSubinstructionIndex;
+ int i = startSubInstructionIndex;
while (i < subInstructions.size() && firstNormalTextIndex < 0) {
LicenseTemplateRule subInstructionRule = subInstructions.get(i).getRule();
if (subInstructionRule != null && subInstructionRule.getType() == RuleType.BEGIN_OPTIONAL) {
@@ -350,7 +346,7 @@ private List findNextNonVarTextStartTokens(ParseInstruction afterChild,
i++;
}
int nextMatchingStart = startToken;
- // Go through the preceding optional rules. If there enough token matches, add it to the result list
+ // Go through the preceding optional rules. If there is enough token matches, add it to the result list
for (int optionalSub:leadingOptionalSubInstructions) {
DifferenceDescription tempDiffDescription = new DifferenceDescription();
int nextOptMatchingStart = nextMatchingStart;
@@ -377,18 +373,18 @@ private List findNextNonVarTextStartTokens(ParseInstruction afterChild,
return retval;
}
- Map normalTextLocations = new HashMap();
+ Map normalTextLocations = new HashMap<>();
String[] textTokens = LicenseTextHelper.tokenizeLicenseText(subInstructions.get(firstNormalTextIndex).getText(), normalTextLocations);
if (textTokens.length > MAX_NEXT_NORMAL_TEXT_SEARCH_LENGTH) {
textTokens = Arrays.copyOf(textTokens, MAX_NEXT_NORMAL_TEXT_SEARCH_LENGTH);
}
- int tokenAfterMatch = compareText(textTokens, matchTokens, nextMatchingStart, endToken, null);
+ int tokenAfterMatch = compareText(textTokens, matchTokens, nextMatchingStart, null);
boolean foundEnoughTokens = false;
while (!foundEnoughTokens && nextMatchingStart <= endToken && !differences.differenceFound) {
while (tokenAfterMatch < 0 && -tokenAfterMatch <= endToken) {
nextMatchingStart = nextMatchingStart + 1;
- tokenAfterMatch = compareText(textTokens, matchTokens, nextMatchingStart, endToken, null);
+ tokenAfterMatch = compareText(textTokens, matchTokens, nextMatchingStart, null);
}
if (tokenAfterMatch < 0) {
// Can not find the text, report a difference
@@ -419,7 +415,7 @@ private List findNextNonVarTextStartTokens(ParseInstruction afterChild,
if (nextCheckToken < 0) {
// we didn't match enough, move on to the next
nextMatchingStart = nextMatchingStart + 1;
- tokenAfterMatch = compareText(textTokens, matchTokens, nextMatchingStart, endToken, null);
+ tokenAfterMatch = compareText(textTokens, matchTokens, nextMatchingStart, null);
} else {
retval.add(nextMatchingStart);
foundEnoughTokens = true;
@@ -431,9 +427,9 @@ private List findNextNonVarTextStartTokens(ParseInstruction afterChild,
/**
* Determine the number of tokens matched from the compare text
- * @param text
+ * @param text text to search
* @param end End of matching text
- * @return
+ * @return number of tokens in the text
*/
private int numTokensMatched(String text, int end) {
if (text.trim().isEmpty()) {
@@ -442,7 +438,7 @@ private int numTokensMatched(String text, int end) {
if (end == 0) {
return 0;
}
- Map temp = new HashMap();
+ Map temp = new HashMap<>();
String subText = text.substring(0, end);
String[] tokenizedString = LicenseTextHelper.tokenizeLicenseText(subText, temp);
return tokenizedString.length;
@@ -453,14 +449,13 @@ private int numTokensMatched(String text, int end) {
* @param matchingStartTokens List of indexes for the start tokens for the next normal text
* @param matchTokens Tokens to match against
* @param startToken Index of the first token to search for the match
- * @param endToken Index of the last token to search for the match
* @param originalText Original text used go generate the matchTokens
* @param differences Any differences found
* @param tokenToLocation Map of token index to line/column where the token was found in the original text
* @return the index of the token after the find or -1 if the text did not match
*/
- private int matchVariable(List matchingStartTokens, String[] matchTokens, int startToken, int endToken,
- String originalText, DifferenceDescription differences, Map tokenToLocation) {
+ private int matchVariable(List matchingStartTokens, String[] matchTokens, int startToken,
+ String originalText, DifferenceDescription differences, Map tokenToLocation) {
if (differences.isDifferenceFound()) {
return -1;
@@ -469,13 +464,11 @@ private int matchVariable(List matchingStartTokens, String[] matchToken
String compareText = LicenseCompareHelper.locateOriginalText(originalText, startToken, matchingStartToken-1, tokenToLocation, matchTokens);
Pattern matchPattern = Pattern.compile(rule.getMatch(), Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
Matcher matcher = matchPattern.matcher(compareText);
- if (!matcher.find() || matcher.start() > 0) {
- continue;
- } else {
- int numMatched = numTokensMatched(compareText, matcher.end());
- return startToken + numMatched;
- }
- }
+ if (matcher.find() && matcher.start() <= 0) {
+ int numMatched = numTokensMatched(compareText, matcher.end());
+ return startToken + numMatched;
+ }
+ }
// if we got here, there was no match found
differences.addDifference(tokenToLocation.get(startToken), LicenseTextHelper.getTokenAt(matchTokens, startToken), "Variable text rule "+rule.getName()+" did not match the compare text",
null, rule, getLastOptionalDifference());
@@ -649,7 +642,7 @@ public boolean isSkipFirstTextToken() {
/**
* Information obout any difference found
*/
- public class DifferenceDescription {
+ public static class DifferenceDescription {
private static final int MAX_DIFF_TEXT_LENGTH = 100;
private boolean differenceFound;
private String differenceMessage;
@@ -737,8 +730,8 @@ public void addDifference(LineColumn location, String token, String msg, String
this.differenceMessage = msg;
if (location != null) {
this.differenceMessage = this.differenceMessage + " starting at line #"+
- String.valueOf(location.getLine())+ " column #" +
- String.valueOf(location.getColumn())+" \""+
+ location.getLine() + " column #" +
+ location.getColumn() +" \""+
token+"\"";
this.differences.add(location);
} else {
@@ -754,7 +747,7 @@ public void addDifference(LineColumn location, String token, String msg, String
}
}
if (rule != null) {
- this.differenceMessage = this.differenceMessage + " while processing rule " + rule.toString();
+ this.differenceMessage = this.differenceMessage + " while processing rule " + rule;
}
if (lastOptionalDifference != null) {
this.differenceMessage = this.differenceMessage +
@@ -765,9 +758,9 @@ public void addDifference(LineColumn location, String token, String msg, String
}
}
- String[] compareTokens = new String[0];
- String compareText = "";
- Map tokenToLocation = new HashMap();
+ String[] compareTokens;
+ String compareText;
+ Map tokenToLocation = new HashMap<>();
ParseInstruction topLevelInstruction = new ParseInstruction(null, null, null);
DifferenceDescription differences = new DifferenceDescription();
ParseInstruction currentOptionalInstruction = null;
@@ -784,15 +777,14 @@ public CompareTemplateOutputHandler(String compareText) throws IOException {
}
/**
- * @param textTokens
- * @param matchTokens
- * @param startToken
- * @param endToken
- * @param instruction
+ * @param textTokens source for compare
+ * @param matchTokens tokens to match against
+ * @param startToken index for the start token
+ * @param instruction parse instruction
* @return positive index of the next match token after the match or negative index of the token which first failed the match
*/
- private int compareText(String[] textTokens, String[] matchTokens, int startToken, int endToken,
- ParseInstruction instruction) {
+ private int compareText(String[] textTokens, String[] matchTokens, int startToken,
+ ParseInstruction instruction) {
if (textTokens.length == 0) {
return startToken;
}
@@ -803,7 +795,7 @@ private int compareText(String[] textTokens, String[] matchTokens, int startToke
while (nextTextToken != null) {
if (nextMatchToken == null) {
// end of compare text stream
- while (nextTextToken != null && LicenseTextHelper.canSkip(nextTextToken)) {
+ while (LicenseTextHelper.canSkip(nextTextToken)) {
nextTextToken = LicenseTextHelper.getTokenAt(textTokens, textTokenCounter++);
}
if (nextTextToken != null) {
@@ -817,11 +809,11 @@ private int compareText(String[] textTokens, String[] matchTokens, int startToke
}
} else {
// see if we can skip through some compare tokens to find a match
- while (nextMatchToken != null && LicenseTextHelper.canSkip(nextMatchToken)) {
+ while (LicenseTextHelper.canSkip(nextMatchToken)) {
nextMatchToken = LicenseTextHelper.getTokenAt(matchTokens, matchTokenCounter++);
}
// just to be sure, skip forward on the text
- while (nextTextToken != null && LicenseTextHelper.canSkip(nextTextToken)) {
+ while (LicenseTextHelper.canSkip(nextTextToken)) {
nextTextToken = LicenseTextHelper.getTokenAt(textTokens, textTokenCounter++);
}
if (LicenseTextHelper.tokensEquivalent(nextMatchToken, nextTextToken)) {
@@ -955,8 +947,8 @@ public void completeParsing() throws LicenseParserException {
* @return next token index (positive) if there is a match, negative first token where this is a miss-match if no match
*/
public int textEquivalent(String text, int startToken) {
- Map textLocations = new HashMap();
+ Map textLocations = new HashMap<>();
String[] textTokens = LicenseTextHelper.tokenizeLicenseText(text, textLocations);
- return this.compareText(textTokens, this.compareTokens, startToken, this.compareTokens.length-1, null);
+ return this.compareText(textTokens, this.compareTokens, startToken, null);
}
}
diff --git a/src/main/java/org/spdx/utility/compare/LicenseCompareHelper.java b/src/main/java/org/spdx/utility/compare/LicenseCompareHelper.java
index 84390689..89858559 100644
--- a/src/main/java/org/spdx/utility/compare/LicenseCompareHelper.java
+++ b/src/main/java/org/spdx/utility/compare/LicenseCompareHelper.java
@@ -1,14 +1,14 @@
/**
* 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.
@@ -61,7 +61,7 @@ public class LicenseCompareHelper {
protected static final Integer CROSS_REF_NUM_WORDS_MATCH = 80;
- protected static final Pattern REGEX_QUANTIFIER_PATTERN = Pattern.compile(".*\\.\\{(\\d+),(\\d+)\\}$");
+ protected static final Pattern REGEX_QUANTIFIER_PATTERN = Pattern.compile(".*\\.\\{(\\d+),(\\d+)}$");
static final String START_COMMENT_CHAR_PATTERN = "(//|/\\*|\\*|#|' |REM ||-\\}|\\*\\)|\\s\\*)\\s*$", ""); // remove end of line comments
+ line = line.replaceAll("(\\*/|-->|-}|\\*\\)|\\s\\*)\\s*$", ""); // remove end of line comments
line = line.replaceAll("^\\s*" + START_COMMENT_CHAR_PATTERN, ""); // remove start of line comments
line = line.replaceAll("^\\s*<>\\s*" + START_COMMENT_CHAR_PATTERN, "<>");
sb.append(line);
@@ -131,65 +131,56 @@ public static String locateOriginalText(String fullLicenseText, int startToken,
}
LineColumn end = tokenToLocation.get(endToken);
// If end == null, then we read to the end
- BufferedReader reader = null;
- try {
- reader = new BufferedReader(new StringReader(fullLicenseText));
- int currentLine = 1;
- String line = reader.readLine();
- while (line != null && currentLine < start.getLine()) {
- currentLine++;
- line = reader.readLine();
- }
- if (line == null) {
- return "";
- }
- if (end == null) {
- // read until the end of the stream
- StringBuilder sb = new StringBuilder(line.substring(start.getColumn(), line.length()));
- currentLine++;
- line = reader.readLine();
- while (line != null) {
- sb.append(line);
- currentLine++;
- line = reader.readLine();
- }
- return sb.toString();
- } else if (end.getLine() == currentLine) {
- return line.substring(start.getColumn(), end.getColumn()+end.getLen());
- } else {
- StringBuilder sb = new StringBuilder(line.substring(start.getColumn(), line.length()));
- currentLine++;
- line = reader.readLine();
- while (line != null && currentLine < end.getLine()) {
- sb.append("\n");
- sb.append(line);
- currentLine++;
- line = reader.readLine();
- }
- if (line != null && end.getColumn()+end.getLen() > 0) {
- sb.append("\n");
- sb.append(line.substring(0, end.getColumn()+end.getLen()));
- }
- return sb.toString();
- }
- } catch (IOException e) {
- // just build with spaces - not ideal, but close enough most of the time
- StringBuilder sb = new StringBuilder(tokens[startToken]);
- for (int i = startToken+1; i <= endToken; i++) {
- sb.append(' ');
- sb.append(tokens[i]);
- }
- return sb.toString();
- } finally {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
- }
+ try (BufferedReader reader = new BufferedReader(new StringReader(fullLicenseText))) {
+ int currentLine = 1;
+ String line = reader.readLine();
+ while (line != null && currentLine < start.getLine()) {
+ currentLine++;
+ line = reader.readLine();
+ }
+ if (line == null) {
+ return "";
+ }
+ if (end == null) {
+ // read until the end of the stream
+ StringBuilder sb = new StringBuilder(line.substring(start.getColumn()));
+ currentLine++;
+ line = reader.readLine();
+ while (line != null) {
+ sb.append(line);
+ currentLine++;
+ line = reader.readLine();
+ }
+ return sb.toString();
+ } else if (end.getLine() == currentLine) {
+ return line.substring(start.getColumn(), end.getColumn() + end.getLen());
+ } else {
+ StringBuilder sb = new StringBuilder(line.substring(start.getColumn()));
+ currentLine++;
+ line = reader.readLine();
+ while (line != null && currentLine < end.getLine()) {
+ sb.append("\n");
+ sb.append(line);
+ currentLine++;
+ line = reader.readLine();
+ }
+ if (line != null && end.getColumn() + end.getLen() > 0) {
+ sb.append("\n");
+ sb.append(line.substring(0, end.getColumn() + end.getLen()));
+ }
+ return sb.toString();
+ }
+ } catch (IOException e) {
+ // just build with spaces - not ideal, but close enough most of the time
+ StringBuilder sb = new StringBuilder(tokens[startToken]);
+ for (int i = startToken + 1; i <= endToken; i++) {
+ sb.append(' ');
+ sb.append(tokens[i]);
+ }
+ return sb.toString();
+ }
+ // ignore
+ }
/*
* @param text text to test
@@ -259,8 +250,8 @@ public static boolean isLicenseEqual(AnyLicenseInfo license1,
if (!(license2 instanceof CustomLicense)) {
return false;
} else {
- String licenseid1 = ((CustomLicense)license1).getObjectUri();
- String licenseid2 = ((CustomLicense)license2).getObjectUri();
+ String licenseid1 = license1.getObjectUri();
+ String licenseid2 = license2.getObjectUri();
String xlatedLicenseId = xlationMap.get(licenseid1);
if (xlatedLicenseId == null) {
return false; // no equivalent license was found
@@ -309,7 +300,7 @@ private static boolean isLicenseSetsEqual(Collection licenseInfo
}
/**
- * Get the text of a license minus any optional text - note: this include the default variable text
+ * Get the text of a license minus any optional text - note: this includes the default variable text
* @param licenseTemplate license template containing optional and var tags
* @param varTextHandling include original, exclude, or include the regex (enclosed with "~~~") for "var" text
* @return list of strings for all non-optional license text.
@@ -346,10 +337,9 @@ public static List getNonOptionalLicenseText(String licenseTemplate,
* @param compareText Text to compare using the template
* @return any differences found
* @throws SpdxCompareException on comparison errors
- * @throws InvalidSPDXAnalysisException on errors reading reading properties from the SPDX model
- */
- public static DifferenceDescription isTextMatchingTemplate(String template, String compareText) throws SpdxCompareException, InvalidSPDXAnalysisException {
- CompareTemplateOutputHandler compareTemplateOutputHandler = null;
+ */
+ public static DifferenceDescription isTextMatchingTemplate(String template, String compareText) throws SpdxCompareException {
+ CompareTemplateOutputHandler compareTemplateOutputHandler;
try {
compareTemplateOutputHandler = new CompareTemplateOutputHandler(LicenseTextHelper.removeLineSeparators(removeCommentChars(compareText)));
} catch (IOException e1) {
@@ -376,7 +366,7 @@ public static DifferenceDescription isTextMatchingTemplate(String template, Stri
*/
public static DifferenceDescription isTextStandardLicense(License license, String compareText) throws SpdxCompareException, InvalidSPDXAnalysisException {
String licenseTemplate = license.getStandardLicenseTemplate().orElse("");
- if (licenseTemplate == null || licenseTemplate.trim().isEmpty()) {
+ if (licenseTemplate.trim().isEmpty()) {
licenseTemplate = license.getLicenseText();
}
return isTextMatchingTemplate(licenseTemplate, compareText);
@@ -392,7 +382,7 @@ public static DifferenceDescription isTextStandardLicense(License license, Strin
*/
public static DifferenceDescription isTextStandardException(ListedLicenseException exception, String compareText) throws SpdxCompareException, InvalidSPDXAnalysisException {
String exceptionTemplate = exception.getStandardAdditionTemplate().orElse("");
- if (exceptionTemplate == null || exceptionTemplate.trim().isEmpty()) {
+ if (exceptionTemplate.trim().isEmpty()) {
exceptionTemplate = exception.getAdditionText();
}
return isTextMatchingTemplate(exceptionTemplate, compareText);
@@ -408,10 +398,10 @@ public static boolean isStandardLicenseWithinText(String text, ListedLicense lic
try {
return new TemplateRegexMatcher(license.getStandardLicenseTemplate().orElse(license.getLicenseText())).isTemplateMatchWithinText(text);
} catch (SpdxCompareException e) {
- logger.warn("Error getting optional text for license " + license.getObjectUri(), e);
+ logger.warn("Compare error getting optional text for license {}", license.getObjectUri(), e);
return false;
} catch (InvalidSPDXAnalysisException e) {
- logger.warn("Error getting optional text for license " + license.getObjectUri(), e);
+ logger.warn("SPDX Analysis error getting optional text for license {}", license.getObjectUri(), e);
return false;
}
}
@@ -431,9 +421,9 @@ public static boolean isStandardLicenseExceptionWithinText(String text, ListedLi
try {
return new TemplateRegexMatcher(exception.getStandardAdditionTemplate().orElse(exception.getAdditionText())).isTemplateMatchWithinText(text);
} catch (SpdxCompareException e) {
- logger.warn("Error getting optional text for license exception ID " + exception.getObjectUri(), e);
+ logger.warn("Compare error getting optional text for license exception ID {}", exception.getObjectUri(), e);
} catch (InvalidSPDXAnalysisException e) {
- logger.warn("Error getting optional text for license exception ID " + exception.getObjectUri(), e);
+ logger.warn("SPDX analysis error getting optional text for license exception ID {}", exception.getObjectUri(), e);
}
return result;
}
@@ -456,7 +446,7 @@ public static String[] matchingStandardLicenseIds(String licenseText) throws Inv
matchingIds.add(licenseUriToLicenseId(license.getObjectUri()));
}
}
- return matchingIds.toArray(new String[matchingIds.size()]);
+ return matchingIds.toArray(new String[0]);
}
@@ -467,9 +457,8 @@ public static String[] matchingStandardLicenseIds(String licenseText) throws Inv
* @param licenseIds License ids to compare against
* @return List of SPDX standard license IDs from licenseIds that match
* @throws InvalidSPDXAnalysisException If an error occurs accessing the standard licenses
- * @throws SpdxCompareException If an error occurs in the comparison
- */
- public static List matchingStandardLicenseIdsWithinText(String text, List licenseIds) throws InvalidSPDXAnalysisException, SpdxCompareException {
+ */
+ public static List matchingStandardLicenseIdsWithinText(String text, List licenseIds) throws InvalidSPDXAnalysisException {
List result = new ArrayList<>();
if (text != null && !text.isEmpty() && licenseIds != null && !licenseIds.isEmpty()) {
@@ -488,12 +477,11 @@ public static List matchingStandardLicenseIdsWithinText(String text, Lis
/**
* Returns a list of SPDX Standard License ID's that were found within the text, using
* the SPDX matching guidelines.
- * @param text Text to compare to all of the standard licenses
+ * @param text Text to compare to all the standard licenses
* @return List of SPDX standard license IDs that match
* @throws InvalidSPDXAnalysisException If an error occurs accessing the standard licenses
- * @throws SpdxCompareException If an error occurs in the comparison
- */
- public static List matchingStandardLicenseIdsWithinText(String text) throws InvalidSPDXAnalysisException, SpdxCompareException {
+ */
+ public static List matchingStandardLicenseIdsWithinText(String text) throws InvalidSPDXAnalysisException {
return matchingStandardLicenseIdsWithinText(text, ListedLicenses.getListedLicenses().getSpdxListedLicenseIds());
}
@@ -503,11 +491,10 @@ public static List matchingStandardLicenseIdsWithinText(String text) thr
* the SPDX matching guidelines.
* @param text Text to compare to
* @param licenseExceptionIds License Exceptions Ids to compare against
- * @return Array of SPDX standard license exception IDs from licenseExceptionIds that match
+ * @return List of SPDX standard license exception IDs from licenseExceptionIds that match
* @throws InvalidSPDXAnalysisException If an error occurs accessing the standard license exceptions
- * @throws SpdxCompareException If an error occurs in the comparison
- */
- public static List matchingStandardLicenseExceptionIdsWithinText(String text, List licenseExceptionIds) throws InvalidSPDXAnalysisException, SpdxCompareException {
+ */
+ public static List matchingStandardLicenseExceptionIdsWithinText(String text, List licenseExceptionIds) throws InvalidSPDXAnalysisException {
List result = new ArrayList<>();
if (text != null && !text.isEmpty() && licenseExceptionIds != null && !licenseExceptionIds.isEmpty()) {
@@ -526,12 +513,11 @@ public static List matchingStandardLicenseExceptionIdsWithinText(String
/**
* Returns a list of SPDX Standard License Exception ID's that were found within the text, using
* the SPDX matching guidelines.
- * @param text Text to compare to all of the standard license exceptions
- * @return Array of SPDX standard license exception IDs that match
+ * @param text Text to compare to all the standard license exceptions
+ * @return List of SPDX standard license exception IDs that match
* @throws InvalidSPDXAnalysisException If an error occurs accessing the standard license exceptions
- * @throws SpdxCompareException If an error occurs in the comparison
- */
- public static List matchingStandardLicenseExceptionIdsWithinText(String text) throws InvalidSPDXAnalysisException, SpdxCompareException {
+ */
+ public static List matchingStandardLicenseExceptionIdsWithinText(String text) throws InvalidSPDXAnalysisException {
return matchingStandardLicenseExceptionIdsWithinText(text, ListedLicenses.getListedLicenses().getSpdxListedExceptionIds());
}
@@ -553,12 +539,11 @@ private static boolean contains(
* @param license license
* @param blackList license black list
* @return if the license pass black lists
- * @throws InvalidSPDXAnalysisException If an error occurs accessing the standard license exceptions
- */
+ */
public static boolean isLicensePassBlackList(
AnyLicenseInfo license,
String... blackList
- ) throws InvalidSPDXAnalysisException {
+ ) {
if (license == null) {
return true;
}
@@ -589,12 +574,11 @@ public static boolean isLicensePassBlackList(
* @param license license
* @param whiteList license white list
* @return if the license pass white lists
- * @throws InvalidSPDXAnalysisException If an error occurs accessing the standard license exceptions
- */
+ */
public static boolean isLicensePassWhiteList(
AnyLicenseInfo license,
String... whiteList
- ) throws InvalidSPDXAnalysisException {
+ ) {
if (license == null) {
return false;
}
@@ -620,7 +604,7 @@ public static boolean isLicensePassWhiteList(
}
}
- /**
+ /*
* The following methods are provided for compatibility with the SPDX 2.X versions of the
* library
*/
@@ -655,8 +639,8 @@ public static boolean isLicenseEqual(org.spdx.library.model.v2.license.AnyLicens
if (!(license2 instanceof org.spdx.library.model.v2.license.ExtractedLicenseInfo)) {
return false;
} else {
- String licenseUri1 = ((org.spdx.library.model.v2.license.ExtractedLicenseInfo)license1).getObjectUri();
- String licenseUri2 = ((org.spdx.library.model.v2.license.ExtractedLicenseInfo)license2).getObjectUri();
+ String licenseUri1 = license1.getObjectUri();
+ String licenseUri2 = license2.getObjectUri();
String xlatedLicenseId = xlationMap.get(licenseUri1);
if (xlatedLicenseId == null) {
return false; // no equivalent license was found
@@ -718,7 +702,7 @@ public static DifferenceDescription isTextStandardLicense(org.spdx.library.model
if (licenseTemplate == null || licenseTemplate.trim().isEmpty()) {
licenseTemplate = license.getLicenseText();
}
- CompareTemplateOutputHandler compareTemplateOutputHandler = null;
+ CompareTemplateOutputHandler compareTemplateOutputHandler;
try {
compareTemplateOutputHandler = new CompareTemplateOutputHandler(LicenseTextHelper.removeLineSeparators(removeCommentChars(compareText)));
} catch (IOException e1) {
@@ -748,7 +732,7 @@ public static DifferenceDescription isTextStandardException(org.spdx.library.mod
if (exceptionTemplate == null || exceptionTemplate.trim().isEmpty()) {
exceptionTemplate = exception.getLicenseExceptionText();
}
- CompareTemplateOutputHandler compareTemplateOutputHandler = null;
+ CompareTemplateOutputHandler compareTemplateOutputHandler;
try {
compareTemplateOutputHandler = new CompareTemplateOutputHandler(LicenseTextHelper.removeLineSeparators(removeCommentChars(compareText)));
} catch (IOException e1) {
@@ -776,10 +760,10 @@ public static boolean isStandardLicenseWithinText(String text, org.spdx.library.
try {
return new TemplateRegexMatcher(license.getStandardLicenseTemplate()).isTemplateMatchWithinText(text);
} catch (SpdxCompareException e) {
- logger.warn("Error getting optional text for license " + license.getObjectUri(), e);
+ logger.warn("Compare error getting optional text for license {}", license.getObjectUri(), e);
return false;
} catch (InvalidSPDXAnalysisException e) {
- logger.warn("Error getting optional text for license " + license.getObjectUri(), e);
+ logger.warn("SPDX error getting optional text for license {}", license.getObjectUri(), e);
return false;
}
}
@@ -799,9 +783,9 @@ public static boolean isStandardLicenseExceptionWithinText(String text, org.spdx
try {
return new TemplateRegexMatcher(exception.getLicenseExceptionTemplate()).isTemplateMatchWithinText(text);
} catch (SpdxCompareException e) {
- logger.warn("Error getting optional text for license exception ID " + exception.getObjectUri(), e);
+ logger.warn("Compare error getting optional text for license exception ID {}", exception.getObjectUri(), e);
} catch (InvalidSPDXAnalysisException e) {
- logger.warn("Error getting optional text for license exception ID " + exception.getObjectUri(), e);
+ logger.warn("SPDX error getting optional text for license exception ID {}", exception.getObjectUri(), e);
}
return result;
}
diff --git a/src/main/java/org/spdx/utility/compare/SpdxCompareException.java b/src/main/java/org/spdx/utility/compare/SpdxCompareException.java
index 0bdfbe56..b14173a4 100644
--- a/src/main/java/org/spdx/utility/compare/SpdxCompareException.java
+++ b/src/main/java/org/spdx/utility/compare/SpdxCompareException.java
@@ -6,29 +6,16 @@
*/
public class SpdxCompareException extends Exception {
- /**
- *
- */
private static final long serialVersionUID = 1L;
- /**
- * @param message
- */
public SpdxCompareException(String message) {
super(message);
}
- /**
- * @param cause
- */
public SpdxCompareException(Throwable cause) {
super(cause);
}
- /**
- * @param message
- * @param cause
- */
public SpdxCompareException(String message, Throwable cause) {
super(message, cause);
}
diff --git a/src/main/java/org/spdx/utility/compare/SpdxComparer.java b/src/main/java/org/spdx/utility/compare/SpdxComparer.java
index 672dc2c3..08477368 100644
--- a/src/main/java/org/spdx/utility/compare/SpdxComparer.java
+++ b/src/main/java/org/spdx/utility/compare/SpdxComparer.java
@@ -1,14 +1,14 @@
/**
* Copyright (c) 2020 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.
@@ -54,12 +54,12 @@
/**
* Performs a comparison between two or more SPDX documents and holds the results of the comparison
* The main function to perform the comparison is compare(spdxdoc1, spdxdoc2)
- *
+ *
* For files, the comparison results are separated into unique files based on the file names
* which can be obtained by the method getUniqueFiles(index1, index2)
. If two
* documents contain files with the same name, but different data, the differences for these
* files can be obtained through the method getFileDifferences(index1, index2)
- *
+ *
* Multi-threading considerations: This class is "mostly" threadsafe in that the calls to
* perform the comparison are synchronized and a flag is used to throw an error for any
* calls to getters when a compare is in progress. There is a small theoretical window in the
@@ -68,6 +68,7 @@
* @author Gary O'Neall
*
*/
+@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public class SpdxComparer {
static final Logger logger = LoggerFactory.getLogger(SpdxComparer.class);
@@ -92,20 +93,20 @@ public class SpdxComparer {
* the comparison which do not contain some of the reviewers in the key document. See the
* implementation of compareReviewers for details
*/
- private Map>> uniqueExtractedLicenses = new HashMap<>();
+ private final Map>> uniqueExtractedLicenses = new HashMap<>();
/**
* Map of any SPDX documents that have extraced license infos with equivalent text but different comments, objectUri's or other fields
*/
- private Map>> licenseDifferences = new HashMap<>();
+ private final Map>> licenseDifferences = new HashMap<>();
/**
* Maps the license ID's for the extracted license infos of the documents being compared. License ID's are mapped based on the text
* being equivalent
*/
- private Map>> extractedLicenseIdMap = new HashMap<>();
+ private final Map>> extractedLicenseIdMap = new HashMap<>();
private boolean creatorInformationEquals;
- private Map>> uniqueCreators = new HashMap<>();
+ private final Map>> uniqueCreators = new HashMap<>();
// file compare results
/**
@@ -114,13 +115,13 @@ public class SpdxComparer {
* the comparison which do not contain some of the files in the key document. See the
* implementation of compareFiles for details
*/
- private Map>> uniqueFiles = new HashMap<>();
+ private final Map>> uniqueFiles = new HashMap<>();
/**
* Holds a map of any SPDX documents which have file differences. A file difference
* is an SPDXReview with the same filename name but a different file property
*/
- private Map>> fileDifferences = new HashMap<>();
+ private final Map>> fileDifferences = new HashMap<>();
// Package compare results
/**
@@ -129,25 +130,25 @@ public class SpdxComparer {
* the comparison which do not contain some of the packages in the key document. See the
* implementation of comparePackages for details
*/
- private Map>> uniquePackages = new HashMap<>();
+ private final Map>> uniquePackages = new HashMap<>();
/**
* Map of package names to package comparisons
*/
- private Map packageComparers = new HashMap<>();
+ private final Map packageComparers = new HashMap<>();
// Annotation comparison results
- private Map>> uniqueDocumentAnnotations = new HashMap<>();
+ private final Map>> uniqueDocumentAnnotations = new HashMap<>();
// Document Relationships comparison results
- private Map>> uniqueDocumentRelationships = new HashMap<>();
+ private final Map>> uniqueDocumentRelationships = new HashMap<>();
// External Document References comparison results
- private Map>> uniqueExternalDocumentRefs = new HashMap<>();
+ private final Map>> uniqueExternalDocumentRefs = new HashMap<>();
// Snippet references comparison results
- private Map>> uniqueSnippets = new HashMap<>();
- private Map snippetComparers = new HashMap<>();
+ private final Map>> uniqueSnippets = new HashMap<>();
+ private final Map snippetComparers = new HashMap<>();
public SpdxComparer() {
// Default empty constructor
@@ -155,20 +156,20 @@ public SpdxComparer() {
/**
* Compares 2 SPDX documents
- * @param spdxDoc1
- * @param spdxDoc2
- * @throws InvalidSPDXAnalysisException
- * @throws SpdxCompareException
+ * @param spdxDoc1 first doc
+ * @param spdxDoc2 second doc
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
+ * @throws SpdxCompareException Customize Toolbar…
*/
public void compare(SpdxDocument spdxDoc1, SpdxDocument spdxDoc2) throws InvalidSPDXAnalysisException, SpdxCompareException {
- compare(Arrays.asList((new SpdxDocument[] {spdxDoc1, spdxDoc2})));
+ compare(Arrays.asList(spdxDoc1, spdxDoc2));
}
/**
* Compares multiple SPDX documents
- * @param spdxDocuments
- * @throws SpdxCompareException
- * @throws InvalidSPDXAnalysisException
+ * @param spdxDocuments documents to compare
+ * @throws SpdxCompareException on SPDX parsing errors
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
*/
public synchronized void compare(List spdxDocuments) throws InvalidSPDXAnalysisException, SpdxCompareException {
//TODO: Add a monitor function which allows for cancel
@@ -179,8 +180,8 @@ public synchronized void compare(List spdxDocuments) throws Invali
}
/**
- * @throws InvalidSPDXAnalysisException
- * @throws SpdxCompareException
+ * @throws InvalidSPDXAnalysisException on SPDX parsing errors
+ * @throws SpdxCompareException Customize Toolbar…
*
*/
private void performCompare() throws InvalidSPDXAnalysisException, SpdxCompareException {
@@ -200,12 +201,12 @@ private void performCompare() throws InvalidSPDXAnalysisException, SpdxCompareEx
/**
* Compare the snippets in the documents
- * @throws SpdxCompareException
+ * @throws SpdxCompareException on compare errors
*/
@SuppressWarnings("unchecked")
private void compareSnippets() throws SpdxCompareException {
// This will be a complete NXN comparison of all documents filling in the uniqueSnippets map
- if (this.spdxDocs == null || this.spdxDocs.size() < 1) {
+ if (this.spdxDocs == null || this.spdxDocs.isEmpty()) {
return;
}
this.uniqueSnippets.clear();
@@ -260,7 +261,7 @@ private void compareSnippets() throws SpdxCompareException {
//Note that the files arrays must be sorted for the find methods to work
Collections.sort(snippetsB);
List uniqueAB = findUniqueSnippets(snippetsA, snippetsB);
- if (uniqueAB != null && uniqueAB.size() > 0) {
+ if (!uniqueAB.isEmpty()) {
uniqueAMap.put(spdxDocs.get(j), uniqueAB);
}
}
@@ -274,15 +275,15 @@ private void compareSnippets() throws SpdxCompareException {
}
/**
- * @param snippetsA
- * @param snippetsB
- * @return
+ * @param snippetsA source snippets
+ * @param snippetsB snippets to compare
+ * @return list of snippets which are in B but not in A
*/
private List findUniqueSnippets(List snippetsA,
List snippetsB) {
int bIndex = 0;
int aIndex = 0;
- List alRetval = new ArrayList<>();;
+ List