Skip to content

Fix SonarCloud blocker and critical findings in biojava-structure - #1176

Merged
josemduarte merged 11 commits into
biojava:masterfrom
josemduarte:jd/sq-structure-blockers
Dec 5, 2026
Merged

josemduarte merged 11 commits into
biojava:masterfrom
josemduarte:jd/sq-structure-blockers

Conversation

@josemduarte

Copy link
Copy Markdown
Contributor

Works through the SonarCloud blocker findings in biojava-structure, and the critical findings that point at possible bugs. Findings in code that #1168 removes (Jama, MMTF, GuiWrapper, AlignmentProgressListener) are skipped.

Bugs fixed (each with a test that failed first)

  • XXE in structure XML parsers: five parsers (AFPChainXMLParser, MultipleAlignmentXMLParser, PdbPairXMLConverter, SiftsXMLParser, BiologicalAssemblyTransformation) resolved external entities, so a crafted file could read local files or make network requests. Adds XMLHelper.newSecureDocumentBuilderFactory() in biojava-core.
  • DSSPParser: the fourth H-bond column's energy went to Donor1 instead of Donor2, so every parsed state had a wrong Donor1 energy and no Donor2 energy. The existing test missed it because SecStrucState.equals ignores energies.
  • OptimalCECPMain: after setParameters(p), align(ca1, ca2) used default CE settings (window size, RMSD thresholds), because a shadowing params field was never passed down.
  • QsAlignResult.setSubunitMap: off-by-one bounds check, and an empty map crashed with NoSuchElementException.

Other fixes

  • Resource leaks (25): try-with-resources throughout. SiftsChainToUniprotMapping.download() never closed its streams. CliTools.configureBean and Ccp4Header.openPossiblyGzipped hand their streams to the caller by design, so the warning is suppressed there with the reason in a comment.
  • Malformed CATH/SCOP lines: now throw an IOException naming the line instead of ArrayIndexOutOfBoundsException.
  • Chem comp providers: no longer write static state from instance methods without synchronization.
  • Intended switch fallthroughs in CeSymm, ScopDescription, AsaCalculator and LocalPDBDirectory are made explicit. No behaviour change.
  • Tests: assertion-less tests now check something real, and TestSpaceGroup now fails on an unexpected fold type instead of passing silently.
  • Small cleanups: braces and indentation, Double.compare in comparators, replace for single characters, ThreadLocalRandom, a discarded replaceFirst in Site.toPDB().

Not addressed

  • 29 clone() findings (S2975): replacing them with copy constructors is an API change, now item 10 in BioJava 8.0 plan: Java 21, a leaner, library-only BioJava #1168.
  • BridgeType.name / SecStrucType.name (S1845): public fields, so renaming them breaks the API for a naming-only issue.
  • 4 false positives: EcodInstallation.parseManualRep returns null on purpose, and Astral:222 and ClusterDomains:234 are safe as written.
  • Style and refactoring criticals (~540): constant names, method complexity and duplicated literals.

Testing

  • Core, alignment and structure unit tests pass locally (1,152 tests, 0 failures).
  • No test covers the CeSymm fallback for open alignments, which would need a structure with translational symmetry. The rewrite was checked by reading the old and new code side by side.

🤖 Generated with Claude Code

josemduarte and others added 11 commits December 4, 2026 19:19
Five parsers in biojava-structure built a DocumentBuilderFactory with
default settings, which resolves external entities: a crafted alignment,
SIFTS or assembly XML could read local files or make network requests
(Sonar java:S2755, blocker).

Add XMLHelper.newSecureDocumentBuilderFactory() in biojava-core, which
disables external entities, external DTDs and XInclude while still
accepting DOCTYPE declarations, and use it in AFPChainXMLParser,
MultipleAlignmentXMLParser, PdbPairXMLConverter, SiftsXMLParser and
BiologicalAssemblyTransformation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Use try-with-resources where streams were only closed on the success
path, or not at all (Sonar java:S2095, blocker):

- SiftsChainToUniprotMapping.download() never closed its input or
  output stream.
- AbstractUserArgumentProcessor, MultipleMcOptimizer, SymmOptimizer,
  AlignmentResult, AllChemCompProvider, SerializableCache,
  SiftsChainToUniprotMapping.build() and BlastClustReader leaked when
  an exception was thrown before the explicit close().
- SynchronizedOutFile leaked the file stream if the GZIPOutputStream
  constructor failed.
- Ccp4Header.openPossiblyGzipped() returns its stream to the caller, but
  leaked it if reading the magic bytes or opening the gzip wrapper failed.

CliTools.configureBean() and Ccp4Header.openPossiblyGzipped() hand their
streams to the caller by design, so S2095 is suppressed there with the
reason given in a comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The consistency check compared the largest map key and value against
the subunit list sizes with ">", but they are 0-based indices, so an
index equal to the list size slipped through and failed later in
getAlignedSubunits1/2. An empty map threw NoSuchElementException from
Collections.max before the code below could mark the relation as
DIFFERENT.

Use ">=", skip the check for an empty map, and use "||" instead of the
non-short-circuit "|" (Sonar java:S2178, blocker).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The flagged fallthroughs (Sonar java:S128, blocker) were all intended,
but read like missing breaks. Behaviour is unchanged:

- CeSymm: SEQUENCE_FUNCTION and ANGLE order detection and
  SEQUENCE_FUNCTION refinement fell through to GRAPH_COMPONENT for OPEN
  alignments. Pick the method up front instead.
- ScopDescription.getClassificationId: assign the number of parts per
  category instead of counting through the cases. Add a test.
- AsaCalculator: unexpected Q/E carbons fell through to the default
  radius; move that default after the switch.
- LocalPDBDirectory: FETCH_REMEDIATED with no local file fell into
  FORCE_DOWNLOAD only to set an already-null file to null; break instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
OptimalCECPMain declared its own "params" field, shadowing CeMain's
(Sonar java:S2387, blocker). setParameters() only updated the subclass
field, but CeMain.align(Atom[], Atom[]) passes CeMain's field down, so
the CP options came from the user's parameters while the CE options
(window size, RMSD thresholds, ...) silently stayed at their defaults.

Rename the subclass field to cpParams and have the constructor and
setParameters() store the same object in CeMain's field too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The private field "m" (gap-create + gap-extend) differed from the field
"M" (length of protein 1) only by case (Sonar java:S1845, blocker).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
These tests only checked that nothing threw (Sonar java:S2699, blocker):

- TestBond: the structures that used to crash formBonds() now must load
  with at least one chain.
- TestVeryLongFileName: toPDB() must wrap a long unbroken title into
  records of at most 80 columns.
- TestChemCompProvider.testNormalStructure: 4HHM must load with the
  ZipChemCompProvider and have chains.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
DSSPParser set the partner of the fourth H-bond column (O-->H-N) on
donor2 but its energy on donor1, so every state parsed from a DSSP file
had donor1's energy overwritten and no donor2 energy. The existing test
did not notice because SecStrucState.equals ignores energies.

Found while adding the default case Sonar asked for (java:S131).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A CathDomall line with fewer than three fields failed with a bare
ArrayIndexOutOfBoundsException, and a SCOP comments line made only of
"!" did the same, while a blank one failed in Integer.parseInt (Sonar
javabugs:S6466). Throw an IOException naming the line instead, and skip
blank lines in the SCOP comments file.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
AllChemCompProvider.loadAllChemComps() only touches static state, so
make it static. DownloadChemCompProvider lazily created its static
fallback provider from an instance method without synchronisation;
ReducedChemCompProvider is cheap to create, so create it once when the
class is loaded (Sonar java:S2696).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Behaviour-preserving cleanups for the remaining critical findings that
point at possible bugs:

- Default cases for switches on a random direction (MultipleMcOptimizer,
  SymmOptimizer) that throw if reached, and default cases that fail in
  TestSpaceGroup, where an unexpected fold type passed silently (S131).
- Braces where indentation suggested a different nesting in the PDP code
  and HelicalRepeatUnit, and "\t" instead of raw tabs in literals
  (S3973, S2479).
- Double.compare in the FragmentJoiner and RotationGroup comparators,
  which keeps them consistent for NaN (S9148).
- replace() instead of replaceAll() for literal characters (S5361).
- ThreadLocalRandom instead of a new Random per default seed (S2119).
- Site.toPDB(): one loop counter in the for clause, and drop a
  replaceFirst() whose result was discarded (S1994).
- Astral: try-with-resources (S2093).
- StructureName: check for a missing PDB ID instead of relying on the
  PdbId constructor throwing for null (S6416).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@josemduarte
josemduarte merged commit 7c3e625 into biojava:master Dec 5, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant