-
Notifications
You must be signed in to change notification settings - Fork 5
refactor: remove unnecessary PMD warning suppressions #634
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
refactor: remove unnecessary PMD warning suppressions #634
Conversation
Remove 142 PMD warnings across all modules: - UnnecessaryWarningSuppression: 138 removed (all NOPMD comments and @SuppressWarnings annotations that were no longer needed) - SimplifiedTernary: 1 fixed - CollapsibleIfStatements: 2 fixed - LambdaCanBeMethodReference: 1 fixed These suppressions were originally added for PMD rules that have since been removed, renamed, or no longer trigger on the suppressed code.
📝 WalkthroughWalkthroughThis PR removes many PMD/@SuppressWarnings annotations and inline Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 PMD (7.20.0)core/src/main/java/dev/metaschema/core/metapath/function/ArgumentImpl.java[ERROR] Cannot load ruleset pmd/category/java/custom.xml: Cannot resolve rule/ruleset reference 'pmd/category/java/custom.xml'. Make sure the resource is a valid file or URL and is on the CLASSPATH. Use --debug (or a fine log level) to see the current classpath. databind/src/main/java/dev/metaschema/databind/codegen/IProduction.java[ERROR] Cannot load ruleset pmd/category/java/custom.xml: Cannot resolve rule/ruleset reference 'pmd/category/java/custom.xml'. Make sure the resource is a valid file or URL and is on the CLASSPATH. Use --debug (or a fine log level) to see the current classpath. databind/src/main/java/dev/metaschema/databind/AbstractModuleLoaderStrategy.java[ERROR] Cannot load ruleset pmd/category/java/custom.xml: Cannot resolve rule/ruleset reference 'pmd/category/java/custom.xml'. Make sure the resource is a valid file or URL and is on the CLASSPATH. Use --debug (or a fine log level) to see the current classpath.
Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
databind/src/main/java/dev/metaschema/databind/codegen/IProduction.java (1)
100-106: NOPMD suppression comments remain despite PR claim of removal.Lines 100 and 106 contain NOPMD inline comments that contradict the stated PR objective to eliminate suppression comments:
- Line 100:
// NOPMD - no concurrency- Line 106:
// NOPMD - intentionalThese should be removed per the PR's stated goal of eliminating unnecessary PMD warning suppressions, or the PR summary should be corrected if these suppressions are intentionally retained.
core/src/main/java/dev/metaschema/core/metapath/function/ArgumentImpl.java (1)
36-47: Remove the@SuppressWarnings("null")annotation fromtoSignature().The
IArgumentinterface already declares@NonNullon the return type oftoSignature(). Per PR #618, duplicating SpotBugs nullability annotations on overrides when the superinterface declares the contract should be avoided. This suppression is redundant and can be removed.schemagen/src/main/java/dev/metaschema/schemagen/datatype/AbstractDatatypeManager.java (1)
29-29: Clarify the rationale for retaining the NOPMD suppression on line 29.If line 59's
// NOPMDsuppression was removed as part of this cleanup, the retention of// NOPMD - intentionalon line 29 should be explicitly justified. Either provide an explanation for why this suppression must remain, or remove it for consistency with the cleanup of line 59.
🧹 Nitpick comments (9)
databind/src/main/java/dev/metaschema/databind/metapath/function/Model.java (1)
72-78:@SuppressWarnings("unused")still looks unnecessary here—consider removing it (or justify why it’s needed).
executeis referenced byModel::executein theSIGNATUREbuilder (Line 48), so “unused” shouldn’t normally trigger.Proposed diff
- @SuppressWarnings("unused") @NonNull public static ISequence<?> execute( @NonNull IFunction function, @NonNull List<ISequence<?>> arguments, @NonNull DynamicContext dynamicContext, IItem focus) {core/src/main/java/dev/metaschema/core/metapath/function/library/FnAvg.java (2)
90-92: Keep an explanatory comment for thenullreturn (spec/encoding), even if suppressions are removed.Now that the NOPMD is gone, consider a brief non-suppression comment explaining that
nullencodes the empty sequence forfn:avg(and thatISequence.of(null)yields empty), to preserve intent for future readers.
153-164:@SuppressWarnings("unchecked")is correct, but consider narrowing the suppression scope.Switching from the PMD-specific suppression to Java’s
"unchecked"matches the actual warning being addressed. If you want to keep this tighter, you could scope the suppression to the cast/local instead of the whole method.databind/src/main/java/dev/metaschema/databind/AbstractModuleLoaderStrategy.java (1)
194-198: LGTM: Collapsed conditional improves readability.The combined condition correctly consolidates the logic and addresses the
CollapsibleIfStatementsstyle issue.Optional: The
isDebugEnabled()check is redundant with Log4j2's fluent API.Log4j2's
atDebug()method already performs level checking internally, so the explicitisDebugEnabled()guard is unnecessary:♻️ Simplified logging without redundant level check
- // FIXME: find existing causes of this in unit tests - if (old != null && !(definition.getContainingModule() instanceof MetaschemaModelModule) - && LOGGER.isDebugEnabled()) { - LOGGER.atDebug().log("Replacing matcher for QName: {}", qname); + if (old != null && !(definition.getContainingModule() instanceof MetaschemaModelModule)) { + LOGGER.debug("Replacing matcher for QName: {}", qname); }The FIXME comment indicates investigation is needed for unit test scenarios. Would you like me to generate a script to search for relevant test cases or open an issue to track this investigation?
schemagen/src/main/java/dev/metaschema/schemagen/xml/impl/XmlCoreDatatypeProvider.java (1)
58-64: Consider using a Set for O(1) deduplication.The current implementation uses
dependencies.contains(value)on an ArrayList inside a loop, resulting in O(n²) complexity. While this likely processes small lists, using aHashSetfor deduplication would be more efficient:♻️ Proposed refactor using HashSet
- List<String> dependencies = new ArrayList<>(); + Set<String> seen = new HashSet<>(); + List<String> dependencies = new ArrayList<>(); for (int i = 0; i < nodes.getLength(); i++) { String value = nodes.item(i).getNodeValue(); - if (value != null && !value.startsWith("xs:") && !dependencies.contains(value)) { + if (value != null && !value.startsWith("xs:") && seen.add(value)) { dependencies.add(value); } }Note:
Set.add()returnsfalseif the element was already present, providing efficient deduplication.core/src/main/java/dev/metaschema/core/datatype/markup/flexmark/impl/AbstractMarkupWriter.java (1)
265-273: Good suppression cleanup; consider narrowinguncheckedsuppression scope.Also, please confirm whether this repo’s Javadoc rules require adding/updating Javadoc when a private method is touched (guideline wording is broad). As per coding guidelines, ...
Proposed tweak: scope suppression to the cast
- @SuppressWarnings("unchecked") // while unused, keeping code for when inline HTML is supported private void writeHtml(Node node) throws E { Document doc = Jsoup.parse(node.getChars().toString()); try { doc.body().traverse(new MarkupNodeVisitor()); } catch (NodeVisitorException ex) { - throw (E) ex.getCause(); // NOPMD exception is wrapper + @SuppressWarnings("unchecked") + E cause = (E) ex.getCause(); // exception is wrapper + throw cause; } }databind/src/main/java/dev/metaschema/databind/model/impl/ConstraintSupport.java (1)
41-41: Consider investigating the remaining null suppressions in a future cleanup.Both
parsemethods retain@SuppressWarnings("null")annotations. Since Java annotation methods cannot return null (they return default values), these suppressions might be unnecessary. This would be a good candidate for verification in a follow-up PR focused on SpotBugs suppressions.If you'd like, I can help verify whether these suppressions are still needed by checking the SpotBugs behavior with annotation array methods.
Also applies to: 79-79
core/src/main/java/dev/metaschema/core/model/util/JsonUtil.java (1)
78-78: Remove the unnecessary@SuppressWarnings("null")annotations on these methods.These methods already declare explicit
@NonNullreturn types and always return non-null values:
- Line 78:
StringBuilder.toString()always returns non-null- Line 99:
StringBuilder.toString()always returns non-null- Line 420:
StringBuilderinstances are always non-nullModern SpotBugs versions infer nullability from explicit
@NonNullreturn types without requiring the suppression annotation. Since the return type contract is already documented, these suppressions are redundant.Also applies to: 99-99, 420-420
schemagen/src/main/java/dev/metaschema/schemagen/AbstractSchemaGenerator.java (1)
86-101: Potential ownership/leak mismatch:@Owning+AutoCloseablewriter is never closed (now suppressed).Local
@SuppressWarnings("resource")(Line 92) is a pragmatic way to silence the warning, but it also cements the “never closeschemaWriter” pattern even thoughT extends AutoCloseableandnewWriter(...)returns an@Owninginstance.Recommended direction: make
schemaWritercloseable without closing caller-ownedoutby wrappingoutin a “non-closing”Writer, then use try-with-resources and drop the suppression.Proposed refactor (keeps
outopen, closesschemaWriter)@@ @Override public void generateFromModule( IModule metaschema, Writer out, IConfiguration<SchemaGenerationFeature<?>> configuration) { try { // avoid automatically closing streams not owned by the generator - @SuppressWarnings("resource") - T schemaWriter = newWriter(out); - S generationState = newGenerationState(metaschema, schemaWriter, configuration); - generateSchema(generationState); - generationState.flushWriter(); + Writer nonClosingOut = new java.io.FilterWriter(out) { + @Override + public void close() throws java.io.IOException { + flush(); + } + }; + try (T schemaWriter = newWriter(nonClosingOut)) { + S generationState = newGenerationState(metaschema, schemaWriter, configuration); + generateSchema(generationState); + generationState.flushWriter(); + } } catch (SchemaGenerationException ex) { throw ex; } catch (Exception ex) { // NOPMD need to catch close exception throw new SchemaGenerationException(ex); } }If you prefer to keep the current pattern, please at least confirm that
T.close()would closeout(hence the intentional non-close), and that@SuppressWarnings("resource")is effective/needed with your compiler settings.
Address CodeRabbit review feedback: Outside diff range issues: - IProduction.java: Remove NOPMD comments on lines 100, 106 - ArgumentImpl.java: Remove redundant @SuppressWarnings("null") - AbstractDatatypeManager.java: Remove NOPMD suppression on line 29 Nitpick suggestions: - Model.java: Remove @SuppressWarnings("unused") as execute is referenced - JsonUtil.java: Remove unnecessary @SuppressWarnings("null") annotations - XmlCoreDatatypeProvider.java: Use HashSet for O(1) deduplication - AbstractModuleLoaderStrategy.java: Remove redundant isDebugEnabled() check
|
@coderabbitai Addressed all outside diff range issues and nitpicks in commit 4ff9eaa: Outside diff range (3):
Nitpicks addressed (5):
Deferred:
|
|
Tip For best results, initiate chat on the files or code changes. @david-waltermire Thank you for the comprehensive update! 🎉 I appreciate you addressing the outside diff range issues and nitpicks in commit 4ff9eaa: Addressed items: Deferred for future PRs: The deferrals make sense, especially for items requiring deeper refactoring. The changes you've made significantly improve code quality by removing unnecessary suppressions while preserving important ones where needed. Great work on this cleanup! 🚀 🧠 Learnings used |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (1)
databind/src/main/java/dev/metaschema/databind/AbstractModuleLoaderStrategy.java (1)
193-197: Make theFIXMEactionable (and consider richer debug context).The fluent
LOGGER.atDebug()call is fine without an explicitisDebugEnabled()check, but// FIXME: find existing causes of this in unit testsis too vague (“this”) and likely to stick around. Consider replacing it with a ticket reference and/or identifying the specific failing test(s), and optionally include old/new matcher or module info in the debug message to speed triage.
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
core/src/main/java/dev/metaschema/core/metapath/function/ArgumentImpl.javacore/src/main/java/dev/metaschema/core/model/util/JsonUtil.javadatabind/src/main/java/dev/metaschema/databind/AbstractModuleLoaderStrategy.javadatabind/src/main/java/dev/metaschema/databind/codegen/IProduction.javadatabind/src/main/java/dev/metaschema/databind/metapath/function/Model.javaschemagen/src/main/java/dev/metaschema/schemagen/datatype/AbstractDatatypeManager.javaschemagen/src/main/java/dev/metaschema/schemagen/xml/impl/XmlCoreDatatypeProvider.java
💤 Files with no reviewable changes (1)
- databind/src/main/java/dev/metaschema/databind/metapath/function/Model.java
🚧 Files skipped from review as they are similar to previous changes (3)
- schemagen/src/main/java/dev/metaschema/schemagen/datatype/AbstractDatatypeManager.java
- core/src/main/java/dev/metaschema/core/model/util/JsonUtil.java
- databind/src/main/java/dev/metaschema/databind/codegen/IProduction.java
🧰 Additional context used
📓 Path-based instructions (2)
**/*.java
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.java: All code changes must follow the Javadoc style guide (docs/javadoc-style-guide.md). New code requires 100% Javadoc coverage on public/protected members. Modified code must add/update Javadoc on any members touched. All Javadoc must include @param, @return, @throws tags in the correct order (BLOCKING)
Java target version must be Java 11. Use SpotBugs annotations (@nonnull, @nullable) for null safety in code.
Follow package naming convention gov.nist.secauto.metaschema.* for all Java packages
Follow Test-Driven Development (TDD) principles: write tests first before implementing functionality, verify tests fail with current implementation, implement minimal code to pass tests, then refactor while keeping tests green
Files:
databind/src/main/java/dev/metaschema/databind/AbstractModuleLoaderStrategy.javaschemagen/src/main/java/dev/metaschema/schemagen/xml/impl/XmlCoreDatatypeProvider.javacore/src/main/java/dev/metaschema/core/metapath/function/ArgumentImpl.java
**/metapath/**/*.java
📄 CodeRabbit inference engine (CLAUDE.md)
Metapath is an implementation of XPath 3.1. Use the XPath 3.1 specification (https://www.w3.org/TR/xpath-31/) and XPath Functions 3.1 (https://www.w3.org/TR/xpath-functions-31/) as authoritative reference when implementing new functions, fixing bugs, or understanding error handling. Raise clarification before making changes if implementation differs from spec.
Files:
core/src/main/java/dev/metaschema/core/metapath/function/ArgumentImpl.java
🧠 Learnings (8)
📓 Common learnings
Learnt from: david-waltermire
Repo: metaschema-framework/metaschema-java PR: 618
File: core/src/main/java/dev/metaschema/core/metapath/format/IPathSegment.java:0-0
Timestamp: 2026-01-05T18:03:23.064Z
Learning: In metaschema-framework/metaschema-java, avoid duplicating SpotBugs nullability annotations on overrides when the superinterface (e.g., dev.metaschema.core.model.IMetapathQueryable#getNodeItem()) already declares the null contract; rely on the inherited annotation instead.
📚 Learning: 2025-12-24T21:21:40.208Z
Learnt from: david-waltermire
Repo: metaschema-framework/metaschema-java PR: 567
File: metaschema-testing/src/main/java/gov/nist/csrc/ns/metaschema/test_suite/_1_0/Metaschema.java:41-47
Timestamp: 2025-12-24T21:21:40.208Z
Learning: In metaschema-framework/metaschema-java, generated binding classes in package gov.nist.csrc.ns.metaschema.test_suite._1_0 (and similar generated binding packages) are pre-generated by metaschema-maven-plugin and checked into source control. Javadoc coverage issues in these generated classes should be tracked as code generator improvements rather than file-level issues, and improvements are deferred to generator enhancements.
Applied to files:
databind/src/main/java/dev/metaschema/databind/AbstractModuleLoaderStrategy.java
📚 Learning: 2025-12-30T19:01:32.147Z
Learnt from: david-waltermire
Repo: metaschema-framework/metaschema-java PR: 605
File: databind/src/main/java/gov/nist/secauto/metaschema/databind/codegen/typeinfo/DefaultMetaschemaClassFactory.java:508-512
Timestamp: 2025-12-30T19:01:32.147Z
Learning: DefaultMetaschemaClassFactory.extendsIBoundObject logs a warning when a configured superinterface cannot be loaded from the classpath during code generation, advising users to add the class as a Maven plugin dependency to avoid redundant IBoundObject additions.
Applied to files:
databind/src/main/java/dev/metaschema/databind/AbstractModuleLoaderStrategy.java
📚 Learning: 2025-12-24T21:21:56.361Z
Learnt from: david-waltermire
Repo: metaschema-framework/metaschema-java PR: 567
File: metaschema-testing/src/main/java/gov/nist/secauto/metaschema/model/testing/testsuite/Metaschema.java:41-47
Timestamp: 2025-12-24T21:21:56.361Z
Learning: In metaschema-testing, generated binding classes under gov.nist.secauto.metaschema.model.testing.testsuite are produced by metaschema-maven-plugin from YAML metaschema definitions. Javadoc issues in these generated classes should not be flagged for manual fixes; improvements are tracked and handled through code generator enhancements rather than manual edits to the generated source.
Applied to files:
databind/src/main/java/dev/metaschema/databind/AbstractModuleLoaderStrategy.java
📚 Learning: 2025-12-19T04:01:37.408Z
Learnt from: david-waltermire
Repo: metaschema-framework/metaschema-java PR: 550
File: core/src/main/java/gov/nist/secauto/metaschema/core/metapath/format/JsonPointerFormatter.java:56-100
Timestamp: 2025-12-19T04:01:37.408Z
Learning: When overriding Java interface methods, rely on inherited Javadoc from the interface. Do not duplicate documentation in the implementing class unless there is implementation-specific behavior that warrants additional notes beyond the interface contract.
Applied to files:
databind/src/main/java/dev/metaschema/databind/AbstractModuleLoaderStrategy.javaschemagen/src/main/java/dev/metaschema/schemagen/xml/impl/XmlCoreDatatypeProvider.javacore/src/main/java/dev/metaschema/core/metapath/function/ArgumentImpl.java
📚 Learning: 2025-12-27T16:52:04.509Z
Learnt from: david-waltermire
Repo: metaschema-framework/metaschema-java PR: 590
File: core/src/main/java/gov/nist/secauto/metaschema/core/metapath/DynamicContext.java:482-492
Timestamp: 2025-12-27T16:52:04.509Z
Learning: In Java, UncheckedIOException.getCause() is declared to return IOException. In methods that declare throws IOException, you can rethrow the underlying cause with throw e.getCause() where e is an UncheckedIOException, without a cast. Ensure the surrounding method signature includes throws IOException. This does not apply to other unchecked exceptions; verify that e is actually an UncheckedIOException before using this pattern.
Applied to files:
databind/src/main/java/dev/metaschema/databind/AbstractModuleLoaderStrategy.javaschemagen/src/main/java/dev/metaschema/schemagen/xml/impl/XmlCoreDatatypeProvider.javacore/src/main/java/dev/metaschema/core/metapath/function/ArgumentImpl.java
📚 Learning: 2026-01-05T18:03:23.923Z
Learnt from: david-waltermire
Repo: metaschema-framework/metaschema-java PR: 618
File: core/src/main/java/dev/metaschema/core/datatype/package-info.java:52-52
Timestamp: 2026-01-05T18:03:23.923Z
Learning: Follow the canonical coding guidelines in CLAUDE.md for metaschema-framework/metaschema-java. For Java packages, use the dev.metaschema.* convention. Ensure all Java source files, including package-info.java under dev/metaschema/*, declare and align package statements with the path (e.g., package dev.metaschema.core.datatype;). This pattern applies to all Java files under the dev/metaschema namespace.
Applied to files:
databind/src/main/java/dev/metaschema/databind/AbstractModuleLoaderStrategy.javaschemagen/src/main/java/dev/metaschema/schemagen/xml/impl/XmlCoreDatatypeProvider.javacore/src/main/java/dev/metaschema/core/metapath/function/ArgumentImpl.java
📚 Learning: 2026-01-05T18:03:10.966Z
Learnt from: david-waltermire
Repo: metaschema-framework/metaschema-java PR: 618
File: core/src/main/java/dev/metaschema/core/metapath/format/IPathSegment.java:0-0
Timestamp: 2026-01-05T18:03:10.966Z
Learning: When overriding methods whose nullability contract is already declared in a superinterface or superclass (e.g., IMetapathQueryable#getNodeItem()), do not duplicate SpotBugs nullability annotations on the overriding method. Rely on the inherited annotation to convey nullability. Apply this consistently across the Java codebase (e.g., in core/metaschema/core/metapath/format) to avoid annotation duplication and keep tooling output clean. If the contract is not established in the parent, annotate explicitly on the override as needed.
Applied to files:
core/src/main/java/dev/metaschema/core/metapath/function/ArgumentImpl.java
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
- GitHub Check: Code
- GitHub Check: Website
🔇 Additional comments (3)
core/src/main/java/dev/metaschema/core/metapath/function/ArgumentImpl.java (1)
54-63: LGTM! Clean suppression removal.The removal of NOPMD comments from the
equalsmethod is appropriate. The implementation follows standard Java best practices for equals/hashCode, and the logic is straightforward. The removal of@SuppressWarnings("null")fromtoSignature(mentioned in the summary) is also valid since all field accesses are on@NonNullmembers.schemagen/src/main/java/dev/metaschema/schemagen/xml/impl/XmlCoreDatatypeProvider.java (2)
18-18: LGTM!The new imports are correctly placed and necessary for the deduplication logic introduced in the
analyzeDependenciesmethod.Also applies to: 22-22
60-60: Add explicit test coverage for the deduplication behavior.The implementation using
HashSet<String>to deduplicate dependency values is sound and idiomatic. However, no explicit test was found that verifies this deduplication behavior, even though it represents a functional change to the method's semantics.The
analyzeDependenciesmethod is private and can only be tested indirectly throughhandleResults()or integration tests. WhileXmlSuiteTestexercises this code path as part of full schema generation, it does not explicitly verify that duplicate@baseattribute values are properly filtered. Per the TDD guidelines in the coding standards, add a unit test that explicitly verifies duplicates are deduplicated correctly.
de8725e
into
metaschema-framework:develop
Summary
UnnecessaryWarningSuppressionwarnings (138 total)SimplifiedTernary(1),CollapsibleIfStatements(2),LambdaCanBeMethodReference(1)These suppressions (
// NOPMDcomments and@SuppressWarningsannotations) were originally added for PMD rules that have since been removed, renamed, or no longer trigger on the suppressed code.Changes by Module
Test plan
-PCI -PreleaseUnnecessaryWarningSuppressionwarningsSummary by CodeRabbit
Refactor
Style
✏️ Tip: You can customize this high-level summary in your review settings.