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 alRetval = new ArrayList<>(); while (aIndex < snippetsA.size()) { if (bIndex >= snippetsB.size()) { alRetval.add(snippetsA.get(aIndex)); @@ -307,10 +308,9 @@ private List findUniqueSnippets(List snippetsA, } /** - * @param spdxDocument - * @param snippets - * @param extractedLicenseIdMap2 - * @throws SpdxCompareException + * @param spdxDocument Document containing the snippets + * @param snippets the snippets + * @throws SpdxCompareException on error */ private void addSnippetComparers( SpdxDocument spdxDocument, @@ -330,7 +330,7 @@ private void addSnippetComparers( } /** - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors * */ private void compareExternalDocumentRefs() throws InvalidSPDXAnalysisException { @@ -351,11 +351,11 @@ private void compareExternalDocumentRefs() throws InvalidSPDXAnalysisException { // find any external refs in A that are not in B List uniqueA = findUniqueExternalDocumentRefs(externalDocRefsA, externalDocRefsB); - if (uniqueA != null && uniqueA.size() > 0) { + if (!uniqueA.isEmpty()) { uniqueAMap.put(spdxDocs.get(j), uniqueA); } } - if (uniqueAMap.keySet().size() > 0) { + if (!uniqueAMap.isEmpty()) { this.uniqueExternalDocumentRefs.put(spdxDocs.get(i), uniqueAMap); } } @@ -366,7 +366,7 @@ private void compareExternalDocumentRefs() throws InvalidSPDXAnalysisException { /** * Compare all of the document level relationships - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private void compareDocumentRelationships() throws InvalidSPDXAnalysisException { // this will be a N x N comparison of all document level relationships to fill the @@ -386,11 +386,11 @@ private void compareDocumentRelationships() throws InvalidSPDXAnalysisException // find any creators in A that are not in B List uniqueA = findUniqueRelationships(relationshipsA, relationshipsB); - if (uniqueA != null && uniqueA.size() > 0) { + if (!uniqueA.isEmpty()) { uniqueAMap.put(spdxDocs.get(j), uniqueA); } } - if (uniqueAMap.keySet().size() > 0) { + if (!uniqueAMap.isEmpty()) { this.uniqueDocumentRelationships.put(spdxDocs.get(i), uniqueAMap); } } @@ -401,7 +401,7 @@ private void compareDocumentRelationships() throws InvalidSPDXAnalysisException /** * Compare all of the Document level annotations - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private void compareDocumentAnnotations() throws InvalidSPDXAnalysisException { // this will be a N x N comparison of all document level annotations to fill the @@ -421,11 +421,11 @@ private void compareDocumentAnnotations() throws InvalidSPDXAnalysisException { // find any creators in A that are not in B List uniqueA = findUniqueAnnotations(annotationsA, annotationsB); - if (uniqueA != null && uniqueA.size() > 0) { + if (!uniqueA.isEmpty()) { uniqueAMap.put(spdxDocs.get(j), uniqueA); } } - if (uniqueAMap.keySet().size() > 0) { + if (!uniqueAMap.isEmpty()) { this.uniqueDocumentAnnotations.put(spdxDocs.get(i), uniqueAMap); } } @@ -435,8 +435,8 @@ private void compareDocumentAnnotations() throws InvalidSPDXAnalysisException { } /** - * @throws InvalidSPDXAnalysisException - * @throws SpdxCompareException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors + * @throws SpdxCompareException on compare errors * */ @SuppressWarnings("unchecked") @@ -453,7 +453,7 @@ private void compareFiles() throws InvalidSPDXAnalysisException, SpdxCompareExce fileStreamA.close(); // note - the file arrays MUST be sorted for the comparator methods to work Collections.sort(filesListA); - SpdxFile[] filesA = filesListA.toArray(new SpdxFile[filesListA.size()]); + SpdxFile[] filesA = filesListA.toArray(new SpdxFile[0]); Map> uniqueAMap = this.uniqueFiles.get(spdxDocs.get(i)); if (uniqueAMap == null) { uniqueAMap = new HashMap<>(); @@ -470,18 +470,18 @@ private void compareFiles() throws InvalidSPDXAnalysisException, SpdxCompareExce Stream fileStreamB = (Stream)SpdxModelFactory.getSpdxObjects( spdxDocs.get(j).getModelStore(), null, SpdxConstantsCompatV2.CLASS_SPDX_FILE, spdxDocs.get(j).getDocumentUri(), null); - List filesListB = (List)fileStreamB.collect(Collectors.toList()); + List filesListB = fileStreamB.collect(Collectors.toList()); fileStreamB.close(); //Note that the files arrays must be sorted for the find methods to work Collections.sort(filesListB); - SpdxFile[] filesB = filesListB.toArray(new SpdxFile[filesListB.size()]); + SpdxFile[] filesB = filesListB.toArray(new SpdxFile[0]); List uniqueAB = findUniqueFiles(filesA, filesB); - if (uniqueAB != null && uniqueAB.size() > 0) { + if (!uniqueAB.isEmpty()) { uniqueAMap.put(spdxDocs.get(j), uniqueAB); } List differences = findFileDifferences(spdxDocs.get(i), spdxDocs.get(j), filesA, filesB, this.extractedLicenseIdMap); - if (differences != null && differences.size() > 0) { + if (!differences.isEmpty()) { diffMap.put(spdxDocs.get(j), differences); } } @@ -500,9 +500,9 @@ private void compareFiles() throws InvalidSPDXAnalysisException, SpdxCompareExce /** * Collect all of the packages present in the SPDX document including packages * embedded in other relationships within documents - * @param spdxDocument - * @return - * @throws InvalidSPDXAnalysisException + * @param spdxDocument document containing packages + * @return list of packages + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ @SuppressWarnings("unchecked") protected List collectAllPackages(SpdxDocument spdxDocument) throws InvalidSPDXAnalysisException { @@ -517,9 +517,9 @@ protected List collectAllPackages(SpdxDocument spdxDocument) throws /** * Collect all of the files present in the SPDX document including files within documents * and files embedded in packages - * @param spdxDocument - * @return - * @throws InvalidSPDXAnalysisException + * @param spdxDocument document containing files + * @return files collected + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ @SuppressWarnings("unchecked") public List collectAllFiles(SpdxDocument spdxDocument) throws InvalidSPDXAnalysisException { @@ -534,11 +534,11 @@ public List collectAllFiles(SpdxDocument spdxDocument) throws InvalidS /** * Returns an array of files differences between A and B where the names * are the same, but one or more properties are different for that file - * @param filesA - * @param filesB - * @return - * @throws SpdxCompareException - * @throws InvalidSPDXAnalysisException + * @param filesA source files + * @param filesB files to compare + * @return a list of files differences between A and B where the names are the same, but one or more properties are different for that file + * @throws SpdxCompareException on compare errors + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ static List findFileDifferences(SpdxDocument docA, SpdxDocument docB, SpdxFile[] filesA, SpdxFile[] filesB, @@ -578,9 +578,9 @@ static List findFileDifferences(SpdxDocument docA, SpdxDocum * finds any packages in A that are not in B. Packages are considered the * same if they have the same package name and the same package version. * NOTE: The arrays must be sorted by file name - * @param pkgsA - * @param pkgsB - * @return + * @param pkgsA source packages + * @param pkgsB packages to compaer + * @return any packages in A that are not in B */ static List findUniquePackages(List pkgsA, List pkgsB) { int bIndex = 0; @@ -610,10 +610,10 @@ static List findUniquePackages(List pkgsA, List findUniqueFiles(SpdxFile[] filesA, SpdxFile[] filesB) throws InvalidSPDXAnalysisException { int bIndex = 0; @@ -643,7 +643,7 @@ static List findUniqueFiles(SpdxFile[] filesA, SpdxFile[] filesB) thro } /** - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors * */ private void compareCreators() throws InvalidSPDXAnalysisException { @@ -653,7 +653,7 @@ private void compareCreators() throws InvalidSPDXAnalysisException { // hashmap uniqueCreators for (int i = 0; i < spdxDocs.size(); i++) { SpdxCreatorInformation creatorInfoA = spdxDocs.get(i).getCreationInfo(); - Collection creatorsA = creatorInfoA.getCreators(); + Collection creatorsA = Objects.requireNonNull(creatorInfoA).getCreators(); Map> uniqueAMap = uniqueCreators.get(spdxDocs.get(i)); if (uniqueAMap == null) { uniqueAMap = new HashMap<>(); @@ -664,11 +664,11 @@ private void compareCreators() throws InvalidSPDXAnalysisException { continue; // skip comparing to ourself } SpdxCreatorInformation creatorInfoB = spdxDocs.get(j).getCreationInfo(); - Collection creatorsB = creatorInfoB.getCreators(); + Collection creatorsB = Objects.requireNonNull(creatorInfoB).getCreators(); // find any creators in A that are not in B List uniqueA = findUniqueString(creatorsA, creatorsB); - if (uniqueA != null && uniqueA.size() > 0) { + if (!uniqueA.isEmpty()) { uniqueAMap.put(spdxDocs.get(j), uniqueA); } // compare creator comments @@ -687,7 +687,7 @@ private void compareCreators() throws InvalidSPDXAnalysisException { this.licenseListVersionEquals = false; } } - if (uniqueAMap.keySet().size() > 0) { + if (!uniqueAMap.isEmpty()) { this.uniqueCreators.put(spdxDocs.get(i), uniqueAMap); this.creatorInformationEquals = false; } @@ -699,9 +699,9 @@ private void compareCreators() throws InvalidSPDXAnalysisException { /** * Finds any strings which are in A but not in B - * @param stringsA - * @param stringsB - * @return + * @param stringsA source strings + * @param stringsB strings to compare + * @return any strings which are in A but not in B */ private List findUniqueString(Collection stringsA, Collection stringsB) { if (stringsA == null) { @@ -727,10 +727,10 @@ private List findUniqueString(Collection stringsA, Collection uniqueAB = findUniquePackages(pkgsA, pkgsB); - if (uniqueAB != null && uniqueAB.size() > 0) { + if (!uniqueAB.isEmpty()) { uniqueAMap.put(spdxDocs.get(j), uniqueAB); } } @@ -786,15 +786,15 @@ private void comparePackages() throws SpdxCompareException { /** * add all the document packages to the multi-comparer - * @param spdxDocument - * @param pkgs - * @param extractedLicenseIdMap - * @throws SpdxCompareException + * @param spdxDocument document containing the packges + * @param pkgs package to add + * @param extractedLicenseIdMap map of documents to extracted licenses and ids + * @throws SpdxCompareException on compare errors */ private void addPackageComparers(SpdxDocument spdxDocument, List pkgs, Map>> extractedLicenseIdMap) throws SpdxCompareException { try { - List addedPackageNames = new ArrayList(); + List addedPackageNames = new ArrayList<>(); for (SpdxPackage pkg:pkgs) { if (!pkg.getName().isPresent()) { logger.warn("Missing package name for package comparer. Skipping unnamed package"); @@ -803,7 +803,7 @@ private void addPackageComparers(SpdxDocument spdxDocument, Optional pkgName = pkg.getName(); if (pkgName.isPresent()) { if (addedPackageNames.contains(pkgName.get())) { - logger.warn("Duplicate package names: "+pkgName.get()+". Only comparing the first instance"); + logger.warn("Duplicate package names: {}. Only comparing the first instance", pkgName.get()); continue; } SpdxPackageComparer mpc = this.packageComparers.get(pkgName.get()); @@ -826,11 +826,11 @@ private void addPackageComparers(SpdxDocument spdxDocument, * the extracted license infos who's ID's may be different between the two documents * Note: The ExtracedLicenseIDMap must be initialized before this method is invoked * @param doc1 Index of the SPDX document for license1 - * @param license1 + * @param license1 license to compare * @param doc2 Index of the SPDX document for license2 - * @param license2 + * @param license2 license to compare * @return true if the licenses are equivalent - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ public boolean compareLicense(int doc1, AnyLicenseInfo license1, int doc2, @@ -853,12 +853,13 @@ public boolean compareLicense(int doc1, } /** - * @param verificationCode - * @param verificationCode2 - * @return - * @throws InvalidSPDXAnalysisException + * @param verificationCode verification code to compare + * @param verificationCode2 verification code to compare + * @return true if the verification codes are equal + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ - static boolean compareVerificationCodes( + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + static boolean compareVerificationCodes( Optional verificationCode, Optional verificationCode2) throws InvalidSPDXAnalysisException { if (!verificationCode.isPresent()) { @@ -870,16 +871,13 @@ static boolean compareVerificationCodes( if (!stringsEqual(verificationCode.get().getValue(), verificationCode2.get().getValue())) { return false; } - if (!stringCollectionsEqual(verificationCode.get().getExcludedFileNames(), - verificationCode2.get().getExcludedFileNames())) { - return false; - } - return true; - } + return stringCollectionsEqual(verificationCode.get().getExcludedFileNames(), + verificationCode2.get().getExcludedFileNames()); + } /** * Compare the document level fields and sets the difference found depending on any differences - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ private void compareDocumentFields() throws SpdxCompareException { compareDataLicense(); @@ -911,7 +909,7 @@ private void compareDocumentContents() throws SpdxCompareException { } /** - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors * */ private void compareSpdxVerions() throws SpdxCompareException { @@ -931,7 +929,7 @@ private void compareSpdxVerions() throws SpdxCompareException { } /** - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors * */ private void compareDocumentComments() throws SpdxCompareException { @@ -951,7 +949,7 @@ private void compareDocumentComments() throws SpdxCompareException { } /** - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors * */ private void compareDataLicense() throws SpdxCompareException { @@ -973,10 +971,9 @@ private void compareDataLicense() throws SpdxCompareException { * Compares the extracted license infos in all documents and builds the * maps for translating IDs as well as capturing any differences between the * extracted licensing information - * @throws InvalidSPDXAnalysisException - * @throws SpdxCompareException - */ - private void compareExtractedLicenseInfos() throws InvalidSPDXAnalysisException, SpdxCompareException { + * @throws InvalidSPDXAnalysisException on SPDX parsing errors + */ + private void compareExtractedLicenseInfos() throws InvalidSPDXAnalysisException { for (int i = 0; i < spdxDocs.size(); i++) { Collection extractedLicensesA = spdxDocs.get(i).getExtractedLicenseInfos(); Map> uniqueMap = new HashMap<>(); @@ -994,20 +991,20 @@ private void compareExtractedLicenseInfos() throws InvalidSPDXAnalysisException, compareLicenses(extractedLicensesA, extractedLicensesB, idMap, alDifferences, uniqueLicenses); // unique - if (uniqueLicenses.size() > 0) { + if (!uniqueLicenses.isEmpty()) { uniqueMap.put(spdxDocs.get(j), uniqueLicenses); } // differences - if (alDifferences.size() > 0) { + if (!alDifferences.isEmpty()) { differenceMap.put(spdxDocs.get(j), alDifferences); } // map licenseIdMap.put(spdxDocs.get(j), idMap); } - if (uniqueMap.keySet().size() > 0) { + if (!uniqueMap.isEmpty()) { this.uniqueExtractedLicenses.put(spdxDocs.get(i), uniqueMap); } - if (differenceMap.keySet().size() > 0) { + if (!differenceMap.isEmpty()) { this.licenseDifferences.put(spdxDocs.get(i), differenceMap); } this.extractedLicenseIdMap.put(spdxDocs.get(i), licenseIdMap); @@ -1019,12 +1016,12 @@ private void compareExtractedLicenseInfos() throws InvalidSPDXAnalysisException, /** * Compares two collections of non standard licenses - * @param extractedLicensesA - * @param extractedLicensesB + * @param extractedLicensesA licenses to compare + * @param extractedLicensesB licenses to compare * @param idMap Map of license IDs for licenses considered equal * @param alDifferences Array list of license differences found where the license text is equivalent but other properties are different * @param uniqueLicenses ArrayList if licenses found in the A but not found in B - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private void compareLicenses(Collection extractedLicensesA, Collection extractedLicensesB, @@ -1063,10 +1060,10 @@ private void compareLicenses(Collection extractedLicensesA /** * Compares the non-license text and non-objectUri fields and returns true * if all relevant fields are equal - * @param spdxNonStandardLicenseA - * @param spdxNonStandardLicenseB - * @return - * @throws InvalidSPDXAnalysisException + * @param spdxNonStandardLicenseA license to compare + * @param spdxNonStandardLicenseB license to compare + * @return true if all relevant fields are equal + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private boolean nonTextLicenseFieldsEqual( ExtractedLicenseInfo spdxNonStandardLicenseA, @@ -1084,19 +1081,15 @@ private boolean nonTextLicenseFieldsEqual( return false; } // Source URL's - if (!stringCollectionsEqual(spdxNonStandardLicenseA.getSeeAlso(), spdxNonStandardLicenseB.getSeeAlso())) { - return false; - } - // if we made it here, everything is equal - return true; - } + return stringCollectionsEqual(spdxNonStandardLicenseA.getSeeAlso(), spdxNonStandardLicenseB.getSeeAlso()); + } /** * Compares 2 collections and returns true if the contents are equal * ignoring order and trimming strings. Nulls are also considered as equal to other nulls. - * @param stringsA - * @param stringsB - * @return + * @param stringsA string to compare + * @param stringsB string to compare + * @return true if the contents are equal ignoring order and trimming strings */ public static boolean stringCollectionsEqual(Collection stringsA, Collection stringsB) { if (stringsA == null) { @@ -1120,9 +1113,9 @@ public static boolean stringCollectionsEqual(Collection stringsA, Collec /** * Compares 2 lists and returns true if the contents are equal * ignoring order and trimming strings. Nulls are also considered as equal to other nulls. - * @param stringsA - * @param stringsB - * @return + * @param stringsA string to compare + * @param stringsB string to compare + * @return true if the contents are equal ignoring order and trimming strings */ static boolean stringListsEqual(List stringsA, List stringsB) { if (stringsA == null) { @@ -1145,9 +1138,9 @@ static boolean stringListsEqual(List stringsA, List stringsB) { /** * returns true if the two objects are equal considering nulls - * @param o1 - * @param o2 - * @return + * @param o1 object to compare + * @param o2 object to compare + * @return true if the two objects are equal considering nulls */ public static boolean objectsEqual(Object o1, Object o2) { if (o1 == null) { @@ -1157,12 +1150,13 @@ public static boolean objectsEqual(Object o1, Object o2) { } /** - * @param elementA - * @param elementB + * @param elementA element to compare + * @param elementB element to compare * @return true of the elements are present and equivalent - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ - public static boolean elementsEquivalent(Optional elementA, Optional elementB) throws InvalidSPDXAnalysisException { + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + public static boolean elementsEquivalent(Optional elementA, Optional elementB) throws InvalidSPDXAnalysisException { if (elementA.isPresent()) { if (elementB.isPresent()) { return elementA.get().equivalent(elementB.get()); @@ -1175,9 +1169,9 @@ public static boolean elementsEquivalent(Optional eleme } /** - * @param collectionA - * @param collectionB - * @throws InvalidSPDXAnalysisException + * @param collectionA collection + * @param collectionB collection + * @throws InvalidSPDXAnalysisException on SPDX parsing errors * @return true if the collections all contain equivalent items */ public static boolean collectionsEquivalent(Collection collectionA, Collection collectionB) throws InvalidSPDXAnalysisException { @@ -1213,11 +1207,11 @@ public static boolean collectionsEquivalent(Collection /** * Compare two object lists - * @param a1 - * @param a2 - * @return + * @param a1 list + * @param a2 list + * @return true if 2 lists are equal */ - public static boolean listsEquals(List a1, List a2) { + public static boolean listsEquals(List a1, List a2) { if (a1 == null) { return a2 == null; } else { @@ -1238,11 +1232,12 @@ public static boolean listsEquals(List a1, List a1, Collection a2) { + @SuppressWarnings("BooleanMethodIsAlwaysInverted") + public static boolean collectionsEquals(Collection a1, Collection a2) { if (a1 == null) { return a2 == null; } else { @@ -1260,14 +1255,14 @@ public static boolean collectionsEquals(Collection a1, Collect return true; } } - + /** * Compares two strings returning true if they are equal * considering null values and trimming the strings. and normalizing * linefeeds. Empty strings are treated as the same as null values. - * @param stringA - * @param stringB - * @return + * @param stringA first string to compare + * @param stringB second string to compare + * @return same result as compareTo */ public static boolean stringsEqual(String stringA, String stringB) { String compA; @@ -1289,32 +1284,25 @@ public static boolean stringsEqual(String stringA, String stringB) { * Compares two strings returning true if they are equal * considering null values and trimming the strings. and normalizing * linefeeds. Empty strings are treated as the same as null values. - * @param stringA - * @param stringB - * @return + * @param stringA first string to compare + * @param stringB second string to compare + * @return same result as compareTo */ - public static boolean stringsEqual(Optional stringA, Optional stringB) { + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + public static boolean stringsEqual(Optional stringA, Optional stringB) { String compA; String compB; - if (!stringA.isPresent()) { - compA = ""; - } else { - compA = stringA.get().replace("\r\n", "\n").trim(); - } - if (!stringB.isPresent()) { - compB = ""; - } else { - compB = stringB.get().replace("\r\n", "\n").trim(); - } + compA = stringA.map(s -> s.replace("\r\n", "\n").trim()).orElse(""); + compB = stringB.map(s -> s.replace("\r\n", "\n").trim()).orElse(""); return (compA.equals(compB)); } /** * Compares two strings including trimming the string and taking into account * they may be null. Null is considered a smaller value - * @param stringA - * @param stringB - * @return + * @param stringA first string to compare + * @param stringB second string to compare + * @return same result as compareTo */ public static int compareStrings(String stringA, String stringB) { if (stringA == null) { @@ -1333,11 +1321,12 @@ public static int compareStrings(String stringA, String stringB) { /** * Compares two strings including trimming the string and taking into account * they may be null. Null is considered a smaller value - * @param stringA - * @param stringB - * @return + * @param stringA first string to compare + * @param stringB second string to compare + * @return same result as compareTo */ - public static int compareStrings(Optional stringA, Optional stringB) { + @SuppressWarnings("OptionalUsedAsFieldOrParameterType") + public static int compareStrings(Optional stringA, Optional stringB) { if (!stringA.isPresent()) { if (!stringB.isPresent()) { return 0; @@ -1345,14 +1334,11 @@ public static int compareStrings(Optional stringA, Optional stri return -1; } } - if (!stringB.isPresent()) { - return 1; - } - return (stringA.get().trim().compareTo(stringB.get().trim())); - } + return stringB.map(s -> (stringA.get().trim().compareTo(s.trim()))).orElse(1); + } /** - * + * clears all the compare results */ private void clearCompareResults() { this.differenceFound = false; @@ -1363,15 +1349,15 @@ private void clearCompareResults() { } /** - * @return + * @return true if any difference is found */ public boolean isDifferenceFound() { return this.differenceFound; } /** - * @return - * @throws SpdxCompareException + * @return true if the SPDX spec versions are equal + * @throws SpdxCompareException on compare errors */ public boolean isSpdxVersionEqual() throws SpdxCompareException { checkInProgress(); @@ -1381,7 +1367,7 @@ public boolean isSpdxVersionEqual() throws SpdxCompareException { /** * checks to make sure there is not a compare in progress - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors * */ private void checkInProgress() throws SpdxCompareException { @@ -1392,7 +1378,7 @@ private void checkInProgress() throws SpdxCompareException { /** * Validates that the spdx dcouments field has been initialized - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ private void checkDocsField() throws SpdxCompareException { if (this.spdxDocs == null) { @@ -1411,14 +1397,14 @@ private void checkDocsIndex(int index) throws SpdxCompareException { throw new SpdxCompareException("Invalid index for SPDX document compare - must be greater than or equal to zero"); } if (index >= spdxDocs.size()) { - throw new SpdxCompareException("Invalid index for SPDX document compare - SPDX document index "+String.valueOf(index)+" does not exist."); + throw new SpdxCompareException("Invalid index for SPDX document compare - SPDX document index "+ index +" does not exist."); } } /** * @param docIndex Reference to which document number - 0 is the first document parameter in compare - * @return - * @throws SpdxCompareException + * @return the SPDX document at the index + * @throws SpdxCompareException on compare errors */ public SpdxDocument getSpdxDoc(int docIndex) throws SpdxCompareException { this.checkDocsField(); @@ -1435,8 +1421,8 @@ public SpdxDocument getSpdxDoc(int docIndex) throws SpdxCompareException { } /** - * @return - * @throws SpdxCompareException + * @return true if the data licenses are equals + * @throws SpdxCompareException on compare errors */ public boolean isDataLicenseEqual() throws SpdxCompareException { checkInProgress(); @@ -1445,8 +1431,8 @@ public boolean isDataLicenseEqual() throws SpdxCompareException { } /** - * @return - * @throws SpdxCompareException + * @return true if the document comments are equal + * @throws SpdxCompareException on compare errors */ public boolean isDocumentCommentsEqual() throws SpdxCompareException { checkInProgress(); @@ -1455,26 +1441,31 @@ public boolean isDocumentCommentsEqual() throws SpdxCompareException { } private boolean _isExternalDcoumentRefsEqualsNoCheck() { - Iterator>>> iter = this.uniqueExternalDocumentRefs.entrySet().iterator(); - while (iter.hasNext()) { - Iterator> docIterator = iter.next().getValue().values().iterator(); - while (docIterator.hasNext()) { - if (docIterator.next().size() > 0) { - return false; - } - } - } + for (Entry>> spdxDocumentMapEntry : this.uniqueExternalDocumentRefs.entrySet()) { + for (List externalDocumentRefs : spdxDocumentMapEntry.getValue().values()) { + if (!externalDocumentRefs.isEmpty()) { + return false; + } + } + } return true; } + /** + * @return true if the external document refs are equal + * @throws SpdxCompareException on compare errors + */ public boolean isExternalDcoumentRefsEquals() throws SpdxCompareException { checkInProgress(); checkDocsField(); return _isExternalDcoumentRefsEqualsNoCheck(); } - + /** + * @return true if the extracted licensing infos are equal + * @throws SpdxCompareException on compare errors + */ public boolean isExtractedLicensingInfosEqual() throws SpdxCompareException { checkInProgress(); checkDocsField(); @@ -1482,43 +1473,37 @@ public boolean isExtractedLicensingInfosEqual() throws SpdxCompareException { } /** - * @return + * @return true if the extracted licensing infos are equal */ private boolean _isExtractedLicensingInfoEqualsNoCheck() { // check for unique extraced license infos - Iterator>>> uniqueIter = - this.uniqueExtractedLicenses.entrySet().iterator(); - while (uniqueIter.hasNext()) { - Entry>> entry = uniqueIter.next(); - Iterator>> entryIter = entry.getValue().entrySet().iterator(); - while(entryIter.hasNext()) { - List licenses = entryIter.next().getValue(); - if (licenses != null && licenses.size() > 0) { - return false; - } - } - } + for (Entry>> entry : this.uniqueExtractedLicenses.entrySet()) { + for (Entry> spdxDocumentListEntry : entry.getValue().entrySet()) { + List licenses = spdxDocumentListEntry.getValue(); + if (licenses != null && !licenses.isEmpty()) { + return false; + } + } + } // check differences - Iterator>>> diffIterator = this.licenseDifferences.entrySet().iterator(); - while (diffIterator.hasNext()) { - Iterator>> entryIter = diffIterator.next().getValue().entrySet().iterator(); - while (entryIter.hasNext()) { - List differences = entryIter.next().getValue(); - if (differences != null && differences.size() > 0) { - return false; - } - } - } + for (Entry>> spdxDocumentMapEntry : this.licenseDifferences.entrySet()) { + for (Entry> spdxDocumentListEntry : spdxDocumentMapEntry.getValue().entrySet()) { + List differences = spdxDocumentListEntry.getValue(); + if (differences != null && !differences.isEmpty()) { + return false; + } + } + } return true; } /** * Retrieves any unique extracted licenses fromt the first SPDX document index * relative to the second - unique is determined by the license text matching - * @param docIndexA - * @param docIndexB - * @return - * @throws SpdxCompareException + * @param docIndexA source document index + * @param docIndexB index of the compare document + * @return ny unique extracted licenses fromt the first SPDX document index relative to the second - unique is determined by the license text matching + * @throws SpdxCompareException on compare errors */ public List getUniqueExtractedLicenses(int docIndexA, int docIndexB) throws SpdxCompareException { this.checkDocsField(); @@ -1541,10 +1526,10 @@ public List getUniqueExtractedLicenses(int docIndexA, int /** * Retrieves any licenses which where the text matches in both documents but * other fields are different - * @param docIndexA - * @param docIndexB - * @return - * @throws SpdxCompareException + * @param docIndexA source document index + * @param docIndexB index of the compare document + * @return any creators which are in the SPDX document 1 which are not in document 2 + * @throws SpdxCompareException on compare errors */ public List getExtractedLicenseDifferences(int docIndexA, int docIndexB) throws SpdxCompareException { this.checkDocsField(); @@ -1566,7 +1551,7 @@ public List getExtractedLicenseDifferences(int docIndexA, /** * @return true if all creation information fields equals - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ public boolean isCreatorInformationEqual() throws SpdxCompareException { this.checkDocsField(); @@ -1576,7 +1561,7 @@ public boolean isCreatorInformationEqual() throws SpdxCompareException { /** * @return true all creator comments equal - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ public boolean isCreatorCommentsEqual() throws SpdxCompareException { this.checkDocsField(); @@ -1586,7 +1571,7 @@ public boolean isCreatorCommentsEqual() throws SpdxCompareException { /** * @return true if all creation information fields equals - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ public boolean isCreatorDatesEqual() throws SpdxCompareException { this.checkDocsField(); @@ -1596,10 +1581,10 @@ public boolean isCreatorDatesEqual() throws SpdxCompareException { /** * Returns any creators which are in the SPDX document 1 which are not in document 2 - * @param doc1index - * @param doc2index - * @return - * @throws SpdxCompareException + * @param doc1index source document index + * @param doc2index index of the compare document + * @return any creators which are in the SPDX document 1 which are not in document 2 + * @throws SpdxCompareException on compare errors */ public List getUniqueCreators(int doc1index, int doc2index) throws SpdxCompareException { this.checkDocsField(); @@ -1617,8 +1602,8 @@ public List getUniqueCreators(int doc1index, int doc2index) throws SpdxC } /** - * @return - * @throws SpdxCompareException + * @return true if the files are equal + * @throws SpdxCompareException on compare errors */ public boolean isfilesEquals() throws SpdxCompareException { this.checkDocsField(); @@ -1627,8 +1612,8 @@ public boolean isfilesEquals() throws SpdxCompareException { } /** - * @return - * @throws SpdxCompareException + * @return true if the packages are equal + * @throws SpdxCompareException on compare errors */ public boolean isPackagesEquals() throws SpdxCompareException { this.checkDocsField(); @@ -1637,8 +1622,8 @@ public boolean isPackagesEquals() throws SpdxCompareException { } /** - * @return - * @throws SpdxCompareException + * @return true if the document annotations are equal + * @throws SpdxCompareException on compare errors */ public boolean isDocumentAnnotationsEquals() throws SpdxCompareException { this.checkDocsField(); @@ -1646,24 +1631,22 @@ public boolean isDocumentAnnotationsEquals() throws SpdxCompareException { return _isDocumentAnnotationsEqualsNoCheck(); } /** - * @return + * @return true if the document annotations are equals */ private boolean _isDocumentAnnotationsEqualsNoCheck() { - Iterator>>> iter = this.uniqueDocumentAnnotations.entrySet().iterator(); - while (iter.hasNext()) { - Iterator> docIterator = iter.next().getValue().values().iterator(); - while (docIterator.hasNext()) { - if (docIterator.next().size() > 0) { - return false; - } - } - } + for (Entry>> spdxDocumentMapEntry : this.uniqueDocumentAnnotations.entrySet()) { + for (List annotations : spdxDocumentMapEntry.getValue().values()) { + if (!annotations.isEmpty()) { + return false; + } + } + } return true; } /** - * @return - * @throws SpdxCompareException + * @return true if the document relationships are equal + * @throws SpdxCompareException on compare errors */ public boolean isDocumentRelationshipsEquals() throws SpdxCompareException { this.checkDocsField(); @@ -1671,62 +1654,55 @@ public boolean isDocumentRelationshipsEquals() throws SpdxCompareException { return _isDocumentRelationshipsEqualsNoCheck(); } /** - * @return + * Compares document relationships without checking validity + * @return true if the documents relationships are equal */ private boolean _isDocumentRelationshipsEqualsNoCheck() { - Iterator>>> iter = this.uniqueDocumentRelationships.entrySet().iterator(); - while (iter.hasNext()) { - Iterator> docIterator = iter.next().getValue().values().iterator(); - while (docIterator.hasNext()) { - if (docIterator.next().size() > 0) { - return false; - } - } - } + for (Entry>> spdxDocumentMapEntry : this.uniqueDocumentRelationships.entrySet()) { + for (List relationships : spdxDocumentMapEntry.getValue().values()) { + if (!relationships.isEmpty()) { + return false; + } + } + } return true; } /** - * @return + * @return true if the files are equal */ private boolean _isFilesEqualsNoCheck() { if (!this.uniqueFiles.isEmpty()) { return false; } - if (!this.fileDifferences.isEmpty()) { - return false; - } - return true; - } + return this.fileDifferences.isEmpty(); + } /** - * @return - * @throws SpdxCompareException + * @return true if the packages are equal + * @throws SpdxCompareException on compare errors */ private boolean _isPackagesEqualsNoCheck() throws SpdxCompareException { - Iterator>>> iter = this.uniquePackages.entrySet().iterator(); - while (iter.hasNext()) { - Iterator> docIterator = iter.next().getValue().values().iterator(); - while (docIterator.hasNext()) { - if (docIterator.next().size() > 0) { - return false; - } - } - } - Iterator diffIter = this.packageComparers.values().iterator(); - while (diffIter.hasNext()) { - if (diffIter.next().isDifferenceFound()) { - return false; - } - } + for (Entry>> spdxDocumentMapEntry : this.uniquePackages.entrySet()) { + for (List spdxPackages : spdxDocumentMapEntry.getValue().values()) { + if (!spdxPackages.isEmpty()) { + return false; + } + } + } + for (SpdxPackageComparer spdxPackageComparer : this.packageComparers.values()) { + if (spdxPackageComparer.isDifferenceFound()) { + return false; + } + } return true; } /** * Return any files which are in spdx document index 1 but not in spdx document index 2 - * @param docindex1 - * @param docindex2 - * @return - * @throws SpdxCompareException + * @param docindex1 index of source document + * @param docindex2 index of document to compare + * @return any files which are in spdx document index 1 but not in spdx document index 2 + * @throws SpdxCompareException on errors doing compare */ public List getUniqueFiles(int docindex1, int docindex2) throws SpdxCompareException { this.checkDocsField(); @@ -1747,10 +1723,11 @@ public List getUniqueFiles(int docindex1, int docindex2) throws SpdxCo /** * Returns any file differences found between the first and second SPDX documents * as specified by the document index - * @param docindex1 - * @param docindex2 - * @return - * @throws SpdxCompareException + * @param docindex1 index of source document + * @param docindex2 index of document to compare + * @return any file differences found between the first and second SPDX documents + * as specified by the document index + * @throws SpdxCompareException on errors doing compare */ public List getFileDifferences(int docindex1, int docindex2) throws SpdxCompareException { this.checkDocsField(); @@ -1770,10 +1747,10 @@ public List getFileDifferences(int docindex1, int docindex2) /** * Return any files which are in spdx document index 1 but not in spdx document index 2 - * @param docindex1 - * @param docindex2 - * @return - * @throws SpdxCompareException + * @param docindex1 index of source document + * @param docindex2 index of document to compare + * @return any files which are in spdx document index 1 but not in spdx document index 2 + * @throws SpdxCompareException on errors doing compare */ public List getUniquePackages(int docindex1, int docindex2) throws SpdxCompareException { this.checkDocsField(); @@ -1793,10 +1770,10 @@ public List getUniquePackages(int docindex1, int docindex2) throws /** * Return any external document references which are in spdx document index 1 but not in spdx document index 2 - * @param docindex1 - * @param docindex2 - * @return - * @throws SpdxCompareException + * @param docindex1 index of source document + * @param docindex2 index of document to compare + * @return any external document references which are in spdx document index 1 but not in spdx document index 2 + * @throws SpdxCompareException on errors doing compare */ public List getUniqueExternalDocumentRefs(int docindex1, int docindex2) throws SpdxCompareException { this.checkDocsField(); @@ -1816,10 +1793,10 @@ public List getUniqueExternalDocumentRefs(int docindex1, in /** * Return any document annotations which are in spdx document index 1 but not in spdx document index 2 - * @param docindex1 - * @param docindex2 - * @return - * @throws SpdxCompareException + * @param docindex1 index of source document + * @param docindex2 index of document to compare + * @return any document annotations which are in spdx document index 1 but not in spdx document index 2 + * @throws SpdxCompareException on errors doing compare */ public List getUniqueDocumentAnnotations(int docindex1, int docindex2) throws SpdxCompareException { this.checkDocsField(); @@ -1839,10 +1816,10 @@ public List getUniqueDocumentAnnotations(int docindex1, int docindex /** * Return any document annotations which are in spdx document index 1 but not in spdx document index 2 - * @param docindex1 - * @param docindex2 - * @return - * @throws SpdxCompareException + * @param docindex1 index of first document to compare + * @param docindex2 index of second document to compare + * @return document annotations in spdx document index 1 but not in spdx document index 2 + * @throws SpdxCompareException On error in comparison */ public List getUniqueDocumentRelationship(int docindex1, int docindex2) throws SpdxCompareException { this.checkDocsField(); @@ -1862,7 +1839,7 @@ public List getUniqueDocumentRelationship(int docindex1, int docin /** * @return Package comparers where there is at least one difference - * @throws SpdxCompareException + * @throws SpdxCompareException On error in comparison */ public List getPackageDifferences() throws SpdxCompareException { Collection comparers = this.packageComparers.values(); @@ -1882,19 +1859,19 @@ public List getPackageDifferences() throws SpdxCompareExcep */ public SpdxPackageComparer[] getPackageComparers() { return this.packageComparers.values().toArray( - new SpdxPackageComparer[this.packageComparers.values().size()]); + new SpdxPackageComparer[0]); } /** - * @return + * @return the number of documents being compared */ public int getNumSpdxDocs() { return this.spdxDocs.size(); } /** - * @return - * @throws SpdxCompareException + * @return true if the licens list version is equal + * @throws SpdxCompareException On error in comparison */ public boolean isLicenseListVersionEqual() throws SpdxCompareException { this.checkDocsField(); @@ -1903,11 +1880,11 @@ public boolean isLicenseListVersionEqual() throws SpdxCompareException { } /** - * Find any SPDX checksums which are in elementsA but not in elementsB - * @param checksumsA - * @param checksumsB - * @return - * @throws InvalidSPDXAnalysisException + * Find any SPDX checksums which are in checksumsA but not in checksumsB + * @param checksumsA checksum to compare + * @param checksumsB checksum to compare + * @return any SPDX checksums which are in checksumsA but not in checksumsB + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ public static List findUniqueChecksums(Collection checksumsA, Collection checksumsB) throws InvalidSPDXAnalysisException { @@ -1936,10 +1913,10 @@ public static List findUniqueChecksums(Collection checksumsA /** * Find any SPDX annotations which are in annotationsA but not in annotationsB - * @param annotationsA - * @param annotationsB - * @return - * @throws InvalidSPDXAnalysisException + * @param annotationsA source annotations + * @param annotationsB annotations to be compared agains + * @return list of unique annotations in annotationsB + * @throws InvalidSPDXAnalysisException On SPDX parsing errors */ public static List findUniqueAnnotations(Collection annotationsA, Collection annotationsB) throws InvalidSPDXAnalysisException { @@ -1965,10 +1942,10 @@ public static List findUniqueAnnotations(Collection anno /** * Find unique relationships that are present in relationshipsA but not relationshipsB - * @param relationshipsA - * @param relationshipsB - * @return - * @throws InvalidSPDXAnalysisException + * @param relationshipsA relationship to compare + * @param relationshipsB relationship to compare + * @return unique relationships that are present in relationshipsA but not relationshipsB + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ public static List findUniqueRelationships( Collection relationshipsA, Collection relationshipsB) throws InvalidSPDXAnalysisException { @@ -1998,10 +1975,10 @@ public static List findUniqueRelationships( /** * Find unique relationships that are present in relationshipsA but not relationshipsB - * @param externalDocRefsA - * @param externalDocRefsB - * @return - * @throws InvalidSPDXAnalysisException + * @param externalDocRefsA doc ref to compare + * @param externalDocRefsB doc ref to compare + * @return list of unique relationship + * @throws InvalidSPDXAnalysisException On error in comparison */ public static List findUniqueExternalDocumentRefs( Collection externalDocRefsA, Collection externalDocRefsB) throws InvalidSPDXAnalysisException { @@ -2032,15 +2009,15 @@ public static List findUniqueExternalDocumentRefs( } /** - * @return + * @return list of SPDX documents */ public List getSpdxDocuments() { return this.spdxDocs; } /** - * @return - * @throws SpdxCompareException + * @return true if the document contents are equals + * @throws SpdxCompareException On error in comparison */ public boolean isDocumentContentsEquals() throws SpdxCompareException { checkInProgress(); @@ -2048,8 +2025,8 @@ public boolean isDocumentContentsEquals() throws SpdxCompareException { } /** - * @return - * @throws SpdxCompareException + * @return true if the snippets are equals + * @throws SpdxCompareException On error in comparison */ public boolean isSnippetsEqual() throws SpdxCompareException { this.checkDocsField(); @@ -2058,25 +2035,22 @@ public boolean isSnippetsEqual() throws SpdxCompareException { } /** - * @return - * @throws SpdxCompareException + * @return true if the snippets are equals + * @throws SpdxCompareException On error in comparison */ private boolean _isSnippetsEqualsNoCheck() throws SpdxCompareException { - Iterator>>> iter = this.uniqueSnippets.entrySet().iterator(); - while (iter.hasNext()) { - Iterator> docIterator = iter.next().getValue().values().iterator(); - while (docIterator.hasNext()) { - if (docIterator.next().size() > 0) { - return false; - } - } - } - Iterator diffIter = this.snippetComparers.values().iterator(); - while (diffIter.hasNext()) { - if (diffIter.next().isDifferenceFound()) { - return false; - } - } + for (Entry>> spdxDocumentMapEntry : this.uniqueSnippets.entrySet()) { + for (List spdxSnippets : spdxDocumentMapEntry.getValue().values()) { + if (!spdxSnippets.isEmpty()) { + return false; + } + } + } + for (SpdxSnippetComparer spdxSnippetComparer : this.snippetComparers.values()) { + if (spdxSnippetComparer.isDifferenceFound()) { + return false; + } + } return true; } @@ -2085,6 +2059,6 @@ private boolean _isSnippetsEqualsNoCheck() throws SpdxCompareException { */ public SpdxSnippetComparer[] getSnippetComparers() { return this.snippetComparers.values().toArray( - new SpdxSnippetComparer[this.snippetComparers.values().size()]); + new SpdxSnippetComparer[0]); } } diff --git a/src/main/java/org/spdx/utility/compare/SpdxExternalRefDifference.java b/src/main/java/org/spdx/utility/compare/SpdxExternalRefDifference.java index 25d107ef..eb373a83 100644 --- a/src/main/java/org/spdx/utility/compare/SpdxExternalRefDifference.java +++ b/src/main/java/org/spdx/utility/compare/SpdxExternalRefDifference.java @@ -1,14 +1,15 @@ /** * 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. @@ -37,22 +38,14 @@ public class SpdxExternalRefDifference { String commentB; ReferenceCategory catA; ReferenceCategory catB; - private String referenceLocator; - private ReferenceType referenceType; + private final String referenceLocator; + private final ReferenceType referenceType; SpdxExternalRefDifference(ExternalRef externalRefA, ExternalRef externalRefB) throws InvalidSPDXAnalysisException { Optional oCommentA = externalRefA.getComment(); - if (oCommentA.isPresent()) { - this.commentA = oCommentA.get(); - } else { - this.commentA = ""; - } + this.commentA = oCommentA.orElse(""); Optional oCommentB = externalRefB.getComment(); - if (oCommentB.isPresent()) { - this.commentB = oCommentB.get(); - } else { - this.commentB = ""; - } + this.commentB = oCommentB.orElse(""); catA = externalRefA.getReferenceCategory(); catB = externalRefB.getReferenceCategory(); this.referenceLocator = externalRefA.getReferenceLocator(); diff --git a/src/main/java/org/spdx/utility/compare/SpdxFileComparer.java b/src/main/java/org/spdx/utility/compare/SpdxFileComparer.java index 0f7541b0..1f91b83e 100644 --- a/src/main/java/org/spdx/utility/compare/SpdxFileComparer.java +++ b/src/main/java/org/spdx/utility/compare/SpdxFileComparer.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. @@ -50,7 +50,7 @@ public class SpdxFileComparer extends SpdxItemComparer { /** * Map of checksums found in one document but not another */ - private Map>> uniqueChecksums = new HashMap<>(); + private final Map>> uniqueChecksums = new HashMap<>(); private boolean checksumsEquals = true; private boolean typesEquals = true; @@ -63,9 +63,9 @@ public SpdxFileComparer(Map> /** * Add a file to the comparer and compare to the existing files * @param spdxDocument document containing the file - * @param spdxFile - * @throws SpdxCompareException - * @throws InvalidSPDXAnalysisException + * @param spdxFile file to add + * @throws SpdxCompareException on compare errors + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ public void addDocumentFile(SpdxDocument spdxDocument, SpdxFile spdxFile) throws SpdxCompareException, InvalidSPDXAnalysisException { @@ -107,40 +107,33 @@ public void addDocumentFile(SpdxDocument spdxDocument, /** * Compare the checks for a new file being added to the existing * package checksums filling in the unique checksums map - * @param spdxDocument - * @param checksums - * @throws SpdxCompareException - * @throws InvalidSPDXAnalysisException + * @param spdxDocument document containing the checksums + * @param checksums checksums to compare + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private void compareNewFileChecksums(SpdxDocument spdxDocument, - Collection checksums) throws SpdxCompareException, InvalidSPDXAnalysisException { + Collection checksums) throws InvalidSPDXAnalysisException { Map> docUniqueChecksums = new HashMap<>(); this.uniqueChecksums.put(spdxDocument, docUniqueChecksums); - Iterator> iter = this.documentItem.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - if (entry.getValue() instanceof SpdxFile) { - Collection compareChecksums = ((SpdxFile)entry.getValue()).getChecksums(); - List uniqueChecksums = SpdxComparer.findUniqueChecksums(checksums, compareChecksums); - if (uniqueChecksums.size() > 0) { - this.checksumsEquals = false; - this.differenceFound = true; - } - docUniqueChecksums.put(entry.getKey(), uniqueChecksums); - Map> compareUniqueChecksums = this.uniqueChecksums.get(entry.getKey()); - if (compareUniqueChecksums == null) { - compareUniqueChecksums = new HashMap<>(); - this.uniqueChecksums.put(entry.getKey(), compareUniqueChecksums); - } - uniqueChecksums = SpdxComparer.findUniqueChecksums(compareChecksums, checksums); - if (uniqueChecksums.size() > 0) { - this.checksumsEquals = false; - this.differenceFound = true; - } - compareUniqueChecksums.put(spdxDocument, uniqueChecksums); - } - } + for (Entry entry : this.documentItem.entrySet()) { + if (entry.getValue() instanceof SpdxFile) { + Collection compareChecksums = ((SpdxFile) entry.getValue()).getChecksums(); + List uniqueChecksums = SpdxComparer.findUniqueChecksums(checksums, compareChecksums); + if (!uniqueChecksums.isEmpty()) { + this.checksumsEquals = false; + this.differenceFound = true; + } + docUniqueChecksums.put(entry.getKey(), uniqueChecksums); + Map> compareUniqueChecksums = this.uniqueChecksums.computeIfAbsent(entry.getKey(), k -> new HashMap<>()); + uniqueChecksums = SpdxComparer.findUniqueChecksums(compareChecksums, checksums); + if (!uniqueChecksums.isEmpty()) { + this.checksumsEquals = false; + this.differenceFound = true; + } + compareUniqueChecksums.put(spdxDocument, uniqueChecksums); + } + } } @@ -166,10 +159,10 @@ public boolean isChecksumsEquals() throws SpdxCompareException { /** * Get the checksums which are present in the file contained document A but not in document B - * @param docA - * @param docB - * @return - * @throws SpdxCompareException + * @param docA document to compare + * @param docB document to compare + * @return the checksums which are present in the file contained document A but not in document B + * @throws SpdxCompareException on compare errors */ public List getUniqueChecksums(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { checkInProgress(); @@ -195,7 +188,7 @@ public boolean isTypesEquals() throws SpdxCompareException { /** * checks to make sure there is not a compare in progress - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors * */ @Override @@ -225,8 +218,8 @@ public boolean isNoticeTextEquals() throws SpdxCompareException { } /** - * @return - * @throws SpdxCompareException + * @return true if any differences are found + * @throws SpdxCompareException on compare errors */ @Override public boolean isDifferenceFound() throws SpdxCompareException { @@ -238,41 +231,41 @@ public boolean isDifferenceFound() throws SpdxCompareException { /** * Return a file difference for the file contained in two different documents - * @param docA - * @param docB - * @return - * @throws SpdxCompareException + * @param docA document containing files to compare + * @param docB document containing files to compare + * @return file differences between docA and docB + * @throws SpdxCompareException on compare errors */ public SpdxFileDifference getFileDifference(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { checkInProgress(); checkCompareMade(); try { SpdxItem itemA = this.documentItem.get(docA); - if (itemA == null || !(itemA instanceof SpdxFile)) { + if (!(itemA instanceof SpdxFile)) { throw new SpdxCompareException("No SPDX File associated with "+docA.getName()); } SpdxFile fileA = (SpdxFile)itemA; SpdxItem itemB = this.documentItem.get(docB); - if (itemB == null || !(itemB instanceof SpdxFile)) { + if (!(itemB instanceof SpdxFile)) { throw new SpdxCompareException("No SPDX File associated with "+docB.getName()); } SpdxFile fileB = (SpdxFile)itemB; List uniqueLicenseInfoInFilesA = this.getUniqueSeenLicenses(docA, docB); List uniqueLicenseInfoInFilesB = this.getUniqueSeenLicenses(docB, docA); - boolean licenseInfoInFilesEquals = uniqueLicenseInfoInFilesA.size() == 0 && - uniqueLicenseInfoInFilesB.size() == 0; + boolean licenseInfoInFilesEquals = uniqueLicenseInfoInFilesA.isEmpty() && + uniqueLicenseInfoInFilesB.isEmpty(); List uniqueChecksumsA = this.getUniqueChecksums(docA, docB); List uniqueChecksumsB = this.getUniqueChecksums(docB, docA); - boolean checksumsEquals = uniqueChecksumsA.size() == 0 && - uniqueChecksumsB.size() == 0; + boolean checksumsEquals = uniqueChecksumsA.isEmpty() && + uniqueChecksumsB.isEmpty(); List uniqueRelationshipA = this.getUniqueRelationship(docA, docB); List uniqueRelationshipB = this.getUniqueRelationship(docB, docA); - boolean relationshipsEquals = uniqueRelationshipA.size() == 0 && - uniqueRelationshipB.size() == 0; + boolean relationshipsEquals = uniqueRelationshipA.isEmpty() && + uniqueRelationshipB.isEmpty(); List uniqueAnnotationsA = this.getUniqueAnnotations(docA, docB); List uniqueAnnotationsB = this.getUniqueAnnotations(docB, docA); - boolean annotationsEquals = uniqueAnnotationsA.size() == 0 && - uniqueAnnotationsB.size() == 0; + boolean annotationsEquals = uniqueAnnotationsA.isEmpty() && + uniqueAnnotationsB.isEmpty(); return new SpdxFileDifference(fileA, fileB, fileA.getLicenseConcluded().equals(fileB.getLicenseConcluded()), @@ -281,7 +274,7 @@ public SpdxFileDifference getFileDifference(SpdxDocument docA, SpdxDocument docB relationshipsEquals, uniqueRelationshipB, uniqueRelationshipB, annotationsEquals, uniqueAnnotationsA, uniqueAnnotationsB); } catch (InvalidSPDXAnalysisException e) { - throw (new SpdxCompareException("Error reading SPDX file propoerties: "+e.getMessage(),e)); + throw (new SpdxCompareException("Error reading SPDX file properties: "+e.getMessage(),e)); } } } diff --git a/src/main/java/org/spdx/utility/compare/SpdxFileDifference.java b/src/main/java/org/spdx/utility/compare/SpdxFileDifference.java index 5ea2625f..383227a8 100644 --- a/src/main/java/org/spdx/utility/compare/SpdxFileDifference.java +++ b/src/main/java/org/spdx/utility/compare/SpdxFileDifference.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. @@ -39,19 +39,19 @@ */ public class SpdxFileDifference extends SpdxItemDifference { - private List fileTypeA; - private List fileTypeB; - private List contributorsA; - private String noticeA; - private List contributorsB; - private String noticeB; - private List dependantFileNamesA; - private List dependantFileNamesB; - private boolean checksumsEquals; - private List uniqueChecksumsA; - private List uniqueChecksumsB; - private String spdxIdA; - private String spdxIdB; + private final List fileTypeA; + private final List fileTypeB; + private final List contributorsA; + private final String noticeA; + private final List contributorsB; + private final String noticeB; + private final List dependantFileNamesA; + private final List dependantFileNamesB; + private final boolean checksumsEquals; + private final List uniqueChecksumsA; + private final List uniqueChecksumsB; + private final String spdxIdA; + private final String spdxIdB; @SuppressWarnings("deprecation") public SpdxFileDifference(SpdxFile fileA, SpdxFile fileB, @@ -72,36 +72,24 @@ public SpdxFileDifference(SpdxFile fileA, SpdxFile fileB, uniqueSeenLicensesA, uniqueSeenLicensesB, relationshipsEquals, uniqueRelationshipA, uniqueRelationshipB, annotationsEquals, uniqueAnnotationsA,uniqueAnnotationsB); - this.fileTypeA = Arrays.asList(fileA.getFileTypes().toArray(new FileType[fileA.getFileTypes().size()])); - this.fileTypeB = Arrays.asList(fileB.getFileTypes().toArray(new FileType[fileB.getFileTypes().size()])); - this.contributorsA = Arrays.asList(fileA.getFileContributors().toArray(new String[fileA.getFileContributors().size()])); - this.contributorsB = Arrays.asList(fileB.getFileContributors().toArray(new String[fileB.getFileContributors().size()])); + this.fileTypeA = Arrays.asList(fileA.getFileTypes().toArray(new FileType[0])); + this.fileTypeB = Arrays.asList(fileB.getFileTypes().toArray(new FileType[0])); + this.contributorsA = Arrays.asList(fileA.getFileContributors().toArray(new String[0])); + this.contributorsB = Arrays.asList(fileB.getFileContributors().toArray(new String[0])); this.dependantFileNamesA = new ArrayList<>(); for (SpdxFile dependantFile:fileA.getFileDependency()) { Optional dependantFileName = dependantFile.getName(); - if (dependantFileName.isPresent()) { - dependantFileNamesA.add(dependantFileName.get()); - } + dependantFileName.ifPresent(dependantFileNamesA::add); } this.dependantFileNamesB = new ArrayList<>(); for (SpdxFile dependantFile:fileB.getFileDependency()) { Optional dependantFileName = dependantFile.getName(); - if (dependantFileName.isPresent()) { - dependantFileNamesB.add(dependantFileName.get()); - } + dependantFileName.ifPresent(dependantFileNamesB::add); } Optional noticeTextA =fileA.getNoticeText(); - if (noticeTextA.isPresent()) { - this.noticeA = noticeTextA.get(); - } else { - this.noticeA = ""; - } + this.noticeA = noticeTextA.orElse(""); Optional noticeTextB =fileB.getNoticeText(); - if (noticeTextB.isPresent()) { - this.noticeB = noticeTextB.get(); - } else { - this.noticeB = ""; - } + this.noticeB = noticeTextB.orElse(""); this.checksumsEquals = checksumsEquals; this.uniqueChecksumsA = uniqueChecksumsA; this.uniqueChecksumsB = uniqueChecksumsB; @@ -142,28 +130,28 @@ public boolean isFileDependenciesEqual() { } /** - * @return + * @return true if the types are equal */ public boolean isTypeEqual() { return SpdxComparer.listsEquals(fileTypeA, fileTypeB); } /** - * @return + * @return true if the checksums are equal */ public boolean isChecksumsEquals() { return this.checksumsEquals; } /** - * @return + * @return string form af all A contributors */ public String getContributorsAAsString() { return stringListToString(this.contributorsA); } /** - * @return + * @return string form of all B contributors */ public String getContributorsBAsString() { return stringListToString(this.contributorsB); @@ -173,7 +161,7 @@ public String getContributorsBAsString() { static String stringListToString(List s) { StringBuilder sb = new StringBuilder(); - if (s != null && s.size() > 0) { + if ((s != null) && (!s.isEmpty())) { sb.append(s.get(0)); for (int i = 1; i < s.size(); i++) { if (Objects.nonNull(s.get(i)) && !s.get(i).isEmpty()) { @@ -186,14 +174,14 @@ static String stringListToString(List s) { } /** - * @return + * @return string form of all A file dependencies */ public String getFileDependenciesAAsString() { return stringListToString(this.dependantFileNamesA); } /** - * @return + * @return string form of all B file dependencies */ public String getFileDependenciesBAsString() { return stringListToString(this.dependantFileNamesB); @@ -270,14 +258,14 @@ public List getUniqueChecksumsB() { } /** - * @return + * @return SPDX ID for A */ public String getSpdxIdA() { return this.spdxIdA; } /** - * @return + * @return SPDX ID for B */ public String getSpdxIdB() { return this.spdxIdB; diff --git a/src/main/java/org/spdx/utility/compare/SpdxItemComparer.java b/src/main/java/org/spdx/utility/compare/SpdxItemComparer.java index 6185eabf..ddbf6882 100644 --- a/src/main/java/org/spdx/utility/compare/SpdxItemComparer.java +++ b/src/main/java/org/spdx/utility/compare/SpdxItemComparer.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. @@ -50,11 +50,11 @@ public class SpdxItemComparer { /** * Map of unique extractedLicenseInfos between two documents */ - private Map>> uniqueLicenseInfosInFiles = new HashMap<>(); + private final Map>> uniqueLicenseInfosInFiles = new HashMap<>(); private boolean commentsEquals = true; private boolean copyrightsEquals = true; - private boolean licenseCommmentsEquals = true; + private boolean licenseCommentsEquals = true; private boolean relationshipsEquals = true; private boolean attributionTextEquals = true; /** @@ -66,7 +66,7 @@ public class SpdxItemComparer { /** * Map of unique annotations between two documents */ - private Map>> uniqueAnnotations = new HashMap<>(); + private final Map>> uniqueAnnotations = new HashMap<>(); /** * Map of SPDX document to Items @@ -86,10 +86,10 @@ public SpdxItemComparer(Map> /** * Add a new item to the comparer and compare the contents of the item * to all items which have been previously added - * @param spdxDocument - * @param spdxItem - * @throws SpdxCompareException - * @throws InvalidSPDXAnalysisException + * @param spdxDocument document containing the item + * @param spdxItem item to add + * @throws SpdxCompareException on compare error + * @throws InvalidSPDXAnalysisException on SPDX parsing error */ public void addDocumentItem(SpdxDocument spdxDocument, SpdxItem spdxItem) throws SpdxCompareException, InvalidSPDXAnalysisException { @@ -98,9 +98,7 @@ public void addDocumentItem(SpdxDocument spdxDocument, } Optional oName = spdxItem.getName(); if (this.name == null) { - if (oName.isPresent()) { - this.name = oName.get(); - } + oName.ifPresent(s -> this.name = s); } else if (oName.isPresent() && !this.name.equals(oName.get()) && !(this instanceof SpdxSnippetComparer)) { throw new SpdxCompareException("Names do not match for item being added to comparer: "+ spdxItem.getName()+", expecting "+this.name); @@ -129,7 +127,7 @@ public void addDocumentItem(SpdxDocument spdxDocument, // license comments if (!SpdxComparer.stringsEqual(spdxItem.getLicenseComments(), itemB.getLicenseComments())) { - this.licenseCommmentsEquals = false; + this.licenseCommentsEquals = false; this.itemDifferenceFound = true; } // attributionText @@ -153,38 +151,28 @@ public void addDocumentItem(SpdxDocument spdxDocument, * as well as the annotationsEquals flag and sets the differenceFound to * true if a difference was found for a newly added item * @param spdxDocument document containing the item - * @param annotations - * @throws InvalidSPDXAnalysisException + * @param annotations annotations to compare + * @throws InvalidSPDXAnalysisException on SPDX parsing error */ private void compareAnnotation(SpdxDocument spdxDocument, Collection annotations) throws InvalidSPDXAnalysisException { - Map> uniqueDocAnnotations = this.uniqueAnnotations.get(spdxDocument); - if (uniqueDocAnnotations == null) { - uniqueDocAnnotations = new HashMap<>(); - this.uniqueAnnotations.put(spdxDocument, uniqueDocAnnotations); - } - Iterator> iter = this.documentItem.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - Map> compareDocAnnotations = this.uniqueAnnotations.get(entry.getKey()); - if (compareDocAnnotations == null) { - compareDocAnnotations = new HashMap<>(); - this.uniqueAnnotations.put(entry.getKey(), compareDocAnnotations); - } - Collection compareAnnotations = entry.getValue().getAnnotations(); - List uniqueAnnotations = SpdxComparer.findUniqueAnnotations(annotations, compareAnnotations); - if (uniqueAnnotations.size() > 0) { - this.annotationsEquals = false; - this.itemDifferenceFound = true; - } - uniqueDocAnnotations.put(entry.getKey(), uniqueAnnotations); - uniqueAnnotations = SpdxComparer.findUniqueAnnotations(compareAnnotations, annotations); - if (uniqueAnnotations.size() > 0) { - this.annotationsEquals = false; - this.itemDifferenceFound = true; - } - compareDocAnnotations.put(spdxDocument, uniqueAnnotations); - } + Map> uniqueDocAnnotations = this.uniqueAnnotations.computeIfAbsent(spdxDocument, k -> new HashMap<>()); + for (Entry entry : this.documentItem.entrySet()) { + Map> compareDocAnnotations = this.uniqueAnnotations.computeIfAbsent(entry.getKey(), k -> new HashMap<>()); + Collection compareAnnotations = entry.getValue().getAnnotations(); + List uniqueAnnotations = SpdxComparer.findUniqueAnnotations(annotations, compareAnnotations); + if (!uniqueAnnotations.isEmpty()) { + this.annotationsEquals = false; + this.itemDifferenceFound = true; + } + uniqueDocAnnotations.put(entry.getKey(), uniqueAnnotations); + uniqueAnnotations = SpdxComparer.findUniqueAnnotations(compareAnnotations, annotations); + if (!uniqueAnnotations.isEmpty()) { + this.annotationsEquals = false; + this.itemDifferenceFound = true; + } + compareDocAnnotations.put(spdxDocument, uniqueAnnotations); + } } /** @@ -192,38 +180,28 @@ private void compareAnnotation(SpdxDocument spdxDocument, * as well as the relationshipsEquals flag and sets the differenceFound to * true if a difference was found for a newly added item * @param spdxDocument document containing the item - * @param relationships - * @throws InvalidSPDXAnalysisException + * @param relationships relationships to compare + * @throws InvalidSPDXAnalysisException on SPDX parsing error */ private void compareRelationships(SpdxDocument spdxDocument, Collection relationships) throws InvalidSPDXAnalysisException { - Map> uniqueDocRelationship = this.uniqueRelationships.get(spdxDocument); - if (uniqueDocRelationship == null) { - uniqueDocRelationship = new HashMap<>(); - this.uniqueRelationships.put(spdxDocument, uniqueDocRelationship); - } - Iterator> iter = this.documentItem.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - Map> uniqueCompareRelationship = this.uniqueRelationships.get(entry.getKey()); - if (uniqueCompareRelationship == null) { - uniqueCompareRelationship = new HashMap<>(); - this.uniqueRelationships.put(entry.getKey(), uniqueCompareRelationship); - } - Collection compareRelationships = entry.getValue().getRelationships(); - List uniqueRelationships = SpdxComparer.findUniqueRelationships(relationships, compareRelationships); - if (uniqueRelationships.size() > 0) { - this.relationshipsEquals = false; - this.itemDifferenceFound = true; - } - uniqueDocRelationship.put(entry.getKey(), uniqueRelationships); - uniqueRelationships = SpdxComparer.findUniqueRelationships(compareRelationships, relationships); - if (uniqueRelationships.size() > 0) { - this.relationshipsEquals = false; - this.itemDifferenceFound = true; - } - uniqueCompareRelationship.put(spdxDocument, uniqueRelationships); - } + Map> uniqueDocRelationship = this.uniqueRelationships.computeIfAbsent(spdxDocument, k -> new HashMap<>()); + for (Entry entry : this.documentItem.entrySet()) { + Map> uniqueCompareRelationship = this.uniqueRelationships.computeIfAbsent(entry.getKey(), k -> new HashMap<>()); + Collection compareRelationships = entry.getValue().getRelationships(); + List uniqueRelationships = SpdxComparer.findUniqueRelationships(relationships, compareRelationships); + if (!uniqueRelationships.isEmpty()) { + this.relationshipsEquals = false; + this.itemDifferenceFound = true; + } + uniqueDocRelationship.put(entry.getKey(), uniqueRelationships); + uniqueRelationships = SpdxComparer.findUniqueRelationships(compareRelationships, relationships); + if (!uniqueRelationships.isEmpty()) { + this.relationshipsEquals = false; + this.itemDifferenceFound = true; + } + uniqueCompareRelationship.put(spdxDocument, uniqueRelationships); + } } /** @@ -231,51 +209,41 @@ private void compareRelationships(SpdxDocument spdxDocument, * as well as the seenLicenseEquals flag and sets the differenceFound to * true if a difference was found for a newly added item * @param spdxDocument document containing the item - * @param licenses - * @throws SpdxCompareException - * @throws InvalidSPDXAnalysisException + * @param licenses licenses to compare + * @throws SpdxCompareException on compare errors + * @throws InvalidSPDXAnalysisException on SPDX parsing error */ private void compareLicenseInfosInFiles(SpdxDocument spdxDocument, Collection licenses) throws SpdxCompareException, InvalidSPDXAnalysisException { - Map> uniqueDocLicenses = - this.uniqueLicenseInfosInFiles.get(spdxDocument); - if (uniqueDocLicenses == null) { - uniqueDocLicenses = new HashMap<>(); - this.uniqueLicenseInfosInFiles.put(spdxDocument, uniqueDocLicenses); - } - Iterator> iter = this.documentItem.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - Map> uniqueCompareLicenses = - this.uniqueLicenseInfosInFiles.get(entry.getKey()); - if (uniqueCompareLicenses == null) { - uniqueCompareLicenses = new HashMap<>(); - this.uniqueLicenseInfosInFiles.put(entry.getKey(), uniqueCompareLicenses); - } - Collection compareLicenses = entry.getValue().getLicenseInfoFromFiles(); - List uniqueInDoc = new ArrayList<>(); - List uniqueInCompare = new ArrayList<>(); - Map licenseXlationMap = this.extractedLicenseIdMap.get(spdxDocument).get(entry.getKey()); - compareLicenseCollections(licenses, compareLicenses, uniqueInDoc, uniqueInCompare, licenseXlationMap); - if (uniqueInDoc.size() > 0 || uniqueInCompare.size() > 0) { - this.seenLicenseEquals = false; - this.itemDifferenceFound = true; - } - uniqueDocLicenses.put(entry.getKey(), uniqueInDoc); - uniqueCompareLicenses.put(spdxDocument, uniqueInCompare); - } + Map> uniqueDocLicenses = + this.uniqueLicenseInfosInFiles.computeIfAbsent(spdxDocument, k -> new HashMap<>()); + for (Entry entry : this.documentItem.entrySet()) { + Map> uniqueCompareLicenses = + this.uniqueLicenseInfosInFiles.computeIfAbsent(entry.getKey(), k -> new HashMap<>()); + Collection compareLicenses = entry.getValue().getLicenseInfoFromFiles(); + List uniqueInDoc = new ArrayList<>(); + List uniqueInCompare = new ArrayList<>(); + Map licenseXlationMap = this.extractedLicenseIdMap.get(spdxDocument).get(entry.getKey()); + compareLicenseCollections(licenses, compareLicenses, uniqueInDoc, uniqueInCompare, licenseXlationMap); + if (!uniqueInDoc.isEmpty() || !uniqueInCompare.isEmpty()) { + this.seenLicenseEquals = false; + this.itemDifferenceFound = true; + } + uniqueDocLicenses.put(entry.getKey(), uniqueInDoc); + uniqueCompareLicenses.put(spdxDocument, uniqueInCompare); + } } /** * Compares to arrays of licenses updating the alUniqueA and alUniqueB to * include any licenses found in A but not B and B but not A resp. - * @param licensesA - * @param licensesB - * @param alUniqueA - * @param alUniqueB - * @param licenseXlationMap - * @throws SpdxCompareException - * @throws InvalidSPDXAnalysisException + * @param licensesA A licenses to compare + * @param licensesB B licenses to compare + * @param alUniqueA list of licenses that are in A but not in B + * @param alUniqueB list of licenses that are in B but not in A + * @param licenseXlationMap map to translate non-listed license IDs + * @throws SpdxCompareException on compare errors + * @throws InvalidSPDXAnalysisException on SPDX parsing error */ private void compareLicenseCollections(Collection licensesA, Collection licensesB, @@ -331,10 +299,10 @@ public boolean isSeenLicenseEquals() throws SpdxCompareException { /** * Get any licenses found in docA but not in docB - * @param docA - * @param docB - * @return - * @throws SpdxCompareException + * @param docA A document to compare + * @param docB B document to compare + * @return any licenses found in docA but not in docB + * @throws SpdxCompareException on compare errors */ public List getUniqueSeenLicenses(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { checkInProgress(); @@ -375,12 +343,12 @@ public boolean isCopyrightsEquals() throws SpdxCompareException { public boolean isLicenseCommmentsEquals() throws SpdxCompareException { checkInProgress(); checkCompareMade(); - return licenseCommmentsEquals; + return licenseCommentsEquals; } /** * checks to make sure there is not a compare in progress - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors * */ protected void checkInProgress() throws SpdxCompareException { @@ -393,15 +361,15 @@ protected void checkInProgress() throws SpdxCompareException { * @throws SpdxCompareException if no comparisons have been made */ protected void checkCompareMade() throws SpdxCompareException { - if (this.documentItem.entrySet().size() < 1) { + if (this.documentItem.isEmpty()) { throw new SpdxCompareException("Trying to obtain results of a file compare before a file compare has been performed"); } } /** - * @return - * @throws SpdxCompareException + * @return true if any difference is found in the item + * @throws SpdxCompareException on compare error */ public boolean isDifferenceFound() throws SpdxCompareException { checkInProgress(); @@ -422,9 +390,9 @@ public boolean isInProgress() throws SpdxCompareException { /** * Get the item contained by the document doc - * @param doc - * @return - * @throws SpdxCompareException + * @param doc document containing the item + * @return the item contained by the document doc + * @throws SpdxCompareException on compare error */ public SpdxItem getItem(SpdxDocument doc) throws SpdxCompareException { checkInProgress(); @@ -444,10 +412,10 @@ public boolean isRelationshipsEquals() throws SpdxCompareException { /** * Get relationships that are in docA but not in docB - * @param docA - * @param docB - * @return - * @throws SpdxCompareException + * @param docA A document to compare + * @param docB B document to compare + * @return relationships that are in docA but not in docB + * @throws SpdxCompareException on compare error */ public List getUniqueRelationship(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { checkInProgress(); @@ -476,7 +444,7 @@ public boolean isAnnotationsEquals() throws SpdxCompareException { /** * @return the attributionTextEquals - * @throws SpdxCompareException + * @throws SpdxCompareException on compare error */ public boolean isAttributionTextEquals() throws SpdxCompareException { checkInProgress(); @@ -486,10 +454,10 @@ public boolean isAttributionTextEquals() throws SpdxCompareException { /** * Get annotations that are in docA but not in docB - * @param docA - * @param docB - * @return - * @throws SpdxCompareException + * @param docA A document to compare + * @param docB B document to compare + * @return annotations that are in docA but not in docB + * @throws SpdxCompareException on compare error */ public List getUniqueAnnotations(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { checkInProgress(); diff --git a/src/main/java/org/spdx/utility/compare/SpdxItemDifference.java b/src/main/java/org/spdx/utility/compare/SpdxItemDifference.java index 35452cee..a0b80dd8 100644 --- a/src/main/java/org/spdx/utility/compare/SpdxItemDifference.java +++ b/src/main/java/org/spdx/utility/compare/SpdxItemDifference.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. @@ -33,25 +33,25 @@ */ public class SpdxItemDifference { - private String name; - private String commentA; - private String commentB; - private String concludedLicenseA; - private String concludedLicenseB; - private boolean concludedLicenseEquals; + private final String name; + private final String commentA; + private final String commentB; + private final String concludedLicenseA; + private final String concludedLicenseB; + private final boolean concludedLicenseEquals; private String copyrightA; private String copyrightB; - private String licenseCommentsA; - private String licenseCommentsB; - private boolean seenLicensesEqual; - private List uniqueSeenLicensesA; - private List uniqueSeenLicensesB; - private boolean relationshipsEquals; - private List uniqueRelationshipA; - private List uniqueRelationshipB; - private boolean annotationsEquals; - private List uniqueAnnotationsA; - private List uniqueAnnotationsB; + private final String licenseCommentsA; + private final String licenseCommentsB; + private final boolean seenLicensesEqual; + private final List uniqueSeenLicensesA; + private final List uniqueSeenLicensesB; + private final boolean relationshipsEquals; + private final List uniqueRelationshipA; + private final List uniqueRelationshipB; + private final boolean annotationsEquals; + private final List uniqueAnnotationsA; + private final List uniqueAnnotationsB; public SpdxItemDifference(SpdxItem itemA, SpdxItem itemB, boolean concludedLicensesEqual, boolean seenLicensesEqual, @@ -63,25 +63,13 @@ public SpdxItemDifference(SpdxItem itemA, SpdxItem itemB, boolean annotationsEquals, List uniqueAnnotationsA, List uniqueAnnotationsB - ) throws SpdxCompareException, InvalidSPDXAnalysisException { + ) throws InvalidSPDXAnalysisException { Optional oNameA = itemA.getName(); - if (oNameA.isPresent()) { - this.name = oNameA.get(); - } else { - this.name = ""; - } + this.name = oNameA.orElse(""); Optional oCommentA = itemA.getComment(); - if (oCommentA.isPresent()) { - this.commentA = oCommentA.get(); - } else { - this.commentA = ""; - } + this.commentA = oCommentA.orElse(""); Optional oCommentB = itemB.getComment(); - if (oCommentB.isPresent()) { - this.commentB = oCommentB.get(); - } else { - this.commentB = ""; - } + this.commentB = oCommentB.orElse(""); this.concludedLicenseA = itemA.getLicenseConcluded().toString(); this.concludedLicenseB = itemB.getLicenseConcluded().toString(); this.concludedLicenseEquals = concludedLicensesEqual; @@ -94,17 +82,9 @@ public SpdxItemDifference(SpdxItem itemA, SpdxItem itemB, this.copyrightB = ""; } Optional oLicenseCommentsA = itemA.getLicenseComments(); - if ( oLicenseCommentsA.isPresent()) { - this.licenseCommentsA = oLicenseCommentsA.get(); - } else { - this.licenseCommentsA = ""; - } + this.licenseCommentsA = oLicenseCommentsA.orElse(""); Optional oLicenseCommentsB = itemB.getLicenseComments(); - if (oLicenseCommentsB.isPresent()) { - this.licenseCommentsB = oLicenseCommentsB.get(); - } else { - this.licenseCommentsB = ""; - } + this.licenseCommentsB = oLicenseCommentsB.orElse(""); this.seenLicensesEqual = seenLicensesEqual; this.uniqueSeenLicensesA = uniqueSeenLicensesA; this.uniqueSeenLicensesB = uniqueSeenLicensesB; diff --git a/src/main/java/org/spdx/utility/compare/SpdxLicenseDifference.java b/src/main/java/org/spdx/utility/compare/SpdxLicenseDifference.java index b6305c17..0d0346e5 100644 --- a/src/main/java/org/spdx/utility/compare/SpdxLicenseDifference.java +++ b/src/main/java/org/spdx/utility/compare/SpdxLicenseDifference.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,8 +31,8 @@ */ public class SpdxLicenseDifference { - private String licenseText; - private String licenseNameA; + private final String licenseText; + private final String licenseNameA; /** * @return the licenseText */ @@ -117,21 +117,21 @@ public boolean isSourceUrlsEqual() { return sourceUrlsEqual; } - private String licenseNameB; - private boolean licenseNamesEqual; - private String IdA; - private String IdB; - private String commentA; - private String commentB; - private boolean commentsEqual; - private Collection sourceUrlsA; - private Collection sourceUrlsB; - private boolean sourceUrlsEqual; + private final String licenseNameB; + private final boolean licenseNamesEqual; + private final String IdA; + private final String IdB; + private final String commentA; + private final String commentB; + private final boolean commentsEqual; + private final Collection sourceUrlsA; + private final Collection sourceUrlsB; + private final boolean sourceUrlsEqual; /** - * @param licenseA - * @param licenseB - * @throws InvalidSPDXAnalysisException + * @param licenseA A license to compare + * @param licenseB B license to compare + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ public SpdxLicenseDifference( ExtractedLicenseInfo licenseA, diff --git a/src/main/java/org/spdx/utility/compare/SpdxPackageComparer.java b/src/main/java/org/spdx/utility/compare/SpdxPackageComparer.java index 73107965..28762975 100644 --- a/src/main/java/org/spdx/utility/compare/SpdxPackageComparer.java +++ b/src/main/java/org/spdx/utility/compare/SpdxPackageComparer.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. @@ -65,70 +65,66 @@ public class SpdxPackageComparer extends SpdxItemComparer { /** * Map of documents to a map of documents with unique checksums */ - private Map>> uniqueChecksums = new HashMap<>(); + private final Map>> uniqueChecksums = new HashMap<>(); /** * Map of documents to a map of documents with unique files */ - private Map>> uniqueFiles = new HashMap<>(); + private final Map>> uniqueFiles = new HashMap<>(); /** * Map of all file differences founds between any two spdx document packages */ - private Map>> fileDifferences = new HashMap<>(); + private final Map>> fileDifferences = new HashMap<>(); /** * Map of documents to a map of documents with unique external refs */ - private Map>> uniqueExternalRefs = new HashMap<>(); + private final Map>> uniqueExternalRefs = new HashMap<>(); /** * Map of documents to a map of documents with external refs with differences */ - private Map>> externalRefDifferences = new HashMap<>(); - private Comparator externalRefTypeNameComparator = new Comparator() { - - @Override - public int compare(ExternalRef arg0, ExternalRef arg1) { - if (arg0 == null) { - if (arg1 == null) { - return 0; - } else { - return -1; - } - } - if (arg1 == null) { - return 1; - } - try { - if (arg0.getReferenceType() == null) { - if (arg1.getReferenceType() != null) { - return -1; - } - } else { - int retval = arg0.getReferenceType().compareTo(arg1.getReferenceType()); - if (retval != 0) { - return retval; - } - } - } catch (InvalidSPDXAnalysisException e) { - // just compare the locators - } - try { - if (arg0.getReferenceLocator() == null) { - if (arg1.getReferenceLocator() == null) { - return 0; - } else { - return -1; - } - } else { - return arg0.getReferenceLocator().compareTo(arg1.getReferenceLocator()); - } - } catch (InvalidSPDXAnalysisException e) { - return -1; - } - } - }; + private final Map>> externalRefDifferences = new HashMap<>(); + private final Comparator externalRefTypeNameComparator = (Comparator) (arg0, arg1) -> { + if (arg0 == null) { + if (arg1 == null) { + return 0; + } else { + return -1; + } + } + if (arg1 == null) { + return 1; + } + try { + if (arg0.getReferenceType() == null) { + if (arg1.getReferenceType() != null) { + return -1; + } + } else { + int retval = arg0.getReferenceType().compareTo(arg1.getReferenceType()); + if (retval != 0) { + return retval; + } + } + } catch (InvalidSPDXAnalysisException e) { + // just compare the locators + } + try { + if (arg0.getReferenceLocator() == null) { + if (arg1.getReferenceLocator() == null) { + return 0; + } else { + return -1; + } + } else { + return arg0.getReferenceLocator().compareTo(arg1.getReferenceLocator()); + } + } catch (InvalidSPDXAnalysisException e) { + return -1; + } + }; /** * @param extractedLicenseIdMap map of all extracted license IDs for any SPDX documents to be added to the comparer @@ -141,8 +137,8 @@ public SpdxPackageComparer(Map packageName = spdxPackage.getName(); if (this.name == null && packageName.isPresent()) { this.name = packageName.get(); - } else if (!Objects.equals(this.name,packageName.get())) { + } else if (!Objects.equals(this.name,packageName.orElse(""))) { throw new SpdxCompareException("Names do not match for item being added to comparer: "+ packageName+", expecting "+this.name); } @@ -250,75 +246,56 @@ public void addDocumentPackage(SpdxDocument spdxDocument, } /** - * @param spdxDocument - * @param externalRefs - * @throws InvalidSPDXAnalysisException + * @param spdxDocument document containing the external refs + * @param externalRefCollection collection of external refs to compare + * @throws InvalidSPDXAnalysisException on SPDX parsing error */ private void compareNewPackageExternalRefs(SpdxDocument spdxDocument, Collection externalRefCollection) throws InvalidSPDXAnalysisException { - ExternalRef[] externalRefs = externalRefCollection.toArray(new ExternalRef[externalRefCollection.size()]); + ExternalRef[] externalRefs = externalRefCollection.toArray(new ExternalRef[0]); Arrays.sort(externalRefs); - Map> docUniqueExternalRefs = this.uniqueExternalRefs.get(spdxDocument); - if (docUniqueExternalRefs == null) { - docUniqueExternalRefs = new HashMap<>(); - this.uniqueExternalRefs.put(spdxDocument, docUniqueExternalRefs); - } - Map> docExternalRefDiffs = this.externalRefDifferences.get(spdxDocument); - if (docExternalRefDiffs == null) { - docExternalRefDiffs = new HashMap<>(); - this.externalRefDifferences.put(spdxDocument, docExternalRefDiffs); - } - - Iterator> iter = this.documentItem.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - if (entry.getValue() instanceof SpdxPackage) { - Collection compareExternalRefCollection = ((SpdxPackage)entry.getValue()).getExternalRefs(); - ExternalRef[] compareExternalRefs = compareExternalRefCollection.toArray(new ExternalRef[compareExternalRefCollection.size()]); - Arrays.sort(compareExternalRefs); - List externalRefDifferences = findExternalRefDifferences(spdxDocument, entry.getKey(), + Map> docUniqueExternalRefs = this.uniqueExternalRefs.computeIfAbsent(spdxDocument, k -> new HashMap<>()); + Map> docExternalRefDiffs = this.externalRefDifferences.computeIfAbsent(spdxDocument, k -> new HashMap<>()); + + for (Entry entry : this.documentItem.entrySet()) { + if (entry.getValue() instanceof SpdxPackage) { + Collection compareExternalRefCollection = ((SpdxPackage) entry.getValue()).getExternalRefs(); + ExternalRef[] compareExternalRefs = compareExternalRefCollection.toArray(new ExternalRef[0]); + Arrays.sort(compareExternalRefs); + List externalRefDifferences = findExternalRefDifferences( externalRefs, compareExternalRefs); - if (externalRefDifferences.size() > 0) { - this.externalRefsEquals = false; - this.differenceFound = true; - } - docExternalRefDiffs.put(entry.getKey(), externalRefDifferences); - Map> compareExternalRefDiffs = this.externalRefDifferences.get(entry.getKey()); - if (compareExternalRefDiffs == null) { - compareExternalRefDiffs = new HashMap<>(); - this.externalRefDifferences.put(entry.getKey(), compareExternalRefDiffs); - } - compareExternalRefDiffs.put(spdxDocument, externalRefDifferences); - - List uniqueRefs = findUniqueExternalRefs(externalRefs, compareExternalRefs); - if (uniqueRefs.size() > 0) { - this.externalRefsEquals = false; - this.differenceFound = true; - } - uniqueExternalRefs.put(entry.getKey(), docUniqueExternalRefs); - Map> compareUniqueRefs = this.uniqueExternalRefs.get(entry.getKey()); - if (compareUniqueRefs == null) { - compareUniqueRefs = new HashMap<>(); - this.uniqueExternalRefs.put(entry.getKey(), compareUniqueRefs); - } - uniqueRefs = findUniqueExternalRefs(compareExternalRefs, externalRefs); - if (uniqueRefs.size() > 0) { - this.externalRefsEquals = false; - this.differenceFound = true; - } - compareUniqueRefs.put(spdxDocument, uniqueRefs); - } - } - } - - /** - * @param compareExternalRefs - * @param externalRefs - * @return - * @throws InvalidSPDXAnalysisException - */ + if (!externalRefDifferences.isEmpty()) { + this.externalRefsEquals = false; + this.differenceFound = true; + } + docExternalRefDiffs.put(entry.getKey(), externalRefDifferences); + Map> compareExternalRefDiffs = this.externalRefDifferences.computeIfAbsent(entry.getKey(), k -> new HashMap<>()); + compareExternalRefDiffs.put(spdxDocument, externalRefDifferences); + + List uniqueRefs = findUniqueExternalRefs(externalRefs, compareExternalRefs); + if (!uniqueRefs.isEmpty()) { + this.externalRefsEquals = false; + this.differenceFound = true; + } + uniqueExternalRefs.put(entry.getKey(), docUniqueExternalRefs); + Map> compareUniqueRefs = this.uniqueExternalRefs.computeIfAbsent(entry.getKey(), k -> new HashMap<>()); + uniqueRefs = findUniqueExternalRefs(compareExternalRefs, externalRefs); + if (!uniqueRefs.isEmpty()) { + this.externalRefsEquals = false; + this.differenceFound = true; + } + compareUniqueRefs.put(spdxDocument, uniqueRefs); + } + } + } + + /** + * @param externalRefsA A external refs to compare + * @param externalRefsB B external refs to compare + * @return list of external refs found in A but not B + */ private List findUniqueExternalRefs( - ExternalRef[] externalRefsA, ExternalRef[] externalRefsB) throws InvalidSPDXAnalysisException { + ExternalRef[] externalRefsA, ExternalRef[] externalRefsB) { int bIndex = 0; int aIndex = 0; List alRetval = new ArrayList<>(); @@ -346,15 +323,12 @@ private List findUniqueExternalRefs( } /** - * @param spdxDocument - * @param key - * @param externalRefs - * @param compareExternalRefs - * @return - * @throws InvalidSPDXAnalysisException + * @param externalRefsA A external refs to compare + * @param externalRefsB B external refs to compare + * @return list of differences between external refs + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private List findExternalRefDifferences( - SpdxDocument spdxDocument, SpdxDocument key, ExternalRef[] externalRefsA, ExternalRef[] externalRefsB) throws InvalidSPDXAnalysisException { List retval = new ArrayList<>(); int aIndex = 0; @@ -382,102 +356,78 @@ private List findExternalRefDifferences( } /** - * @param spdxDocument - * @param filesCollection - * @throws SpdxCompareException - * @throws InvalidSPDXAnalysisException + * @param spdxDocument document containing the files + * @param filesCollection files to compare + * @throws SpdxCompareException on compare error + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private void compareNewPackageFiles(SpdxDocument spdxDocument, Collection filesCollection) throws SpdxCompareException, InvalidSPDXAnalysisException { - SpdxFile[] files = filesCollection.toArray(new SpdxFile[filesCollection.size()]); + SpdxFile[] files = filesCollection.toArray(new SpdxFile[0]); Arrays.sort(files); - Map> docUniqueFiles = this.uniqueFiles.get(spdxDocument); - if (docUniqueFiles == null) { - docUniqueFiles = new HashMap<>(); - this.uniqueFiles.put(spdxDocument, docUniqueFiles); - } - Map> docDifferentFiles = this.fileDifferences.get(spdxDocument); - if (docDifferentFiles == null) { - docDifferentFiles = new HashMap<>(); - this.fileDifferences.put(spdxDocument, docDifferentFiles); - } - Iterator> iter = this.documentItem.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - if (entry.getValue() instanceof SpdxPackage) { - Collection compareFilesCollection = ((SpdxPackage)entry.getValue()).getFiles(); - SpdxFile[] compareFiles = compareFilesCollection.toArray(new SpdxFile[compareFilesCollection.size()]); - Arrays.sort(compareFiles); - List fileDifferences = - SpdxComparer.findFileDifferences(spdxDocument, entry.getKey(), files, compareFiles, this.extractedLicenseIdMap); - if (fileDifferences.size() > 0) { - this.packageFilesEquals = false; - this.differenceFound = true; - } - docDifferentFiles.put(entry.getKey(), fileDifferences); - Map> compareDifferentFiles = this.fileDifferences.get(entry.getKey()); - if (compareDifferentFiles == null) { - compareDifferentFiles = new HashMap<>(); - this.fileDifferences.put(entry.getKey(), compareDifferentFiles); - } - compareDifferentFiles.put(spdxDocument, fileDifferences); - List uniqueFiles = SpdxComparer.findUniqueFiles(files, compareFiles); - if (uniqueFiles.size() > 0) { - this.packageFilesEquals = false; - this.differenceFound = true; - } - docUniqueFiles.put(entry.getKey(), uniqueFiles); - Map> compareUniqueFiles = this.uniqueFiles.get(entry.getKey()); - if (compareUniqueFiles == null) { - compareUniqueFiles = new HashMap<>(); - this.uniqueFiles.put(entry.getKey(), compareUniqueFiles); - } - uniqueFiles = SpdxComparer.findUniqueFiles(compareFiles, files); - if (uniqueFiles.size() > 0) { - this.packageFilesEquals = false; - this.differenceFound = true; - } - compareUniqueFiles.put(spdxDocument, uniqueFiles); - } - } + Map> docUniqueFiles = this.uniqueFiles.computeIfAbsent(spdxDocument, k -> new HashMap<>()); + Map> docDifferentFiles = this.fileDifferences.computeIfAbsent(spdxDocument, k -> new HashMap<>()); + for (Entry entry : this.documentItem.entrySet()) { + if (entry.getValue() instanceof SpdxPackage) { + Collection compareFilesCollection = ((SpdxPackage) entry.getValue()).getFiles(); + SpdxFile[] compareFiles = compareFilesCollection.toArray(new SpdxFile[0]); + Arrays.sort(compareFiles); + List fileDifferences = + SpdxComparer.findFileDifferences(spdxDocument, entry.getKey(), files, compareFiles, this.extractedLicenseIdMap); + if (!fileDifferences.isEmpty()) { + this.packageFilesEquals = false; + this.differenceFound = true; + } + docDifferentFiles.put(entry.getKey(), fileDifferences); + Map> compareDifferentFiles = this.fileDifferences.computeIfAbsent(entry.getKey(), k -> new HashMap<>()); + compareDifferentFiles.put(spdxDocument, fileDifferences); + List uniqueFiles = SpdxComparer.findUniqueFiles(files, compareFiles); + if (!uniqueFiles.isEmpty()) { + this.packageFilesEquals = false; + this.differenceFound = true; + } + docUniqueFiles.put(entry.getKey(), uniqueFiles); + Map> compareUniqueFiles = this.uniqueFiles.computeIfAbsent(entry.getKey(), k -> new HashMap<>()); + uniqueFiles = SpdxComparer.findUniqueFiles(compareFiles, files); + if (!uniqueFiles.isEmpty()) { + this.packageFilesEquals = false; + this.differenceFound = true; + } + compareUniqueFiles.put(spdxDocument, uniqueFiles); + } + } } /** * Compare the checks for a new package being added to the existing * package checksums filling in the unique checksums map - * @param spdxDocument - * @param checksums - * @throws SpdxCompareException + * @param spdxDocument document containing the checksums + * @param checksums checksums to compare + * @throws SpdxCompareException on compare errors */ private void compareNewPackageChecksums(SpdxDocument spdxDocument, Collection checksums) throws SpdxCompareException { try { Map> docUniqueChecksums = new HashMap<>(); this.uniqueChecksums.put(spdxDocument, docUniqueChecksums); - Iterator> iter = this.documentItem.entrySet().iterator(); - while (iter.hasNext()) { - Entry entry = iter.next(); - if (entry.getValue() instanceof SpdxPackage) { - Collection compareChecksums = ((SpdxPackage)entry.getValue()).getChecksums(); - List uniqueChecksums = SpdxComparer.findUniqueChecksums(checksums, compareChecksums); - if (uniqueChecksums.size() > 0) { - this.packageChecksumsEquals = false; - this.differenceFound = true; - } - docUniqueChecksums.put(entry.getKey(), uniqueChecksums); - Map> compareUniqueChecksums = this.uniqueChecksums.get(entry.getKey()); - if (compareUniqueChecksums == null) { - compareUniqueChecksums = new HashMap<>(); - this.uniqueChecksums.put(entry.getKey(), compareUniqueChecksums); - } - uniqueChecksums = SpdxComparer.findUniqueChecksums(compareChecksums, checksums); - if (uniqueChecksums.size() > 0) { - this.packageChecksumsEquals = false; - this.differenceFound = true; - } - compareUniqueChecksums.put(spdxDocument, uniqueChecksums); - } - } + for (Entry entry : this.documentItem.entrySet()) { + if (entry.getValue() instanceof SpdxPackage) { + Collection compareChecksums = ((SpdxPackage) entry.getValue()).getChecksums(); + List uniqueChecksums = SpdxComparer.findUniqueChecksums(checksums, compareChecksums); + if (!uniqueChecksums.isEmpty()) { + this.packageChecksumsEquals = false; + this.differenceFound = true; + } + docUniqueChecksums.put(entry.getKey(), uniqueChecksums); + Map> compareUniqueChecksums = this.uniqueChecksums.computeIfAbsent(entry.getKey(), k -> new HashMap<>()); + uniqueChecksums = SpdxComparer.findUniqueChecksums(compareChecksums, checksums); + if (!uniqueChecksums.isEmpty()) { + this.packageChecksumsEquals = false; + this.differenceFound = true; + } + compareUniqueChecksums.put(spdxDocument, uniqueChecksums); + } + } } catch (InvalidSPDXAnalysisException e) { throw new SpdxCompareException("SPDX error getting package checksums: "+e.getMessage(),e); } @@ -493,7 +443,7 @@ public boolean isInProgress() { /** * @return the differenceFound - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ @Override public boolean isDifferenceFound() throws SpdxCompareException { @@ -503,7 +453,7 @@ public boolean isDifferenceFound() throws SpdxCompareException { /** * checks to make sure there is not a compare in progress - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors * */ @Override @@ -515,7 +465,7 @@ protected void checkInProgress() throws SpdxCompareException { } /** * @return the packageVersionsEquals - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ public boolean isPackageVersionsEquals() throws SpdxCompareException { checkInProgress(); @@ -547,7 +497,7 @@ public boolean isPackageDownloadLocationsEquals() throws SpdxCompareException { } /** - * @return the packageVerificationCodeesEquals + * @return the packageVerificationCodesEquals */ public boolean isPackageVerificationCodesEquals() throws SpdxCompareException { checkInProgress(); @@ -558,7 +508,7 @@ public boolean isPackageVerificationCodesEquals() throws SpdxCompareException { /** * @return the filesAnalyzedEquals - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ public boolean isFilesAnalyzedEquals() throws SpdxCompareException { checkInProgress(); @@ -624,7 +574,7 @@ public boolean isPackageHomePagesEquals() throws SpdxCompareException { /** * @return the externalRefsEquals - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ public boolean isExternalRefsEquals() throws SpdxCompareException { checkInProgress(); @@ -633,12 +583,12 @@ public boolean isExternalRefsEquals() throws SpdxCompareException { /** * Return the package associated with the document - * @param document - * @return The document associated with the document + * @param document document + * @return The package associated with the document */ - public SpdxPackage getDocPackage(SpdxDocument document) throws SpdxCompareException { + public SpdxPackage getDocPackage(SpdxDocument document) { SpdxItem retItem = this.documentItem.get(document); - if (retItem != null && retItem instanceof SpdxPackage) { + if (retItem instanceof SpdxPackage) { return (SpdxPackage)retItem; } else { return null; @@ -700,9 +650,9 @@ public boolean isPackageFilesEquals() throws SpdxCompareException { /** * Get any fileDifferences which are in docA but not in docB - * @param docA - * @param docB - * @return + * @param docA A document to compare + * @param docB B document compare + * @return any fileDifferences which are in docA but not in docB */ public List getFileDifferences(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { @@ -721,9 +671,9 @@ public List getFileDifferences(SpdxDocument docA, /** * Return any unique files by name which are in docA but not in docB - * @param docA - * @param docB - * @return + * @param docA A document to compare + * @param docB B document compare + * @return any unique files by name which are in docA but not in docB */ public List getUniqueFiles(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { checkInProgress(); @@ -739,7 +689,7 @@ public List getUniqueFiles(SpdxDocument docA, SpdxDocument docB) throw } /** - * @return + * @return package name */ public String getPackageName() throws SpdxCompareException { checkInProgress(); @@ -747,8 +697,8 @@ public String getPackageName() throws SpdxCompareException { } /** - * @return - * @throws SpdxCompareException + * @return number of package + * @throws SpdxCompareException on compare errors */ public int getNumPackages() throws SpdxCompareException { checkInProgress(); diff --git a/src/main/java/org/spdx/utility/compare/SpdxSnippetComparer.java b/src/main/java/org/spdx/utility/compare/SpdxSnippetComparer.java index f53f85e1..a719267d 100644 --- a/src/main/java/org/spdx/utility/compare/SpdxSnippetComparer.java +++ b/src/main/java/org/spdx/utility/compare/SpdxSnippetComparer.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. @@ -65,7 +65,7 @@ public SpdxSnippetComparer(Map unique = this.uniqueSnippetFromFile.get(document2); - if (unique == null) { - unique = new HashMap<>(); - this.uniqueSnippetFromFile.put(document2, unique); - } - unique.put(spdxDocument, fromFile2); + Map unique = this.uniqueSnippetFromFile.computeIfAbsent(document2, k -> new HashMap<>()); + unique.put(spdxDocument, fromFile2); this.snippetFromFilesEquals = false; } } else if (fromFile2 == null) { - Map unique = this.uniqueSnippetFromFile.get(spdxDocument); - if (unique == null) { - unique = new HashMap<>(); - this.uniqueSnippetFromFile.put(spdxDocument, unique); - } - unique.put(document2, fromFile); + Map unique = this.uniqueSnippetFromFile.computeIfAbsent(spdxDocument, k -> new HashMap<>()); + unique.put(document2, fromFile); this.snippetFromFilesEquals = false; } else if (!Objects.equals(fromFile2.getName(), fromFile.getName())) { - Map unique = this.uniqueSnippetFromFile.get(spdxDocument); - if (unique == null) { - unique = new HashMap<>(); - this.uniqueSnippetFromFile.put(spdxDocument, unique); - } - unique.put(document2, fromFile); - Map unique2 = this.uniqueSnippetFromFile.get(document2); - if (unique2 == null) { - unique2 = new HashMap<>(); - this.uniqueSnippetFromFile.put(document2, unique2); - } - unique2.put(spdxDocument, fromFile2); + Map unique = this.uniqueSnippetFromFile.computeIfAbsent(spdxDocument, k -> new HashMap<>()); + unique.put(document2, fromFile); + Map unique2 = this.uniqueSnippetFromFile.computeIfAbsent(document2, k -> new HashMap<>()); + unique2.put(spdxDocument, fromFile2); this.snippetFromFilesEquals = false; } else { SpdxFileComparer fileCompare = new SpdxFileComparer(this.extractedLicenseIdMap); @@ -183,12 +167,8 @@ private void compareSnippetFromFiles(SpdxDocument spdxDocument, SpdxFile fromFil this.snippetFromFilesEquals = false; Map comparerMap = new HashMap<>(); this.snippetFromFileDifferences.put(spdxDocument, comparerMap); - Map comparerMap2 = this.snippetFromFileDifferences.get(document2); - if (comparerMap2 == null) { - comparerMap2 = new HashMap<>(); - this.snippetFromFileDifferences.put(document2, comparerMap2); - } - comparerMap.put(document2, fileCompare.getFileDifference(spdxDocument, document2)); + Map comparerMap2 = this.snippetFromFileDifferences.computeIfAbsent(document2, k -> new HashMap<>()); + comparerMap.put(document2, fileCompare.getFileDifference(spdxDocument, document2)); comparerMap2.put(spdxDocument, fileCompare.getFileDifference(document2, spdxDocument)); } } @@ -199,7 +179,7 @@ private void compareSnippetFromFiles(SpdxDocument spdxDocument, SpdxFile fromFil /** * @return the differenceFound - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ @Override public boolean isDifferenceFound() throws SpdxCompareException { @@ -209,7 +189,7 @@ public boolean isDifferenceFound() throws SpdxCompareException { /** * checks to make sure there is not a compare in progress - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors * */ @Override @@ -222,10 +202,10 @@ protected void checkInProgress() throws SpdxCompareException { /** * Get any file difference for the Spdx Snippet From File between the two SPDX documents - * If the fileName is different, the they are considered unique files and the getUniqueSnippetFromFile should be called + * If the fileName is different, they are considered unique files and the getUniqueSnippetFromFile should be called * to obtain the unique file - * @param docA - * @param docB + * @param docA A document to compare + * @param docB B document to compare * @return the file difference or null if there is no file difference */ public SpdxFileDifference getSnippetFromFileDifference(SpdxDocument docA, @@ -273,9 +253,9 @@ public boolean isNameEquals() throws SpdxCompareException { /** * Get an SpdxFile that only exists in docA but not docB - * @param docA - * @param docB - * @return + * @param docA A document to compare + * @param docB B document to compare + * @return an SpdxFile that only exists in docA but not docB */ public SpdxFile getUniqueSnippetFromFile(SpdxDocument docA, SpdxDocument docB) throws SpdxCompareException { checkInProgress(); @@ -294,12 +274,12 @@ public int getNumSnippets() { } /** - * @param spdxDocument - * @return + * @param spdxDocument document containing the snippet + * @return snippet in the spdxDocument */ public SpdxSnippet getDocSnippet(SpdxDocument spdxDocument) { SpdxItem retItem = this.documentItem.get(spdxDocument); - if (retItem != null && retItem instanceof SpdxSnippet) { + if (retItem instanceof SpdxSnippet) { return (SpdxSnippet)retItem; } else { return null; diff --git a/src/main/java/org/spdx/utility/compare/TemplateRegexMatcher.java b/src/main/java/org/spdx/utility/compare/TemplateRegexMatcher.java index 4ca4f41a..27e47b1a 100644 --- a/src/main/java/org/spdx/utility/compare/TemplateRegexMatcher.java +++ b/src/main/java/org/spdx/utility/compare/TemplateRegexMatcher.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. @@ -38,11 +38,11 @@ /** * Constructs a regular expression from a license or exception template and provide a matching method * to see if code matching the template exists within the text provided - * + *

* Note that the regular expression assumes a fully normalized text string to match - * - * isTemplateMatchWithinText(String text) will return true if the text text matches the template - * + *

+ * isTemplateMatchWithinText(String text) will return true if the text matches the template + *

* getQuickMatchRegex() will return a regular expression with limited backtracking which can be used for a quick search * getCompleteRegex() will return a regular expression for the entire license where * getStartRegex(int wordLimit) will return a regular expression to match the beginning of a license @@ -57,13 +57,13 @@ public class TemplateRegexMatcher implements ILicenseTemplateOutputHandler { static final int WORD_LIMIT = 25; // number of words to search for in the quick match, beginning and end of the template - static final String REGEX_GLOBAL_MODIFIERS = "(?im)"; // ignore case and muti-line + static final String REGEX_GLOBAL_MODIFIERS = "(?im)"; // ignore case and multi-line interface RegexElement { } static class RegexList implements RegexElement { - private List elements = new ArrayList<>(); + private final List elements = new ArrayList<>(); public void addElement(RegexElement element) { elements.add(element); @@ -95,7 +95,7 @@ public String toString() { } static class RegexToken implements RegexElement { - private String token; + private final String token; public RegexToken(String token) { this.token = token.trim(); @@ -137,21 +137,21 @@ public void setPattern(String pattern) { } } - private String template; + private final String template; /** * Top level regex */ - private RegexList regexPatternList = new RegexList(); + private final RegexList regexPatternList = new RegexList(); private int optionalNestLevel = 0; - private List optionalGroups = new ArrayList<>(); + private final List optionalGroups = new ArrayList<>(); /** * Generates regular expressions from a license or exception template - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ public TemplateRegexMatcher(String template) throws SpdxCompareException { this.template = template; @@ -160,7 +160,7 @@ public TemplateRegexMatcher(String template) throws SpdxCompareException { /** * Parses the template generating the regular expression - * @throws SpdxCompareException + * @throws SpdxCompareException on compare errors */ private void parseTemplate() throws SpdxCompareException { try { @@ -176,7 +176,7 @@ private void parseTemplate() throws SpdxCompareException { * @return the complete regular expression for the template */ public String getCompleteRegex() { - return REGEX_GLOBAL_MODIFIERS + regexPatternList.toString(); + return REGEX_GLOBAL_MODIFIERS + regexPatternList; } /** @@ -204,7 +204,8 @@ public String getQuickMatchRegex(int wordLimit) { } if (numWords < largestContiguousText) { // Need to retry to get as much as we can - while (index < elementList.size() && numWords <= largestContiguousText) { + //noinspection ConstantValue + while (index < elementList.size() && numWords <= largestContiguousText) { RegexElement element = elementList.get(index++); result.addElement(element); if (element instanceof RegexToken) { @@ -215,11 +216,11 @@ public String getQuickMatchRegex(int wordLimit) { } } } - return REGEX_GLOBAL_MODIFIERS + result.toString(); + return REGEX_GLOBAL_MODIFIERS + result; } /** - * @param wordLimit number of non optional words to include in the pattern + * @param wordLimit number of non-optional words to include in the pattern * @return a regex to match the start of the license per the template */ public String getStartRegex(int wordLimit) { @@ -244,11 +245,11 @@ public String getStartRegex(int wordLimit) { } } } - return REGEX_GLOBAL_MODIFIERS + result.toString(); + return REGEX_GLOBAL_MODIFIERS + result; } /** - * @param wordLimit number of non optional words to include in the pattern + * @param wordLimit number of non-optional words to include in the pattern * @return a regex to match the end of the license per the template */ public String getEndRegex(int wordLimit) { @@ -265,7 +266,7 @@ public String getEndRegex(int wordLimit) { while (index < elementList.size()) { result.addElement(elementList.get(index++)); } - return REGEX_GLOBAL_MODIFIERS + result.toString(); + return REGEX_GLOBAL_MODIFIERS + result; } /** @@ -285,14 +286,14 @@ public boolean isTemplateMatchWithinText(String text) throws SpdxCompareExceptio } /** - * @param text + * @param text text to search for * @return the text matching the beginning and end regular expressions for the template. Null if there is no match. - * @throws SpdxCompareException - */ - private @Nullable String findTemplateWithinText(String text) { + */ + @SuppressWarnings("UnusedAssignment") + private @Nullable String findTemplateWithinText(String text) { // Get match status String result = null; - int startIndex = -1; + @SuppressWarnings("UnusedAssignment") int startIndex = -1; int endIndex = -1; if (text == null || text.isEmpty() || template == null) { @@ -380,7 +381,7 @@ public void endOptional(LicenseTemplateRule rule) { * @see org.spdx.licenseTemplate.ILicenseTemplateOutputHandler#completeParsing() */ @Override - public void completeParsing() throws LicenseParserException { + public void completeParsing() { // Nothing to do here } } diff --git a/src/main/java/org/spdx/utility/compare/package-info.java b/src/main/java/org/spdx/utility/compare/package-info.java index a85971ba..57f82e6e 100644 --- a/src/main/java/org/spdx/utility/compare/package-info.java +++ b/src/main/java/org/spdx/utility/compare/package-info.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. diff --git a/src/main/java/org/spdx/utility/license/LicenseExpressionParser.java b/src/main/java/org/spdx/utility/license/LicenseExpressionParser.java index ef1d204f..b565071f 100644 --- a/src/main/java/org/spdx/utility/license/LicenseExpressionParser.java +++ b/src/main/java/org/spdx/utility/license/LicenseExpressionParser.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. @@ -66,7 +66,7 @@ /** * A parser for the SPDX License Expressions as documented in the SPDX appendix. - * + *

* This is a static help class. The primary method is parseLicenseExpression which * returns an AnyLicenseInfo. * @author Gary O'Neall @@ -76,8 +76,9 @@ public class LicenseExpressionParser { enum Operator { OR_LATER, WITH, AND, OR //NOTE: These must be in precedence order - }; - static final String LEFT_PAREN = "("; + } + + static final String LEFT_PAREN = "("; static final String RIGHT_PAREN = ")"; static final Map OPERATOR_MAP = new HashMap<>(); public static final String UNINITIALIZED_LICENSE_TEXT = "[Initialized with license Parser. The actual license text is not available]"; @@ -93,7 +94,7 @@ enum Operator { } /** - * Parses a license expression into an license for use in the Model using the SPDX Version 3.X model + * Parses a license expression into n license for use in the Model using the SPDX Version 3.X model * @param expression Expression to be parsed * @param store Store containing any extractedLicenseInfos - if any extractedLicenseInfos by ID already exist, they will be used. If * none exist for an ID, they will be added. If null, the default model store will be used. @@ -102,7 +103,7 @@ enum Operator { * @param copyManager if non-null, allows for copying of any properties set which use other model stores or document URI's * @param customIdToUri Mapping of the id prefixes used in the license expression to the namespace preceding the external ID * @return the parsed license expression - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ public static AnyLicenseInfo parseLicenseExpression(String expression, IModelStore store, String customLicenseUriPrefix, @Nullable IModelCopyManager copyManager, @@ -132,7 +133,7 @@ public static AnyLicenseInfo parseLicenseExpression(String expression, IModelSto } /** - * Parses a license expression into an license for use in the Model using the SPDX Version 2.X model + * Parses a license expression into n license for use in the Model using the SPDX Version 2.X model * @param expression Expression to be parsed * @param store Store containing any extractedLicenseInfos - if any extractedLicenseInfos by ID already exist, they will be used. If * none exist for an ID, they will be added. If null, the default model store will be used. @@ -140,7 +141,7 @@ public static AnyLicenseInfo parseLicenseExpression(String expression, IModelSto * none exist for an ID, they will be added. If null, the default model document URI will be used. * @param copyManager if non-null, allows for copying of any properties set which use other model stores or document URI's * @return the parsed license expression - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ public static org.spdx.library.model.v2.license.AnyLicenseInfo parseLicenseExpressionCompatV2(String expression, IModelStore store, String documentUri, IModelCopyManager copyManager) throws InvalidSPDXAnalysisException { @@ -167,9 +168,9 @@ public static org.spdx.library.model.v2.license.AnyLicenseInfo parseLicenseExpre } /** - * A custom tokenizer since there is not white space between parents and pluses - * @param expression - * @return + * A custom tokenizer since there is not a white space between parents and pluses + * @param expression license expression string + * @return array of string tokens */ private static String[] tokenizeExpression(String expression) { String[] startTokens = expression.split("\\s"); @@ -177,17 +178,18 @@ private static String[] tokenizeExpression(String expression) { for (String token : startTokens) { processPreToken(token, endTokens); } - return endTokens.toArray(new String[endTokens.size()]); + return endTokens.toArray(new String[0]); } /** - * @param preToken - * @param tokenList + * @param preToken previous token + * @param tokenList resultant list of tokens - modified by this methods */ private static void processPreToken(String preToken, List tokenList) { if (preToken.isEmpty()) { - return; + //noinspection UnnecessaryReturnStatement + return; } else if (preToken.startsWith("(")) { tokenList.add("("); processPreToken(preToken.substring(1), tokenList); @@ -204,14 +206,14 @@ private static void processPreToken(String preToken, /** * Parses a tokenized license expression into a license for use in the RDF Parser - * @param tokens - * @param store + * @param tokens array of tokens + * @param store model store for non-listed licenses * @param customLicenseUriPrefix Prefix for Object URI's created when appending custom license ID's or custom license additions. If any custom licenses or additions already exist, they will be used. * If none exist for an ID, they will be added. If null, the default model document URI will be used. * @param copyManager if non-null, allows for copying of any properties set which use other model stores or document URI's * @param customIdToUri Mapping of the id prefixes used in the license expression to the namespace preceding the external ID - required for any external additions or licenses * @return a license info representing the fully parsed list of tokens - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private static AnyLicenseInfo parseLicenseExpression(String[] tokens, IModelStore store, String customLicenseUriPrefix, @Nullable IModelCopyManager copyManager, @@ -219,8 +221,8 @@ private static AnyLicenseInfo parseLicenseExpression(String[] tokens, IModelStor if (tokens == null || tokens.length == 0) { throw new LicenseParserException("Expected license expression"); } - Stack operandStack = new Stack(); - Stack operatorStack = new Stack(); + Stack operandStack = new Stack<>(); + Stack operatorStack = new Stack<>(); int tokenIndex = 0; String token; while (tokenIndex < tokens.length) { @@ -287,21 +289,21 @@ private static AnyLicenseInfo parseLicenseExpression(String[] tokens, IModelStor } /** - * Parses a tokenized license expression into a license for use in the RDF Parser - * @param tokens - * @param store - * @param documentUri + * Parses a tokenized license expression into a license + * @param tokens array of tokens + * @param store model store for non-listed licenses + * @param documentUri document URI for non-listed licenses * @param copyManager if non-null, allows for copying of any properties set which use other model stores or document URI's - * @return - * @throws InvalidSPDXAnalysisException + * @return a license represented by the license expression + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private static org.spdx.library.model.v2.license.AnyLicenseInfo parseLicenseExpressionCompatV2(String[] tokens, IModelStore store, String documentUri, IModelCopyManager copyManager) throws InvalidSPDXAnalysisException { if (tokens == null || tokens.length == 0) { throw new LicenseParserException("Expected license expression"); } - Stack operandStack = new Stack(); - Stack operatorStack = new Stack(); + Stack operandStack = new Stack<>(); + Stack operatorStack = new Stack<>(); int tokenIndex = 0; String token; while (tokenIndex < tokens.length) { @@ -329,7 +331,7 @@ private static org.spdx.library.model.v2.license.AnyLicenseInfo parseLicenseExpr throw new LicenseParserException("Missing exception clause"); } token = tokens[tokenIndex++]; - org.spdx.library.model.v2.license.ListedLicenseException licenseException = null; + org.spdx.library.model.v2.license.ListedLicenseException licenseException; Optional exceptionId = Optional.empty(); if (LicenseInfoFactory.isSpdxListedExceptionId(token)) { exceptionId = LicenseInfoFactory.listedExceptionIdCaseSensitive(token); @@ -378,8 +380,9 @@ private static org.spdx.library.model.v2.license.AnyLicenseInfo parseLicenseExpr /** * Returns the index of the rightmost parenthesis or -1 if not found - * @param tokens - * @return + * @param tokens array of tokens + * @param startToken index of the token to start the search + * @return index of the matching end parenthesis */ private static int findMatchingParen(String[] tokens, int startToken) { if (tokens == null) { @@ -409,7 +412,7 @@ private static int findMatchingParen(String[] tokens, int startToken) { * @param copyManager to use when copying from the listed license store * @param customIdToUri Mapping of the id prefixes used in the license expression to the namespace preceding the external ID - required for any external additions or licenses * @return a CustomLicenseAddition, ListedLicense, ListedLicenseException or CustomLicense depending on what is in the store - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private static LicenseAddition parseSimpleLicenseAdditionToken(String token, IModelStore store, String customLicenseUriPrefix, @Nullable IModelCopyManager copyManager, @Nullable List customIdToUri) throws InvalidSPDXAnalysisException { @@ -440,7 +443,7 @@ private static LicenseAddition parseSimpleLicenseAdditionToken(String token, IMo } else { // custom addition String objectUri = customLicenseUriPrefix + token; - CustomLicenseAddition localAddition = null; + CustomLicenseAddition localAddition; if (store.exists(objectUri)) { localAddition = new CustomLicenseAddition(store, objectUri, copyManager, false, customLicenseUriPrefix); } else { @@ -460,7 +463,7 @@ private static LicenseAddition parseSimpleLicenseAdditionToken(String token, IMo * @param copyManager to use when copying from the listed license store * @param customIdToUri Mapping of the id prefixes used in the license expression to the namespace preceding the external ID * @return a CustomLicenseAddition, ListedLicense, ListedLicenseException or CustomLicense depending on what is in the store - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private static AnyLicenseInfo parseSimpleLicenseToken(String token, IModelStore store, String customLicenseUriPrefix, @Nullable IModelCopyManager copyManager, @Nullable List customIdToUri) throws InvalidSPDXAnalysisException { @@ -490,7 +493,7 @@ private static AnyLicenseInfo parseSimpleLicenseToken(String token, IModelStore } else { // LicenseRef String objectUri = customLicenseUriPrefix + token; - CustomLicense localLicense = null; + CustomLicense localLicense; if (store.exists(objectUri)) { localLicense = new CustomLicense(store, objectUri, copyManager, false, customLicenseUriPrefix); } else { @@ -505,7 +508,7 @@ private static AnyLicenseInfo parseSimpleLicenseToken(String token, IModelStore * @param externalReference String of the form [prefix]:[id] where [prefix] is a prefix in the customIdToUri and ID is the suffix of the object URI * @param customIdToUri Mapping of the id prefixes used in the license expression to the namespace preceding the external ID * @return the full object URI with the [prefix] replaced by the associated namespace - * @throws InvalidSPDXAnalysisException + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private static String convertToExternalObjectUri(String externalReference, @Nullable List customIdToUri) throws InvalidSPDXAnalysisException { if (Objects.isNull(customIdToUri)) { @@ -534,15 +537,17 @@ private static String convertToExternalObjectUri(String externalReference, @Null /** * Converts a string token into its equivalent license * checking for a listed license - * @param token - * @param baseStore - * @param documentUri - * @param copyManager - * @return - * @throws InvalidSPDXAnalysisException + * @param token license ID token + * @param store model store for non-listed licenses + * @param documentUri document URI for non-listed licenses + * @param copyManager copy manager to copy listed licenses to local store + * @return license equivalent to the token + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ - private static org.spdx.library.model.v2.license.AnyLicenseInfo parseSimpleLicenseTokenCompatV2(String token, IModelStore store, String documentUri, - IModelCopyManager copyManager) throws InvalidSPDXAnalysisException { + private static org.spdx.library.model.v2.license.AnyLicenseInfo parseSimpleLicenseTokenCompatV2(String token, + IModelStore store, + String documentUri, + IModelCopyManager copyManager) throws InvalidSPDXAnalysisException { Objects.requireNonNull(token, "Token can not be null"); Objects.requireNonNull(store, "Model store can not be null"); Objects.requireNonNull(documentUri, "URI prefix can not be null"); @@ -569,7 +574,7 @@ private static org.spdx.library.model.v2.license.AnyLicenseInfo parseSimpleLicen } else { // LicenseRef Optional caseSensitiveId = store.getCaseSensisitiveId(documentUri, token); - ExtractedLicenseInfo localLicense = null; + ExtractedLicenseInfo localLicense; if (caseSensitiveId.isPresent()) { localLicense = new ExtractedLicenseInfo(store, documentUri, caseSensitiveId.get(), copyManager, false); @@ -583,11 +588,13 @@ private static org.spdx.library.model.v2.license.AnyLicenseInfo parseSimpleLicen } /** - * Evaluate the given operator using paramaeters in the parameter stack - * @param operator - * @param operandStack - * @param copyManager - * @throws InvalidSPDXAnalysisException + * Evaluate the given operator using parameters in the parameter stack + * @param operator operator + * @param operandStack operands for the operator + * @param copyManager copy manager to use when copying listed licenses to local store + * @param store model store to store non-listed licenses + * @param customLicenseUriPrefix prefix to use for non-listed licenses + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private static void evaluateExpression(Operator operator, Stack operandStack, IModelStore store, @@ -613,11 +620,13 @@ private static void evaluateExpression(Operator operator, } /** - * Evaluate the given operator using paramaeters in the parameter stack - * @param operator - * @param operandStack - * @param copyManager - * @throws InvalidSPDXAnalysisException + * Evaluate the given operator using parameters in the parameter stack + * @param operator operator + * @param operandStack operands for the operator + * @param copyManager copy manager to use when copying listed licenses to local store + * @param store model store to store non-listed licenses + * @param documentUri prefix to use for non-listed licenses + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private static void evaluateExpressionCompatV2(Operator operator, Stack operandStack, IModelStore store, @@ -643,13 +652,15 @@ private static void evaluateExpressionCompatV2(Operator operator, } /** - * Evaluates a binary expression and merges conjuctive and disjunctive licenses - * @param tosOperator - * @param operand1 - * @param operand2 - * @param copyManager - * @return - * @throws InvalidSPDXAnalysisException + * Evaluates a binary expression and merges conjunctive and disjunctive licenses + * @param tosOperator binary operator + * @param operand1 first operand + * @param operand2 second operand + * @param copyManager copy manager to use when copying listed licenses to local store + * @param store model store to store non-listed licenses + * @param customLicenseUriPrefix prefix to use for non-listed licenses + * @return resultant license representing the binary operation + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private static AnyLicenseInfo evaluateBinary(Operator tosOperator, AnyLicenseInfo operand1, AnyLicenseInfo operand2, IModelStore store, @@ -684,13 +695,15 @@ private static AnyLicenseInfo evaluateBinary(Operator tosOperator, } /** - * Evaluates a binary expression and merges conjuctive and disjunctive licenses - * @param tosOperator - * @param operand1 - * @param operand2 - * @param copyManager - * @return - * @throws InvalidSPDXAnalysisException + * Evaluates a binary expression and merges conjunctive and disjunctive licenses + * @param tosOperator binary operator + * @param operand1 first operand + * @param operand2 second operand + * @param copyManager copy manager to use when copying listed licenses to local store + * @param store model store to store non-listed licenses + * @param documentUri prefix to use for non-listed licenses + * @return resultant license representing the binary operation + * @throws InvalidSPDXAnalysisException on SPDX parsing errors */ private static org.spdx.library.model.v2.license.AnyLicenseInfo evaluateBinaryCompatV2(Operator tosOperator, org.spdx.library.model.v2.license.AnyLicenseInfo operand1, org.spdx.library.model.v2.license.AnyLicenseInfo operand2, IModelStore store, diff --git a/src/main/java/org/spdx/utility/license/LicenseParserException.java b/src/main/java/org/spdx/utility/license/LicenseParserException.java index 3e02a940..6663db67 100644 --- a/src/main/java/org/spdx/utility/license/LicenseParserException.java +++ b/src/main/java/org/spdx/utility/license/LicenseParserException.java @@ -10,7 +10,7 @@ public class LicenseParserException extends InvalidSPDXAnalysisException { private static final long serialVersionUID = 1L; /** - * @param msg + * @param msg exception message */ public LicenseParserException(String msg) { super(msg); diff --git a/src/main/java/org/spdx/utility/license/package-info.java b/src/main/java/org/spdx/utility/license/package-info.java index d7bb67e4..c8e6b5c5 100644 --- a/src/main/java/org/spdx/utility/license/package-info.java +++ b/src/main/java/org/spdx/utility/license/package-info.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/utility/package-info.java b/src/main/java/org/spdx/utility/package-info.java index 5a21607a..dd63fb35 100644 --- a/src/main/java/org/spdx/utility/package-info.java +++ b/src/main/java/org/spdx/utility/package-info.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. diff --git a/src/main/java/org/spdx/utility/verificationcode/IFileChecksumGenerator.java b/src/main/java/org/spdx/utility/verificationcode/IFileChecksumGenerator.java index 7d8f2cfd..84a8faf2 100644 --- a/src/main/java/org/spdx/utility/verificationcode/IFileChecksumGenerator.java +++ b/src/main/java/org/spdx/utility/verificationcode/IFileChecksumGenerator.java @@ -1,12 +1,12 @@ /** * Copyright (c) 2011 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. @@ -30,5 +30,5 @@ public interface IFileChecksumGenerator { * @return the checksum for the file * @throws IOException on errors reading the file */ - public String getFileChecksum(File file) throws IOException; + String getFileChecksum(File file) throws IOException; } diff --git a/src/main/java/org/spdx/utility/verificationcode/JavaSha1ChecksumGenerator.java b/src/main/java/org/spdx/utility/verificationcode/JavaSha1ChecksumGenerator.java index a266e1c4..b0409954 100644 --- a/src/main/java/org/spdx/utility/verificationcode/JavaSha1ChecksumGenerator.java +++ b/src/main/java/org/spdx/utility/verificationcode/JavaSha1ChecksumGenerator.java @@ -1,12 +1,12 @@ /** * Copyright (c) 2011 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. @@ -30,7 +30,7 @@ public class JavaSha1ChecksumGenerator implements IFileChecksumGenerator { static final String SHA1_ALGORITHM = "SHA-1"; static final String PACKAGE_VERIFICATION_CHARSET = "UTF-8"; - private MessageDigest digest = null; + private final MessageDigest digest; /** * Create a SHA1 based checksum generator @@ -40,33 +40,33 @@ public JavaSha1ChecksumGenerator() throws NoSuchAlgorithmException { this.digest = MessageDigest.getInstance(SHA1_ALGORITHM); } - /* (non-Javadoc) - * @see org.spdx.rdfparser.IFileChecksumGenerator#getFileChecksum(java.io.File) + /** + * + * @param file File to generate the checksum for + * @return file checksum + * @throws IOException on IO errors */ @Override public String getFileChecksum(File file) throws IOException { digest.reset(); - FileInputStream in = new FileInputStream(file); - try { - byte[] buffer = new byte[2048]; - int numBytes = in.read(buffer); - while (numBytes >= 0) { - digest.update(buffer, 0, numBytes); - numBytes = in.read(buffer); - } - byte[] digestBytes = digest.digest(); - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < digestBytes.length; i++) { - String hex = Integer.toHexString(0xff & digestBytes[i]); - if (hex.length() < 2) { - sb.append('0'); - } - sb.append(hex); - } - return sb.toString(); - } finally { - in.close(); - } + try (FileInputStream in = new FileInputStream(file)) { + byte[] buffer = new byte[2048]; + int numBytes = in.read(buffer); + while (numBytes >= 0) { + digest.update(buffer, 0, numBytes); + numBytes = in.read(buffer); + } + byte[] digestBytes = digest.digest(); + StringBuilder sb = new StringBuilder(); + for (byte digestByte : digestBytes) { + String hex = Integer.toHexString(0xff & digestByte); + if (hex.length() < 2) { + sb.append('0'); + } + sb.append(hex); + } + return sb.toString(); + } } } diff --git a/src/main/java/org/spdx/utility/verificationcode/VerificationCodeGenerator.java b/src/main/java/org/spdx/utility/verificationcode/VerificationCodeGenerator.java index 01a287bf..e1d70645 100644 --- a/src/main/java/org/spdx/utility/verificationcode/VerificationCodeGenerator.java +++ b/src/main/java/org/spdx/utility/verificationcode/VerificationCodeGenerator.java @@ -1,12 +1,12 @@ /** * Copyright (c) 2011 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. @@ -18,7 +18,7 @@ import java.io.File; import java.io.IOException; -import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; @@ -38,7 +38,7 @@ /** * Generates a package verification code from a directory of source code or an array of SPDXFiles. - * + *

* A class implementing the IFileChecksumGenerator is supplied as a parameter to the constructor. * The method getFileChecksum is called for each file in the directory. This can * be used as a hook to capture all files in the directory and capture the checksum values at @@ -49,7 +49,7 @@ */ public class VerificationCodeGenerator { - private IFileChecksumGenerator fileChecksumGenerator; + private final IFileChecksumGenerator fileChecksumGenerator; public VerificationCodeGenerator(IFileChecksumGenerator fileChecksumGenerator) { this.fileChecksumGenerator = fileChecksumGenerator; @@ -62,8 +62,8 @@ public VerificationCodeGenerator(IFileChecksumGenerator fileChecksumGenerator) { * @param modelStore where the resultant VerificationCode is store * @param documentUri document URI where the VerificationCode is stored * @return VerificationCode based on all files in spdxFiles minus the skippedFilePaths - * @throws NoSuchAlgorithmException - * @throws InvalidSPDXAnalysisException + * @throws NoSuchAlgorithmException unexpected checksum calculation error + * @throws InvalidSPDXAnalysisException on SPDX parsing error */ public SpdxPackageVerificationCode generatePackageVerificationCode(SpdxFile[] spdxFiles, String[] skippedFilePaths, IModelStore modelStore, String documentUri) throws NoSuchAlgorithmException, InvalidSPDXAnalysisException { @@ -72,34 +72,34 @@ public SpdxPackageVerificationCode generatePackageVerificationCode(SpdxFile[] sp } Set skippedFilePathSet = new TreeSet<>(); if (skippedFilePaths != null) { - for (int i = 0; i < skippedFilePaths.length; i++) { - if (skippedFilePaths[i] != null) { - skippedFilePathSet.add(skippedFilePaths[i]); - } - } + for (String skippedFilePath : skippedFilePaths) { + if (skippedFilePath != null) { + skippedFilePathSet.add(skippedFilePath); + } + } } List fileChecksums = new ArrayList<>(); - for (int i = 0; i < spdxFiles.length; i++) { - if (spdxFiles[i] != null) { - Optional name = spdxFiles[i].getName(); - if (name.isPresent() && !skippedFilePathSet.contains(name.get())) { - fileChecksums.add(spdxFiles[i].getSha1()); - } - } - } - return generatePackageVerificationCode(fileChecksums, skippedFilePathSet.toArray(new String[skippedFilePathSet.size()]), modelStore, documentUri); + for (SpdxFile spdxFile : spdxFiles) { + if (spdxFile != null) { + Optional name = spdxFile.getName(); + if (name.isPresent() && !skippedFilePathSet.contains(name.get())) { + fileChecksums.add(spdxFile.getSha1()); + } + } + } + return generatePackageVerificationCode(fileChecksums, skippedFilePathSet.toArray(new String[0]), modelStore, documentUri); } /** * Generate the SPDX Package Verification Code from a directory of files included in the archive - * @param sourceDirectory + * @param sourceDirectory source directory for the package verification code * @param modelStore where the resultant VerificationCode is store * @param documentUri document URI where the VerificationCode is stored * @return PackageVerificationCode based on the files in the sourceDirectory - * @throws NoSuchAlgorithmException - * @throws IOException - * @throws InvalidSPDXAnalysisException + * @throws NoSuchAlgorithmException unexpected error creating checksums + * @throws IOException on file or directory read errors + * @throws InvalidSPDXAnalysisException on SPDX parsing error */ public SpdxPackageVerificationCode generatePackageVerificationCode(File sourceDirectory, File[] skippedFiles, IModelStore modelStore, String documentUri) throws NoSuchAlgorithmException, IOException, InvalidSPDXAnalysisException { @@ -107,10 +107,10 @@ public SpdxPackageVerificationCode generatePackageVerificationCode(File sourceDi Set skippedFilesPath = new TreeSet<>(); String rootOfDirectory = sourceDirectory.getAbsolutePath(); int rootLen = rootOfDirectory.length()+1; - for (int i = 0; i < skippedFiles.length; i++) { - String skippedPath = normalizeFilePath(skippedFiles[i].getAbsolutePath().substring(rootLen)); - skippedFilesPath.add(skippedPath); - } + for (File skippedFile : skippedFiles) { + String skippedPath = normalizeFilePath(skippedFile.getAbsolutePath().substring(rootLen)); + skippedFilesPath.add(skippedPath); + } List fileChecksums = new ArrayList<>(); collectFileData(rootOfDirectory, sourceDirectory, fileChecksums, skippedFilesPath); String[] skippedFileNames = new String[skippedFilesPath.size()]; @@ -128,17 +128,17 @@ public SpdxPackageVerificationCode generatePackageVerificationCode(File sourceDi * @param modelStore where the resultant VerificationCode is store * @param documentUri document URI where the VerificationCode is stored * @return a PackageVerificationCode with the value created from the fileChecksums - * @throws NoSuchAlgorithmException - * @throws InvalidSPDXAnalysisException + * @throws NoSuchAlgorithmException unexpected error creating checksums + * @throws InvalidSPDXAnalysisException on SPDX parsing error */ protected SpdxPackageVerificationCode generatePackageVerificationCode(List fileChecksums, String[] skippedFilePaths, IModelStore modelStore, String documentUri) throws NoSuchAlgorithmException, InvalidSPDXAnalysisException { Collections.sort(fileChecksums); MessageDigest verificationCodeDigest = MessageDigest.getInstance("SHA-1"); - for (int i = 0;i < fileChecksums.size(); i++) { - byte[] hashInput = fileChecksums.get(i).getBytes(Charset.forName("UTF-8")); - verificationCodeDigest.update(hashInput); - } + for (String fileChecksum : fileChecksums) { + byte[] hashInput = fileChecksum.getBytes(StandardCharsets.UTF_8); + verificationCodeDigest.update(hashInput); + } String value = convertChecksumToString(verificationCodeDigest.digest()); SpdxPackageVerificationCode retval = new SpdxPackageVerificationCode(modelStore, documentUri, modelStore.getNextId(IdType.Anonymous), null, true); retval.setValue(value); @@ -150,10 +150,11 @@ protected SpdxPackageVerificationCode generatePackageVerificationCode(List fileNameAndChecksums, Set skippedFiles) throws IOException { @@ -164,26 +165,27 @@ private void collectFileData(String prefixForRelative, File sourceDirectory, if (filesAndDirs == null) { return; } - for (int i = 0; i < filesAndDirs.length; i++) { - if (filesAndDirs[i].isDirectory()) { - collectFileData(prefixForRelative, filesAndDirs[i], fileNameAndChecksums, skippedFiles); - } else { - String filePath = normalizeFilePath(filesAndDirs[i].getAbsolutePath() - .substring(prefixForRelative.length()+1)); - if (!skippedFiles.contains(filePath)) { - String checksumValue = this.fileChecksumGenerator.getFileChecksum(filesAndDirs[i]).toLowerCase(); - fileNameAndChecksums.add(checksumValue); - } - } - } + for (File filesAndDir : filesAndDirs) { + if (filesAndDir.isDirectory()) { + collectFileData(prefixForRelative, filesAndDir, fileNameAndChecksums, skippedFiles); + } else { + String filePath = normalizeFilePath(filesAndDir.getAbsolutePath() + .substring(prefixForRelative.length() + 1)); + if (!skippedFiles.contains(filePath)) { + String checksumValue = this.fileChecksumGenerator.getFileChecksum(filesAndDir).toLowerCase(); + fileNameAndChecksums.add(checksumValue); + } + } + } } /** * Normalizes a file path per the SPDX spec - * @param nonNormalizedFilePath - * @return + * @param nonNormalizedFilePath original file path - may be unix or DOS format + * @return file path normalized per SPDX spec */ - public static String normalizeFilePath(String nonNormalizedFilePath) { + @SuppressWarnings("StatementWithEmptyBody") + public static String normalizeFilePath(String nonNormalizedFilePath) { String filePath = nonNormalizedFilePath.replace('\\', '/').trim(); if (filePath.contains("../")) { // need to remove these references @@ -213,28 +215,28 @@ public static String normalizeFilePath(String nonNormalizedFilePath) { } /** * Convert a byte array SHA-1 digest into a 40 character hex string - * @param digest - * @return + * @param digest message digest from checksum calculation + * @return string representation of the checksum */ private static String convertChecksumToString(byte[] digest) { StringBuilder sb = new StringBuilder(); - for (int i = 0; i < digest.length; i++) { - String hex = Integer.toHexString(0xff & digest[i]); - if (hex.length() < 2) { - sb.append('0'); - } - sb.append(hex); - } + for (byte b : digest) { + String hex = Integer.toHexString(0xff & b); + if (hex.length() < 2) { + sb.append('0'); + } + sb.append(hex); + } return sb.toString(); } /** - * @param sourceDirectory + * @param sourceDirectory directory to create the verification code for * @param modelStore where the resultant VerificationCode is store * @param documentUri document URI where the VerificationCode is stored - * @return - * @throws NoSuchAlgorithmException - * @throws IOException - * @throws InvalidSPDXAnalysisException + * @return SPDX package verification code + * @throws NoSuchAlgorithmException unexpected error creating checksums + * @throws IOException on IO error reading files or directories + * @throws InvalidSPDXAnalysisException on SPDX parsing error */ public SpdxPackageVerificationCode generatePackageVerificationCode( File sourceDirectory, IModelStore modelStore, String documentUri) throws NoSuchAlgorithmException, IOException, InvalidSPDXAnalysisException { diff --git a/src/main/java/org/spdx/utility/verificationcode/package-info.java b/src/main/java/org/spdx/utility/verificationcode/package-info.java index bb392448..ddac6763 100644 --- a/src/main/java/org/spdx/utility/verificationcode/package-info.java +++ b/src/main/java/org/spdx/utility/verificationcode/package-info.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.