From e80374ba8559a0b124e868d906de9fb59482752c Mon Sep 17 00:00:00 2001
From: Tim Fennell
Date: Sat, 25 Apr 2026 08:26:06 -0600
Subject: [PATCH 1/2] Apply Palantir Java Format to entire codebase
This is a mechanical reformat of every .java file under src/ via the
Palantir Java Format style. There are no behavior changes.
The follow-up commit adds the Spotless Gradle plugin that produced this
output, wires it into the build as an enforcement step, updates the
contributor docs, deletes the obsolete java-style-eclipse.xml and
java-style-intellij.xml style guides, and adds .git-blame-ignore-revs
so this commit is skipped by `git blame`.
The single non-mechanical change in this commit is the removal of one
stray "// the imports for unit testing." comment from
VariantContextUnitTest.java that was preventing the formatter from
treating the surrounding imports as a contiguous block. The comment
carried no information.
Part of #1761.
---
src/main/java/htsjdk/annotations/BetaAPI.java | 7 +-
.../java/htsjdk/annotations/InternalAPI.java | 7 +-
.../codecs/hapref/fasta/FASTACodecV1_0.java | 34 +-
.../codecs/hapref/fasta/FASTADecoderV1_0.java | 35 +-
.../beta/codecs/reads/ReadsCodecUtils.java | 56 +-
.../beta/codecs/reads/bam/BAMCodec.java | 14 +-
.../beta/codecs/reads/bam/BAMDecoder.java | 17 +-
.../codecs/reads/bam/BAMDecoderOptions.java | 7 +-
.../beta/codecs/reads/bam/BAMEncoder.java | 16 +-
.../codecs/reads/bam/BAMEncoderOptions.java | 15 +-
.../reads/bam/bamV1_0/BAMCodecV1_0.java | 10 +-
.../reads/bam/bamV1_0/BAMDecoderV1_0.java | 14 +-
.../reads/bam/bamV1_0/BAMEncoderV1_0.java | 32 +-
.../beta/codecs/reads/cram/CRAMCodec.java | 18 +-
.../beta/codecs/reads/cram/CRAMDecoder.java | 78 +-
.../codecs/reads/cram/CRAMDecoderOptions.java | 6 +-
.../beta/codecs/reads/cram/CRAMEncoder.java | 30 +-
.../codecs/reads/cram/CRAMEncoderOptions.java | 3 -
.../reads/cram/cramV2_1/CRAMCodecV2_1.java | 7 +-
.../reads/cram/cramV2_1/CRAMDecoderV2_1.java | 3 +-
.../reads/cram/cramV2_1/CRAMEncoderV2_1.java | 3 +-
.../reads/cram/cramV3_0/CRAMCodecV3_0.java | 8 +-
.../reads/cram/cramV3_0/CRAMDecoderV3_0.java | 1 -
.../reads/cram/cramV3_0/CRAMEncoderV3_0.java | 1 -
.../reads/cram/cramV3_1/CRAMCodecV3_1.java | 6 +-
.../reads/cram/cramV3_1/CRAMDecoderV3_1.java | 1 -
.../reads/cram/cramV3_1/CRAMEncoderV3_1.java | 2 -
.../codecs/reads/htsget/HtsgetBAMCodec.java | 31 +-
.../codecs/reads/htsget/HtsgetBAMDecoder.java | 11 +-
.../htsgetBAMV1_2/HtsgetBAMCodecV1_2.java | 13 +-
.../htsgetBAMV1_2/HtsgetBAMDecoderV1_2.java | 15 +-
.../beta/codecs/reads/sam/SAMCodec.java | 16 +-
.../beta/codecs/reads/sam/SAMDecoder.java | 15 +-
.../beta/codecs/reads/sam/SAMEncoder.java | 12 +-
.../reads/sam/samV1_0/SAMCodecV1_0.java | 7 +-
.../reads/sam/samV1_0/SAMDecoderV1_0.java | 7 +-
.../reads/sam/samV1_0/SAMEncoderV1_0.java | 27 +-
.../beta/codecs/variants/vcf/VCFCodec.java | 25 +-
.../beta/codecs/variants/vcf/VCFDecoder.java | 58 +-
.../beta/codecs/variants/vcf/VCFEncoder.java | 56 +-
.../variants/vcf/VariantsCodecUtils.java | 5 +-
.../variants/vcf/vcfv3_2/VCFCodecV3_2.java | 13 +-
.../variants/vcf/vcfv3_2/VCFDecoderV3_2.java | 3 +-
.../variants/vcf/vcfv3_2/VCFEncoderV3_2.java | 5 +-
.../variants/vcf/vcfv3_3/VCFCodecV3_3.java | 13 +-
.../variants/vcf/vcfv3_3/VCFDecoderV3_3.java | 3 +-
.../variants/vcf/vcfv3_3/VCFEncoderV3_3.java | 5 +-
.../variants/vcf/vcfv4_0/VCFCodecV4_0.java | 13 +-
.../variants/vcf/vcfv4_0/VCFDecoderV4_0.java | 3 +-
.../variants/vcf/vcfv4_0/VCFEncoderV4_0.java | 5 +-
.../variants/vcf/vcfv4_1/VCFCodecV4_1.java | 13 +-
.../variants/vcf/vcfv4_1/VCFDecoderV4_1.java | 3 +-
.../variants/vcf/vcfv4_1/VCFEncoderV4_1.java | 5 +-
.../variants/vcf/vcfv4_2/VCFCodecV4_2.java | 11 +-
.../variants/vcf/vcfv4_2/VCFDecoderV4_2.java | 1 -
.../variants/vcf/vcfv4_2/VCFEncoderV4_2.java | 3 +-
.../variants/vcf/vcfv4_3/VCFCodecV4_3.java | 13 +-
.../variants/vcf/vcfv4_3/VCFDecoderV4_3.java | 3 +-
.../beta/exception/HtsjdkPluginException.java | 1 -
src/main/java/htsjdk/beta/io/IOPathUtils.java | 45 +-
.../java/htsjdk/beta/io/bundle/Bundle.java | 27 +-
.../htsjdk/beta/io/bundle/BundleBuilder.java | 12 +-
.../htsjdk/beta/io/bundle/BundleJSON.java | 107 +-
.../htsjdk/beta/io/bundle/BundleResource.java | 2 -
.../beta/io/bundle/BundleResourceBase.java | 38 +-
.../beta/io/bundle/BundleResourceType.java | 9 +-
.../htsjdk/beta/io/bundle/IOPathResource.java | 24 +-
.../beta/io/bundle/InputStreamResource.java | 22 +-
.../beta/io/bundle/OutputStreamResource.java | 10 +-
.../io/bundle/SeekableStreamResource.java | 22 +-
.../beta/io/bundle/SignatureStream.java | 5 +-
src/main/java/htsjdk/beta/package-info.java | 2 -
.../java/htsjdk/beta/plugin/HtsCodec.java | 14 +-
.../htsjdk/beta/plugin/HtsContentType.java | 2 +-
.../java/htsjdk/beta/plugin/HtsDecoder.java | 4 +-
.../htsjdk/beta/plugin/HtsDecoderOptions.java | 3 +-
.../java/htsjdk/beta/plugin/HtsEncoder.java | 2 -
.../htsjdk/beta/plugin/HtsEncoderOptions.java | 3 +-
.../java/htsjdk/beta/plugin/HtsHeader.java | 5 +-
.../java/htsjdk/beta/plugin/HtsRecord.java | 5 +-
.../java/htsjdk/beta/plugin/HtsVersion.java | 5 +-
src/main/java/htsjdk/beta/plugin/IOUtils.java | 49 +-
.../plugin/hapref/HapRefDecoderOptions.java | 3 +-
.../plugin/hapref/HaploidReferenceCodec.java | 10 +-
.../hapref/HaploidReferenceDecoder.java | 2 +-
.../HaploidReferenceDecoderOptions.java | 3 +-
.../hapref/HaploidReferenceEncoder.java | 2 +-
.../HaploidReferenceEncoderOptions.java | 3 +-
.../hapref/HaploidReferenceFormats.java | 1 -
.../plugin/interval/HtsIntervalUtils.java | 28 +-
.../htsjdk/beta/plugin/interval/HtsQuery.java | 11 +-
.../plugin/interval/HtsQueryInterval.java | 32 +-
.../htsjdk/beta/plugin/reads/ReadsBundle.java | 40 +-
.../htsjdk/beta/plugin/reads/ReadsCodec.java | 5 +-
.../beta/plugin/reads/ReadsDecoder.java | 4 +-
.../plugin/reads/ReadsDecoderOptions.java | 26 +-
.../beta/plugin/reads/ReadsEncoder.java | 2 +-
.../plugin/reads/ReadsEncoderOptions.java | 5 +-
.../beta/plugin/reads/ReadsFormats.java | 1 -
.../htsjdk/beta/plugin/reads/ReadsQuery.java | 1 -
.../registry/HaploidReferenceResolver.java | 33 +-
.../plugin/registry/HtsCodecRegistry.java | 37 +-
.../plugin/registry/HtsCodecResolver.java | 161 +-
.../plugin/registry/HtsDefaultRegistry.java | 14 +-
.../beta/plugin/registry/ReadsResolver.java | 25 +-
.../plugin/registry/VariantsResolver.java | 21 +-
.../beta/plugin/variants/VariantsBundle.java | 25 +-
.../beta/plugin/variants/VariantsCodec.java | 5 +-
.../beta/plugin/variants/VariantsDecoder.java | 2 +-
.../variants/VariantsDecoderOptions.java | 6 +-
.../beta/plugin/variants/VariantsEncoder.java | 2 +-
.../variants/VariantsEncoderOptions.java | 12 +-
src/main/java/htsjdk/io/AsyncWriterPool.java | 37 +-
src/main/java/htsjdk/io/HtsPath.java | 69 +-
src/main/java/htsjdk/io/IOPath.java | 11 +-
.../htsjdk/samtools/AbstractBAMFileIndex.java | 94 +-
.../samtools/AbstractSAMHeaderRecord.java | 14 +-
.../java/htsjdk/samtools/AlignmentBlock.java | 12 +-
.../htsjdk/samtools/AsyncSAMFileWriter.java | 23 +-
.../htsjdk/samtools/BAMFileConstants.java | 3 +-
.../java/htsjdk/samtools/BAMFileReader.java | 385 +++--
.../java/htsjdk/samtools/BAMFileSpan.java | 74 +-
.../java/htsjdk/samtools/BAMFileWriter.java | 61 +-
src/main/java/htsjdk/samtools/BAMIndex.java | 5 +-
.../java/htsjdk/samtools/BAMIndexContent.java | 144 +-
.../java/htsjdk/samtools/BAMIndexMerger.java | 39 +-
.../htsjdk/samtools/BAMIndexMetaData.java | 576 +++----
.../java/htsjdk/samtools/BAMIndexWriter.java | 5 +-
src/main/java/htsjdk/samtools/BAMIndexer.java | 48 +-
.../htsjdk/samtools/BAMIteratorFilter.java | 11 +-
...MQueryMultipleIntervalsIteratorFilter.java | 22 +-
src/main/java/htsjdk/samtools/BAMRecord.java | 73 +-
.../java/htsjdk/samtools/BAMRecordCodec.java | 66 +-
.../java/htsjdk/samtools/BAMSBIIndexer.java | 7 +-
.../samtools/BAMStartingAtIteratorFilter.java | 2 +-
.../java/htsjdk/samtools/BAMStreamWriter.java | 13 +-
.../java/htsjdk/samtools/BamConverter.java | 29 +-
.../java/htsjdk/samtools/BamFileIoUtils.java | 80 +-
.../htsjdk/samtools/BamIndexValidator.java | 436 +++---
src/main/java/htsjdk/samtools/Bin.java | 31 +-
src/main/java/htsjdk/samtools/BinList.java | 8 +-
.../htsjdk/samtools/BinaryBAMIndexWriter.java | 35 +-
.../java/htsjdk/samtools/BinaryTagCodec.java | 132 +-
.../htsjdk/samtools/BinningIndexBuilder.java | 22 +-
.../htsjdk/samtools/BinningIndexContent.java | 9 +-
.../htsjdk/samtools/BrowseableBAMIndex.java | 4 +-
.../java/htsjdk/samtools/CRAMBAIIndexer.java | 905 +++++------
.../java/htsjdk/samtools/CRAMCRAIIndexer.java | 36 +-
.../samtools/CRAMContainerStreamWriter.java | 16 +-
.../java/htsjdk/samtools/CRAMFileReader.java | 159 +-
.../java/htsjdk/samtools/CRAMFileWriter.java | 46 +-
.../java/htsjdk/samtools/CRAMIndexer.java | 1 -
.../java/htsjdk/samtools/CRAMIterator.java | 68 +-
src/main/java/htsjdk/samtools/CSIIndex.java | 122 +-
.../htsjdk/samtools/CachingBAMFileIndex.java | 47 +-
...achingBamFileIndexOptimizedForMerging.java | 34 +-
.../samtools/ChainedDownsamplingIterator.java | 8 +-
src/main/java/htsjdk/samtools/Chunk.java | 43 +-
src/main/java/htsjdk/samtools/Cigar.java | 139 +-
.../java/htsjdk/samtools/CigarElement.java | 9 +-
.../java/htsjdk/samtools/CigarOperator.java | 74 +-
.../samtools/ComparableSamRecordIterator.java | 14 +-
.../samtools/CompressedIndexFileBuffer.java | 10 +-
.../ConstantMemoryDownsamplingIterator.java | 11 +-
.../samtools/CoordinateSortedPairInfoMap.java | 21 +-
.../htsjdk/samtools/CustomReaderFactory.java | 195 ++-
.../samtools/DefaultSAMRecordFactory.java | 58 +-
src/main/java/htsjdk/samtools/Defaults.java | 28 +-
.../samtools/DiskBasedBAMFileIndex.java | 31 +-
.../htsjdk/samtools/DownsamplingIterator.java | 37 +-
.../samtools/DownsamplingIteratorFactory.java | 62 +-
.../samtools/DuplicateScoringStrategy.java | 22 +-
.../java/htsjdk/samtools/DuplicateSet.java | 23 +-
.../htsjdk/samtools/DuplicateSetIterator.java | 46 +-
.../samtools/FileTruncatedException.java | 3 +-
.../htsjdk/samtools/GenomicIndexUtil.java | 69 +-
.../HighAccuracyDownsamplingIterator.java | 35 +-
.../htsjdk/samtools/HtsgetBAMFileReader.java | 207 +--
.../java/htsjdk/samtools/IndexFileBuffer.java | 8 +-
.../samtools/IndexFileBufferFactory.java | 9 +-
.../htsjdk/samtools/IndexStreamBuffer.java | 31 +-
.../java/htsjdk/samtools/LinearIndex.java | 18 +-
.../samtools/MemoryMappedFileBuffer.java | 4 +-
.../samtools/MergingSamRecordIterator.java | 29 +-
.../java/htsjdk/samtools/QueryInterval.java | 15 +-
.../samtools/RandomAccessFileBuffer.java | 17 +-
.../htsjdk/samtools/ReservedTagConstants.java | 139 +-
.../SAMBinaryTagAndUnsignedArrayValue.java | 6 +-
.../htsjdk/samtools/SAMBinaryTagAndValue.java | 101 +-
.../java/htsjdk/samtools/SAMException.java | 3 +-
.../java/htsjdk/samtools/SAMFileHeader.java | 40 +-
.../java/htsjdk/samtools/SAMFileWriter.java | 26 +-
.../htsjdk/samtools/SAMFileWriterFactory.java | 146 +-
.../htsjdk/samtools/SAMFileWriterImpl.java | 77 +-
src/main/java/htsjdk/samtools/SAMFlag.java | 39 +-
.../htsjdk/samtools/SAMFormatException.java | 3 +-
.../samtools/SAMHeaderRecordComparator.java | 49 +-
.../java/htsjdk/samtools/SAMLineParser.java | 79 +-
.../htsjdk/samtools/SAMProgramRecord.java | 26 +-
.../htsjdk/samtools/SAMReadGroupRecord.java | 155 +-
src/main/java/htsjdk/samtools/SAMRecord.java | 479 +++---
.../SAMRecordCoordinateComparator.java | 5 +-
.../SAMRecordDuplicateComparator.java | 78 +-
.../htsjdk/samtools/SAMRecordFactory.java | 27 +-
.../htsjdk/samtools/SAMRecordIterator.java | 1 -
.../SAMRecordQueryHashComparator.java | 4 +-
.../SAMRecordQueryNameComparator.java | 6 +-
.../htsjdk/samtools/SAMRecordSetBuilder.java | 223 ++-
.../samtools/SAMSequenceDictionary.java | 114 +-
.../samtools/SAMSequenceDictionaryCodec.java | 3 +-
.../htsjdk/samtools/SAMSequenceRecord.java | 62 +-
src/main/java/htsjdk/samtools/SAMTag.java | 8 +-
src/main/java/htsjdk/samtools/SAMTagUtil.java | 187 ++-
.../java/htsjdk/samtools/SAMTestUtil.java | 5 +-
.../htsjdk/samtools/SAMTextHeaderCodec.java | 154 +-
.../java/htsjdk/samtools/SAMTextReader.java | 22 +-
.../java/htsjdk/samtools/SAMTextWriter.java | 11 +-
src/main/java/htsjdk/samtools/SAMUtils.java | 204 ++-
.../htsjdk/samtools/SAMValidationError.java | 25 +-
src/main/java/htsjdk/samtools/SBIIndex.java | 58 +-
.../java/htsjdk/samtools/SBIIndexMerger.java | 10 +-
.../java/htsjdk/samtools/SBIIndexWriter.java | 14 +-
src/main/java/htsjdk/samtools/SQTagUtil.java | 22 +-
.../java/htsjdk/samtools/SRAFileReader.java | 74 +-
src/main/java/htsjdk/samtools/SRAIndex.java | 72 +-
.../java/htsjdk/samtools/SRAIterator.java | 79 +-
.../htsjdk/samtools/SamFileHeaderMerger.java | 258 ++--
.../htsjdk/samtools/SamFileValidator.java | 197 ++-
src/main/java/htsjdk/samtools/SamFiles.java | 18 +-
.../java/htsjdk/samtools/SamFlagField.java | 101 +-
src/main/java/htsjdk/samtools/SamIndexes.java | 15 +-
.../htsjdk/samtools/SamInputResource.java | 79 +-
.../java/htsjdk/samtools/SamPairUtil.java | 171 ++-
src/main/java/htsjdk/samtools/SamReader.java | 37 +-
.../htsjdk/samtools/SamReaderFactory.java | 199 ++-
src/main/java/htsjdk/samtools/SamStreams.java | 64 +-
.../SecondaryAlignmentSkippingIterator.java | 2 +-
...ondaryOrSupplementarySkippingIterator.java | 3 +-
.../StreamInflatingIndexingOutputStream.java | 8 +-
.../java/htsjdk/samtools/TextCigarCodec.java | 8 +-
.../java/htsjdk/samtools/TextTagCodec.java | 48 +-
.../samtools/TextualBAMIndexWriter.java | 47 +-
.../samtools/apps/TimeRandomAccessFile.java | 3 +-
.../java/htsjdk/samtools/cram/BAIEntry.java | 50 +-
.../java/htsjdk/samtools/cram/CRAIEntry.java | 49 +-
.../java/htsjdk/samtools/cram/CRAIIndex.java | 30 +-
.../htsjdk/samtools/cram/CRAIIndexMerger.java | 56 +-
.../htsjdk/samtools/cram/CRAMException.java | 2 +-
.../htsjdk/samtools/cram/CramComparison.java | 72 +-
.../htsjdk/samtools/cram/CramConverter.java | 34 +-
.../java/htsjdk/samtools/cram/CramStats.java | 24 +-
.../cram/build/CRAMReferenceRegion.java | 50 +-
.../cram/build/CompressionHeaderFactory.java | 81 +-
.../samtools/cram/build/ContainerFactory.java | 27 +-
.../build/CramContainerHeaderIterator.java | 7 +-
.../cram/build/CramContainerIterator.java | 1 -
.../htsjdk/samtools/cram/build/CramIO.java | 81 +-
.../cram/build/CramSpanContainerIterator.java | 7 +-
.../samtools/cram/build/SliceFactory.java | 83 +-
.../htsjdk/samtools/cram/build/Utils.java | 3 +-
.../samtools/cram/common/CRAMVersion.java | 5 +-
.../samtools/cram/common/CramVersions.java | 13 +-
.../compression/BZIP2ExternalCompressor.java | 5 +-
.../cram/compression/CompressionUtils.java | 60 +-
.../cram/compression/ExternalCompressor.java | 36 +-
.../compression/GZIPExternalCompressor.java | 8 +-
.../compression/LZMAExternalCompressor.java | 12 +-
.../RANS4x8ExternalCompressor.java | 19 +-
.../RANSNx16ExternalCompressor.java | 12 +-
.../cram/compression/TrialCompressor.java | 4 +-
.../compression/fqzcomp/FQZCompDecode.java | 44 +-
.../compression/fqzcomp/FQZCompEncode.java | 39 +-
.../fqzcomp/FQZCompExternalCompressor.java | 10 +-
.../compression/fqzcomp/FQZGlobalFlags.java | 15 +-
.../cram/compression/fqzcomp/FQZModels.java | 10 +-
.../cram/compression/fqzcomp/FQZParam.java | 5 +-
.../cram/compression/fqzcomp/FQZParams.java | 7 +-
.../cram/compression/fqzcomp/FQZState.java | 120 +-
.../cram/compression/fqzcomp/FQZUtils.java | 6 +-
.../NameTokenisationDecode.java | 81 +-
.../NameTokenisationEncode.java | 164 +-
.../NameTokeniserExternalCompressor.java | 7 +-
.../nametokenisation/TokenStreams.java | 18 +-
.../nametokenisation/tokens/EncodeToken.java | 12 +-
.../cram/compression/range/ByteModel.java | 35 +-
.../cram/compression/range/Constants.java | 6 +-
.../cram/compression/range/RangeCoder.java | 26 +-
.../cram/compression/range/RangeDecode.java | 96 +-
.../cram/compression/range/RangeEncode.java | 22 +-
.../range/RangeExternalCompressor.java | 15 +-
.../cram/compression/range/RangeParams.java | 35 +-
.../cram/compression/rans/Constants.java | 7 +-
.../cram/compression/rans/RANS4x8Decode.java | 12 +-
.../cram/compression/rans/RANS4x8Encode.java | 95 +-
.../compression/rans/RANSEncodingSymbol.java | 4 +-
.../cram/compression/rans/RANSNx16Decode.java | 65 +-
.../cram/compression/rans/RANSNx16Encode.java | 50 +-
.../cram/compression/rans/RANSParams.java | 8 +-
.../cram/digest/AbstractSerialDigest.java | 6 +-
.../samtools/cram/digest/ByteSumCombine.java | 4 +-
.../samtools/cram/digest/ContentDigests.java | 76 +-
.../samtools/cram/digest/Crc32Hasher.java | 1 -
.../cram/digest/IntegerSumCombine.java | 1 -
.../cram/digest/MessageDigestHasher.java | 4 +-
.../htsjdk/samtools/cram/digest/SERIES.java | 3 +-
.../cram/encoding/ByteArrayLenCodec.java | 4 +-
.../cram/encoding/ByteArrayLenEncoding.java | 12 +-
.../samtools/cram/encoding/CRAMCodec.java | 2 +-
.../samtools/cram/encoding/CRAMEncoding.java | 5 +-
.../cram/encoding/EncodingFactory.java | 16 +-
.../cram/encoding/core/BetaIntegerCodec.java | 18 +-
.../encoding/core/BetaIntegerEncoding.java | 6 +-
.../core/CanonicalHuffmanByteCodec.java | 7 +-
.../core/CanonicalHuffmanByteEncoding.java | 15 +-
.../core/CanonicalHuffmanIntegerCodec.java | 7 +-
.../core/CanonicalHuffmanIntegerEncoding.java | 17 +-
.../cram/encoding/core/CoreCodec.java | 2 +-
.../cram/encoding/core/GammaIntegerCodec.java | 10 +-
.../encoding/core/GammaIntegerEncoding.java | 7 +-
.../core/SubexponentialIntegerCodec.java | 13 +-
.../core/SubexponentialIntegerEncoding.java | 5 +-
.../core/experimental/ExperimentalCodec.java | 3 +-
.../core/experimental/GolombIntegerCodec.java | 15 +-
.../experimental/GolombIntegerEncoding.java | 8 +-
.../core/experimental/GolombLongCodec.java | 12 +-
.../core/experimental/GolombLongEncoding.java | 6 +-
.../experimental/GolombRiceIntegerCodec.java | 10 +-
.../GolombRiceIntegerEncoding.java | 5 +-
.../core/huffmanUtils/HuffmanBitCode.java | 9 +-
.../HuffmanCanoncialCodeGenerator.java | 54 +-
.../core/huffmanUtils/HuffmanLeaf.java | 3 +-
.../core/huffmanUtils/HuffmanNode.java | 2 +-
.../core/huffmanUtils/HuffmanParams.java | 7 +-
.../huffmanUtils/HuffmanParamsCalculator.java | 6 +-
.../core/huffmanUtils/HuffmanTree.java | 4 +-
.../encoding/external/ByteArrayStopCodec.java | 10 +-
.../external/ByteArrayStopEncoding.java | 11 +-
.../external/ExternalByteArrayCodec.java | 8 +-
.../external/ExternalByteArrayEncoding.java | 16 +-
.../encoding/external/ExternalByteCodec.java | 12 +-
.../external/ExternalByteEncoding.java | 12 +-
.../external/ExternalIntegerCodec.java | 12 +-
.../external/ExternalIntegerEncoding.java | 13 +-
.../encoding/external/ExternalLongCodec.java | 12 +-
.../external/ExternalLongEncoding.java | 12 +-
.../encoding/reader/CramRecordReader.java | 101 +-
.../encoding/reader/DataSeriesReader.java | 9 +-
.../readfeatures/BaseQualityScore.java | 12 +-
.../cram/encoding/readfeatures/Bases.java | 3 +-
.../cram/encoding/readfeatures/Deletion.java | 3 +-
.../cram/encoding/readfeatures/HardClip.java | 3 +-
.../encoding/readfeatures/InsertBase.java | 12 +-
.../cram/encoding/readfeatures/Insertion.java | 3 +-
.../cram/encoding/readfeatures/Padding.java | 3 +-
.../cram/encoding/readfeatures/ReadBase.java | 17 +-
.../cram/encoding/readfeatures/RefSkip.java | 3 +-
.../cram/encoding/readfeatures/Scores.java | 4 +-
.../cram/encoding/readfeatures/SoftClip.java | 3 +-
.../encoding/readfeatures/Substitution.java | 6 +-
.../encoding/writer/CramRecordWriter.java | 94 +-
.../encoding/writer/DataSeriesWriter.java | 10 +-
.../samtools/cram/io/BitInputStream.java | 1 -
.../samtools/cram/io/BitOutputStream.java | 5 -
.../samtools/cram/io/CRC32InputStream.java | 8 +-
.../samtools/cram/io/CRC32OutputStream.java | 19 +-
.../samtools/cram/io/CountingInputStream.java | 1 -
.../java/htsjdk/samtools/cram/io/CramInt.java | 13 +-
.../htsjdk/samtools/cram/io/CramIntArray.java | 3 +-
.../cram/io/DefaultBitInputStream.java | 29 +-
.../cram/io/DefaultBitOutputStream.java | 38 +-
.../java/htsjdk/samtools/cram/io/ITF8.java | 49 +-
.../samtools/cram/io/InputStreamUtils.java | 5 +-
.../java/htsjdk/samtools/cram/io/LTF8.java | 22 +-
.../cram/ref/CRAMLazyReferenceSource.java | 8 +-
.../cram/ref/CRAMReferenceSource.java | 4 +-
.../samtools/cram/ref/EnaRefService.java | 17 +-
.../samtools/cram/ref/ReferenceContext.java | 6 +-
.../samtools/cram/ref/ReferenceSource.java | 90 +-
.../cram/structure/AlignmentContext.java | 58 +-
.../cram/structure/AlignmentSpan.java | 13 +-
.../structure/CRAMCompressionProfile.java | 157 +-
.../cram/structure/CRAMCompressionRecord.java | 284 ++--
.../cram/structure/CRAMEncodingStrategy.java | 70 +-
.../structure/CRAMRecordReadFeatures.java | 159 +-
.../cram/structure/CompressionHeader.java | 31 +-
.../CompressionHeaderEncodingMap.java | 147 +-
.../cram/structure/CompressorCache.java | 48 +-
.../samtools/cram/structure/Container.java | 93 +-
.../cram/structure/ContainerHeader.java | 57 +-
.../samtools/cram/structure/CramHeader.java | 6 +-
.../samtools/cram/structure/DataSeries.java | 71 +-
.../cram/structure/EncodingDescriptor.java | 6 +-
.../samtools/cram/structure/ReadTag.java | 131 +-
.../htsjdk/samtools/cram/structure/Slice.java | 336 ++--
.../samtools/cram/structure/SliceBlocks.java | 31 +-
.../structure/SliceBlocksReadStreams.java | 7 +-
.../structure/SliceBlocksWriteStreams.java | 16 +-
.../cram/structure/SubstitutionBase.java | 8 +-
.../cram/structure/SubstitutionMatrix.java | 45 +-
.../samtools/cram/structure/TagKeyCache.java | 4 +-
.../samtools/cram/structure/block/Block.java | 54 +-
.../block/BlockCompressionMethod.java | 3 +-
.../structure/block/BlockContentType.java | 1 -
.../samtools/example/ExampleSamUsage.java | 38 +-
.../samtools/example/PrintReadsExample.java | 31 +-
.../samtools/fastq/AsyncFastqWriter.java | 17 +-
.../samtools/fastq/BasicFastqWriter.java | 5 +-
.../htsjdk/samtools/fastq/FastqConstants.java | 15 +-
.../htsjdk/samtools/fastq/FastqEncoder.java | 27 +-
.../htsjdk/samtools/fastq/FastqReader.java | 64 +-
.../htsjdk/samtools/fastq/FastqRecord.java | 50 +-
.../htsjdk/samtools/fastq/FastqWriter.java | 3 +-
.../samtools/fastq/FastqWriterFactory.java | 14 +-
.../filter/AbstractJavascriptFilter.java | 16 +-
.../samtools/filter/AggregateFilter.java | 161 +-
.../htsjdk/samtools/filter/AlignedFilter.java | 178 +--
.../samtools/filter/DuplicateReadFilter.java | 1 +
.../filter/FailsVendorReadQualityFilter.java | 118 +-
.../samtools/filter/FilteringIterator.java | 11 +-
.../samtools/filter/FilteringSamIterator.java | 15 +-
.../samtools/filter/InsertSizeFilter.java | 2 +-
.../samtools/filter/IntervalFilter.java | 17 +-
.../filter/IntervalKeepPairFilter.java | 10 +-
.../htsjdk/samtools/filter/InvertFilter.java | 4 +-
.../filter/JavascriptSamRecordFilter.java | 17 +-
.../filter/NotPrimaryAlignmentFilter.java | 4 +-
.../filter/OverclippedReadFilter.java | 16 +-
.../samtools/filter/ReadNameFilter.java | 220 ++-
.../samtools/filter/SamRecordFilter.java | 106 +-
.../filter/SecondaryAlignmentFilter.java | 4 +-
.../SecondaryOrSupplementaryFilter.java | 2 +-
.../samtools/filter/SolexaNoiseFilter.java | 135 +-
.../htsjdk/samtools/filter/TagFilter.java | 233 ++-
.../filter/WholeReadClippedFilter.java | 4 +-
.../java/htsjdk/samtools/liftover/Chain.java | 100 +-
.../htsjdk/samtools/liftover/LiftOver.java | 82 +-
.../java/htsjdk/samtools/metrics/Header.java | 1 -
.../htsjdk/samtools/metrics/MetricBase.java | 36 +-
.../htsjdk/samtools/metrics/MetricsFile.java | 199 +--
.../htsjdk/samtools/metrics/StringHeader.java | 24 +-
.../samtools/metrics/VersionHeader.java | 10 +-
.../reference/AbstractFastaSequenceFile.java | 28 +-
.../AbstractIndexedFastaSequenceFile.java | 102 +-
...ockCompressedIndexedFastaSequenceFile.java | 19 +-
.../reference/FastaReferenceWriter.java | 123 +-
.../FastaReferenceWriterBuilder.java | 29 +-
.../samtools/reference/FastaSequenceFile.java | 24 +-
.../reference/FastaSequenceIndex.java | 53 +-
.../reference/FastaSequenceIndexCreator.java | 34 +-
.../reference/FastaSequenceIndexEntry.java | 30 +-
.../reference/IndexedFastaSequenceFile.java | 9 +-
.../samtools/reference/ReferenceSequence.java | 22 +-
.../reference/ReferenceSequenceFile.java | 8 +-
.../ReferenceSequenceFileFactory.java | 67 +-
.../ReferenceSequenceFileWalker.java | 29 +-
.../SamLocusAndReferenceIterator.java | 31 +-
.../ISeekableStreamFactory.java | 5 +-
.../SeekableBufferedStream.java | 7 +-
.../seekablestream/SeekableFTPStream.java | 19 +-
.../SeekableFTPStreamHelper.java | 11 +-
.../seekablestream/SeekableFileStream.java | 22 +-
.../seekablestream/SeekableHTTPStream.java | 32 +-
.../seekablestream/SeekableMemoryStream.java | 1 -
.../seekablestream/SeekablePathStream.java | 18 +-
.../seekablestream/SeekableStream.java | 9 +-
.../seekablestream/SeekableStreamFactory.java | 50 +-
.../seekablestream/UserPasswordInput.java | 65 +-
.../htsjdk/samtools/sra/ReferenceCache.java | 1 -
.../htsjdk/samtools/sra/SRAAccession.java | 68 +-
.../samtools/sra/SRAAlignmentIterator.java | 83 +-
.../samtools/sra/SRAIndexedSequenceFile.java | 17 +-
.../htsjdk/samtools/sra/SRALazyRecord.java | 106 +-
.../samtools/sra/SRAUnalignmentIterator.java | 72 +-
.../java/htsjdk/samtools/sra/SRAUtils.java | 53 +-
.../samtools/util/AbstractAsyncWriter.java | 34 +-
.../samtools/util/AbstractLocusInfo.java | 9 +-
.../samtools/util/AbstractLocusIterator.java | 90 +-
.../samtools/util/AbstractProgressLogger.java | 37 +-
.../util/AbstractRecordAndOffset.java | 7 +-
.../htsjdk/samtools/util/AsciiWriter.java | 1 -
.../util/AsyncBlockCompressedInputStream.java | 41 +-
.../samtools/util/AsyncBufferedIterator.java | 54 +-
.../htsjdk/samtools/util/BinaryCodec.java | 1366 ++++++++---------
.../util/BlockCompressedFilePointerUtil.java | 11 +-
.../util/BlockCompressedInputStream.java | 163 +-
.../util/BlockCompressedOutputStream.java | 52 +-
.../util/BlockCompressedStreamConstants.java | 75 +-
.../htsjdk/samtools/util/BlockGunzipper.java | 32 +-
.../samtools/util/BufferedLineReader.java | 17 +-
.../java/htsjdk/samtools/util/CigarUtil.java | 204 +--
.../samtools/util/CloseableIterator.java | 2 +-
.../java/htsjdk/samtools/util/CloserUtil.java | 161 +-
.../htsjdk/samtools/util/CollectionUtil.java | 29 +-
.../htsjdk/samtools/util/ComparableTuple.java | 3 +-
.../java/htsjdk/samtools/util/CoordMath.java | 12 +-
.../samtools/util/CoordSpanInputSteam.java | 7 +-
.../samtools/util/CustomGzipOutputStream.java | 4 +-
.../java/htsjdk/samtools/util/DateParser.java | 53 +-
.../htsjdk/samtools/util/DiskBackedQueue.java | 64 +-
.../samtools/util/EdgeReadIterator.java | 110 +-
.../samtools/util/EdgingRecordAndOffset.java | 11 +-
.../htsjdk/samtools/util/FastLineReader.java | 4 +-
.../util/FileAppendStreamLRUCache.java | 10 +-
.../htsjdk/samtools/util/FileExtensions.java | 30 +-
.../java/htsjdk/samtools/util/FormatUtil.java | 117 +-
.../java/htsjdk/samtools/util/GZIIndex.java | 53 +-
.../java/htsjdk/samtools/util/GzipCodec.java | 65 +-
.../java/htsjdk/samtools/util/Histogram.java | 101 +-
.../java/htsjdk/samtools/util/HttpUtils.java | 23 +-
.../java/htsjdk/samtools/util/IOUtil.java | 322 ++--
.../java/htsjdk/samtools/util/Interval.java | 24 +-
.../htsjdk/samtools/util/IntervalCodec.java | 14 +-
.../util/IntervalCoordinateComparator.java | 1 -
.../htsjdk/samtools/util/IntervalList.java | 145 +-
.../IntervalListReferenceSequenceMask.java | 5 +-
.../samtools/util/IntervalListWriter.java | 3 -
.../htsjdk/samtools/util/IntervalTree.java | 698 +++------
.../htsjdk/samtools/util/IntervalTreeMap.java | 62 +-
.../htsjdk/samtools/util/IntervalUtil.java | 19 +-
.../samtools/util/IterableOnceIterator.java | 6 +-
.../java/htsjdk/samtools/util/Iterables.java | 4 +-
src/main/java/htsjdk/samtools/util/Lazy.java | 6 +-
.../java/htsjdk/samtools/util/ListMap.java | 2 +-
.../java/htsjdk/samtools/util/Locatable.java | 4 +-
.../htsjdk/samtools/util/LocationAware.java | 10 +-
src/main/java/htsjdk/samtools/util/Locus.java | 2 +-
src/main/java/htsjdk/samtools/util/Log.java | 7 +-
.../util/Md5CalculatingInputStream.java | 32 +-
.../util/Md5CalculatingOutputStream.java | 21 +-
.../htsjdk/samtools/util/MergingIterator.java | 204 +--
.../java/htsjdk/samtools/util/Murmur3.java | 26 +-
.../htsjdk/samtools/util/OverlapDetector.java | 13 +-
.../htsjdk/samtools/util/PeekIterator.java | 4 +-
.../samtools/util/PeekableIterator.java | 7 +-
.../samtools/util/PositionalOutputStream.java | 55 +-
.../htsjdk/samtools/util/ProcessExecutor.java | 85 +-
.../htsjdk/samtools/util/ProgressLogger.java | 10 +-
.../util/ProgressLoggerInterface.java | 13 +-
.../util/QualityEncodingDetector.java | 70 +-
.../htsjdk/samtools/util/QualityUtil.java | 6 +-
.../samtools/util/ResourceLimitedMap.java | 23 +-
.../samtools/util/RuntimeEOFException.java | 3 +-
.../samtools/util/RuntimeIOException.java | 3 +-
.../samtools/util/RuntimeScriptException.java | 4 +-
.../util/SAMRecordPrefetchingIterator.java | 30 +-
.../htsjdk/samtools/util/SamConstants.java | 7 +-
.../samtools/util/SamLocusIterator.java | 39 +-
.../SamRecordIntervalIteratorFactory.java | 23 +-
.../util/SamRecordTrackingBuffer.java | 110 +-
.../samtools/util/SamRecordWithOrdinal.java | 21 +-
.../htsjdk/samtools/util/SequenceUtil.java | 199 +--
.../htsjdk/samtools/util/SnappyLoader.java | 25 +-
.../samtools/util/SnappyLoaderInternal.java | 24 +-
.../samtools/util/SolexaQualityConverter.java | 17 +-
.../samtools/util/SortingCollection.java | 141 +-
.../samtools/util/SortingLongCollection.java | 10 +-
.../java/htsjdk/samtools/util/StopWatch.java | 5 +-
.../java/htsjdk/samtools/util/StringUtil.java | 195 ++-
.../samtools/util/TempStreamFactory.java | 1 -
.../java/htsjdk/samtools/util/TestUtil.java | 15 +-
.../htsjdk/samtools/util/TrimmingUtil.java | 2 +-
.../htsjdk/samtools/util/ftp/FTPClient.java | 474 +++---
.../htsjdk/samtools/util/ftp/FTPReply.java | 220 ++-
.../htsjdk/samtools/util/ftp/FTPStream.java | 105 +-
.../htsjdk/samtools/util/ftp/FTPUtils.java | 66 +-
.../util/htsget/HtsgetErrorResponse.java | 1 -
.../HtsgetMalformedResponseException.java | 2 +-
.../util/htsget/HtsgetPOSTRequest.java | 53 +-
.../samtools/util/htsget/HtsgetRequest.java | 82 +-
.../samtools/util/htsget/HtsgetResponse.java | 46 +-
.../util/nio/DeleteOnExitPathHook.java | 5 +-
.../samtools/util/zip/DeflaterFactory.java | 5 +-
.../samtools/util/zip/InflaterFactory.java | 3 +-
.../samtools/util/zip/LibdeflateDeflater.java | 9 +-
.../samtools/util/zip/LibdeflateInflater.java | 1 -
.../htsjdk/tribble/AbstractFeatureCodec.java | 5 +-
.../htsjdk/tribble/AbstractFeatureReader.java | 110 +-
.../htsjdk/tribble/AsciiFeatureCodec.java | 10 +-
.../htsjdk/tribble/BinaryFeatureCodec.java | 6 +-
src/main/java/htsjdk/tribble/Feature.java | 4 +-
.../java/htsjdk/tribble/FeatureCodec.java | 14 +-
.../htsjdk/tribble/FeatureCodecHeader.java | 6 +-
.../java/htsjdk/tribble/FeatureReader.java | 1 -
.../IntervalList/IntervalListCodec.java | 68 +-
.../java/htsjdk/tribble/MutableFeature.java | 2 +-
.../java/htsjdk/tribble/NameAwareCodec.java | 1 +
.../java/htsjdk/tribble/NamedFeature.java | 1 -
.../htsjdk/tribble/TabixFeatureReader.java | 43 +-
src/main/java/htsjdk/tribble/Tribble.java | 6 +-
.../java/htsjdk/tribble/TribbleException.java | 35 +-
.../tribble/TribbleIndexedFeatureReader.java | 111 +-
.../htsjdk/tribble/annotation/Strand.java | 8 +-
.../java/htsjdk/tribble/bed/BEDCodec.java | 19 +-
.../java/htsjdk/tribble/bed/BEDFeature.java | 1 -
.../htsjdk/tribble/bed/FullBEDFeature.java | 21 +-
.../htsjdk/tribble/bed/SimpleBEDFeature.java | 7 +-
.../htsjdk/tribble/example/CountRecords.java | 29 +-
.../tribble/example/ExampleBinaryCodec.java | 21 +-
.../htsjdk/tribble/example/IndexToTable.java | 11 +-
.../tribble/example/IndicesAreEqual.java | 6 +-
.../tribble/example/ProfileIndexReading.java | 9 +-
.../exception/CodecLineParsingException.java | 4 +-
.../exception/UnsortedFileException.java | 5 +-
.../java/htsjdk/tribble/gff/Gff3BaseData.java | 64 +-
.../java/htsjdk/tribble/gff/Gff3Codec.java | 146 +-
.../htsjdk/tribble/gff/Gff3Constants.java | 24 +-
.../java/htsjdk/tribble/gff/Gff3Feature.java | 41 +-
.../htsjdk/tribble/gff/Gff3FeatureImpl.java | 115 +-
.../java/htsjdk/tribble/gff/Gff3Writer.java | 52 +-
.../htsjdk/tribble/gff/SequenceRegion.java | 25 +-
.../htsjdk/tribble/index/AbstractIndex.java | 40 +-
src/main/java/htsjdk/tribble/index/Block.java | 12 +-
.../java/htsjdk/tribble/index/ChrIndex.java | 2 -
.../tribble/index/DynamicIndexCreator.java | 106 +-
src/main/java/htsjdk/tribble/index/Index.java | 3 +-
.../htsjdk/tribble/index/IndexCreator.java | 6 +-
.../htsjdk/tribble/index/IndexFactory.java | 240 +--
.../tribble/index/TribbleIndexCreator.java | 3 +-
.../tribble/index/interval/Interval.java | 33 +-
.../index/interval/IntervalIndexCreator.java | 21 +-
.../tribble/index/interval/IntervalTree.java | 85 +-
.../index/interval/IntervalTreeIndex.java | 17 +-
.../tribble/index/linear/LinearIndex.java | 74 +-
.../index/linear/LinearIndexCreator.java | 32 +-
.../index/tabix/AllRefsTabixIndexCreator.java | 38 +-
.../tabix/StreamBasedTabixIndexCreator.java | 61 +-
.../tribble/index/tabix/TabixFormat.java | 22 +-
.../tribble/index/tabix/TabixIndex.java | 33 +-
.../index/tabix/TabixIndexCreator.java | 32 +-
.../tribble/index/tabix/TabixIndexMerger.java | 32 +-
.../tribble/readers/AsciiLineReader.java | 46 +-
.../readers/AsciiLineReaderIterator.java | 20 +-
.../BlockCompressedAsciiLineReader.java | 9 +-
.../tribble/readers/LineIteratorImpl.java | 5 +-
.../htsjdk/tribble/readers/LineReader.java | 1 -
.../readers/LongLineBufferedReader.java | 90 +-
.../htsjdk/tribble/readers/Positional.java | 3 +-
.../readers/PositionalBufferedStream.java | 49 +-
.../readers/SynchronousLineReader.java | 11 +-
.../readers/TabixIteratorLineReader.java | 4 +-
.../htsjdk/tribble/readers/TabixReader.java | 152 +-
.../java/htsjdk/tribble/util/FTPHelper.java | 4 +-
.../java/htsjdk/tribble/util/HTTPHelper.java | 4 -
.../tribble/util/LittleEndianInputStream.java | 42 +-
.../util/LittleEndianOutputStream.java | 28 +-
.../java/htsjdk/tribble/util/MathUtils.java | 25 +-
.../htsjdk/tribble/util/ParsingUtils.java | 66 +-
.../java/htsjdk/tribble/util/TabixUtils.java | 3 -
.../java/htsjdk/tribble/util/URLHelper.java | 2 -
.../htsjdk/tribble/util/URLHelperFactory.java | 1 -
.../util/popgen/HardyWeinbergCalculation.java | 233 ++-
src/main/java/htsjdk/utils/ClassFinder.java | 39 +-
.../java/htsjdk/utils/ValidationUtils.java | 2 -
.../java/htsjdk/variant/bcf2/BCF2Codec.java | 206 ++-
.../java/htsjdk/variant/bcf2/BCF2Decoder.java | 131 +-
.../bcf2/BCF2GenotypeFieldDecoders.java | 195 ++-
.../bcf2/BCF2LazyGenotypesDecoder.java | 74 +-
.../java/htsjdk/variant/bcf2/BCF2Type.java | 83 +-
.../java/htsjdk/variant/bcf2/BCF2Utils.java | 175 ++-
.../java/htsjdk/variant/bcf2/BCFVersion.java | 53 +-
.../variant/example/PrintVariantsExample.java | 29 +-
.../utils/BinomialCoefficientUtil.java | 27 +-
.../htsjdk/variant/utils/GeneralUtils.java | 90 +-
.../utils/SAMSequenceDictionaryExtractor.java | 25 +-
.../htsjdk/variant/utils/VCFHeaderReader.java | 10 +-
.../htsjdk/variant/variantcontext/Allele.java | 134 +-
.../variant/variantcontext/CommonInfo.java | 180 +--
.../variant/variantcontext/FastGenotype.java | 95 +-
.../variant/variantcontext/Genotype.java | 221 +--
.../variantcontext/GenotypeBuilder.java | 125 +-
.../variantcontext/GenotypeJEXLContext.java | 16 +-
.../variantcontext/GenotypeLikelihoods.java | 250 ++-
.../GenotypeNumLikelihoodsCache.java | 46 +-
.../variant/variantcontext/GenotypeType.java | 48 +-
.../variantcontext/GenotypesContext.java | 138 +-
.../variant/variantcontext/JEXLMap.java | 38 +-
.../JexlMissingValueTreatment.java | 9 +-
.../variantcontext/LazyGenotypesContext.java | 76 +-
.../variant/variantcontext/SimpleAllele.java | 129 +-
.../variantcontext/StructuralVariantType.java | 3 +-
.../variantcontext/VariantContext.java | 657 ++++----
.../variantcontext/VariantContextBuilder.java | 98 +-
.../VariantContextComparator.java | 157 +-
.../variantcontext/VariantContextUtils.java | 222 +--
.../variantcontext/VariantJEXLContext.java | 58 +-
.../variantcontext/filter/CompoundFilter.java | 1 -
.../filter/FilteringIterator.java | 5 +-
.../FilteringVariantContextIterator.java | 3 +-
.../filter/GenotypeQualityFilter.java | 15 +-
.../filter/HeterozygosityFilter.java | 13 +-
.../filter/JavascriptVariantFilter.java | 91 +-
.../filter/VariantContextFilter.java | 3 +-
.../writer/AsyncVariantContextWriter.java | 18 +-
.../variantcontext/writer/BCF2Encoder.java | 139 +-
.../writer/BCF2FieldEncoder.java | 187 ++-
.../writer/BCF2FieldWriter.java | 132 +-
.../writer/BCF2FieldWriterManager.java | 115 +-
.../variantcontext/writer/BCF2Writer.java | 204 +--
.../writer/IndexingVariantContextWriter.java | 112 +-
.../writer/IntGenotypeFieldAccessors.java | 71 +-
.../variantcontext/writer/Options.java | 50 +-
.../writer/SortingVariantContextWriter.java | 51 +-
.../SortingVariantContextWriterBase.java | 73 +-
.../variantcontext/writer/VCFWriter.java | 184 ++-
.../writer/VariantContextWriter.java | 55 +-
.../writer/VariantContextWriterBuilder.java | 199 +--
.../htsjdk/variant/vcf/AbstractVCFCodec.java | 367 ++---
.../java/htsjdk/variant/vcf/VCF3Codec.java | 91 +-
.../htsjdk/variant/vcf/VCFAltHeaderLine.java | 13 +-
.../java/htsjdk/variant/vcf/VCFCodec.java | 107 +-
.../variant/vcf/VCFCompoundHeaderLine.java | 167 +-
.../java/htsjdk/variant/vcf/VCFConstants.java | 69 +-
.../variant/vcf/VCFContigHeaderLine.java | 100 +-
.../java/htsjdk/variant/vcf/VCFEncoder.java | 89 +-
.../htsjdk/variant/vcf/VCFFileReader.java | 27 +-
.../variant/vcf/VCFFilterHeaderLine.java | 54 +-
.../variant/vcf/VCFFormatHeaderLine.java | 52 +-
.../java/htsjdk/variant/vcf/VCFHeader.java | 129 +-
.../htsjdk/variant/vcf/VCFHeaderLine.java | 87 +-
.../variant/vcf/VCFHeaderLineCount.java | 52 +-
.../variant/vcf/VCFHeaderLineTranslator.java | 168 +-
.../htsjdk/variant/vcf/VCFHeaderLineType.java | 52 +-
.../htsjdk/variant/vcf/VCFHeaderVersion.java | 64 +-
.../htsjdk/variant/vcf/VCFIDHeaderLine.java | 46 +-
.../htsjdk/variant/vcf/VCFInfoHeaderLine.java | 58 +-
.../java/htsjdk/variant/vcf/VCFIterator.java | 44 +-
.../variant/vcf/VCFIteratorBuilder.java | 90 +-
.../htsjdk/variant/vcf/VCFMetaHeaderLine.java | 1 -
.../variant/vcf/VCFPedigreeHeaderLine.java | 1 -
.../vcf/VCFPercentEncodedTextTransformer.java | 14 +-
.../java/htsjdk/variant/vcf/VCFReader.java | 7 +-
.../htsjdk/variant/vcf/VCFRecordCodec.java | 75 +-
.../variant/vcf/VCFSampleHeaderLine.java | 1 -
.../variant/vcf/VCFSimpleHeaderLine.java | 102 +-
.../variant/vcf/VCFStandardHeaderLines.java | 204 ++-
.../variant/vcf/VCFTextTransformer.java | 2 -
.../java/htsjdk/variant/vcf/VCFUtils.java | 167 +-
src/test/java/htsjdk/HtsjdkTest.java | 4 +-
.../java/htsjdk/TestClassDependenceTest.java | 48 +-
src/test/java/htsjdk/TestDataProviders.java | 47 +-
.../fasta/HaploidReferenceResolverTest.java | 95 +-
.../hapref/fasta/HtsFASTACodecTest.java | 33 +-
.../reads/bam/BAMDecoderOptionsTest.java | 1 -
.../reads/bam/BAMEncoderOptionsTest.java | 1 -
.../codecs/reads/bam/HtsBAMCodecTest.java | 56 +-
.../reads/bam/HtsBAMDecoderQueryTest.java | 116 +-
.../reads/cram/CRAMDecoderOptionsTest.java | 5 +-
.../reads/cram/CRAMEncoderOptionsTest.java | 5 +-
.../codecs/reads/cram/HtsCRAMCodec21Test.java | 30 +-
.../cram/HtsCRAMCodec30And21QueryTest.java | 1176 ++++++++------
.../codecs/reads/cram/HtsCRAMCodec30Test.java | 39 +-
.../codecs/reads/cram/HtsCRAMCodec31Test.java | 48 +-
.../htsget/HtsgetBAM/HtsgetBAMCodecTest.java | 44 +-
.../codecs/reads/sam/SAMCodecV1_0Test.java | 59 +-
.../codecs/variants/vcf/HtsVCFCodecTest.java | 193 +--
.../htsjdk/beta/io/bundle/BundleJSONTest.java | 449 +++---
.../beta/io/bundle/BundleResourceTest.java | 320 ++--
.../io/bundle/BundleResourceTestData.java | 30 +-
.../htsjdk/beta/io/bundle/BundleTest.java | 41 +-
.../io/bundle/InputStreamResourceTest.java | 24 +-
.../io/bundle/OutputStreamResourceTest.java | 16 +-
.../io/bundle/SeekableStreamResourceTest.java | 31 +-
.../beta/io/bundle/SignatureStreamTest.java | 6 +-
.../htsjdk/beta/plugin/HtsVersionTest.java | 46 +-
.../beta/plugin/reads/ReadsBundleTest.java | 142 +-
.../plugin/reads/ReadsDecoderOptionsTest.java | 7 +-
.../plugin/registry/HtsCodecRegistryTest.java | 46 +-
.../plugin/registry/HtsCodecResolverTest.java | 1099 ++++++-------
.../plugin/registry/HtsReadsCodecTest.java | 52 +-
.../registry/testcodec/HtsTestCodec.java | 36 +-
.../testcodec/HtsTestCodecFormats.java | 7 +-
.../registry/testcodec/HtsTestDecoder.java | 9 +-
.../registry/testcodec/HtsTestEncoder.java | 12 +-
.../plugin/variants/VariantsBundleTest.java | 145 +-
.../java/htsjdk/io/AsyncWriterPoolTest.java | 19 +-
src/test/java/htsjdk/io/HtsPathUnitTest.java | 731 ++++-----
src/test/java/htsjdk/io/IOPathUtilsTest.java | 42 +-
.../samtools/AbstractBAMFileIndexTest.java | 23 +-
.../htsjdk/samtools/BAMCigarOverflowTest.java | 19 +-
.../htsjdk/samtools/BAMFileIndexTest.java | 160 +-
.../htsjdk/samtools/BAMFileReaderTest.java | 106 +-
.../java/htsjdk/samtools/BAMFileSpanTest.java | 111 +-
.../htsjdk/samtools/BAMFileWriterTest.java | 220 ++-
.../samtools/BAMIndexValidatorTest.java | 26 +-
.../htsjdk/samtools/BAMIndexWriterTest.java | 464 +++---
.../java/htsjdk/samtools/BAMIteratorTest.java | 8 +-
.../java/htsjdk/samtools/BAMMergerTest.java | 45 +-
...ryMultipleIntervalsIteratorFilterTest.java | 258 +++-
.../htsjdk/samtools/BAMRemoteFileTest.java | 95 +-
.../htsjdk/samtools/BAMSBIIndexerTest.java | 27 +-
.../htsjdk/samtools/BaiEqualityChecker.java | 42 +-
.../samtools/BamFileIoUtilsUnitTest.java | 60 +-
src/test/java/htsjdk/samtools/BinTest.java | 10 +-
.../samtools/BinningIndexBuilderTest.java | 74 +-
.../CRAMAllEncodingStrategiesTest.java | 177 ++-
.../htsjdk/samtools/CRAMBAIIndexerTest.java | 70 +-
.../htsjdk/samtools/CRAMCRAIIndexerTest.java | 69 +-
.../htsjdk/samtools/CRAMComplianceTest.java | 226 +--
.../CRAMContainerStreamWriterTest.java | 71 +-
.../htsjdk/samtools/CRAMEdgeCasesTest.java | 51 +-
.../htsjdk/samtools/CRAMFileBAIIndexTest.java | 174 +--
.../samtools/CRAMFileCRAIIndexTest.java | 158 +-
.../htsjdk/samtools/CRAMFileReaderTest.java | 23 +-
.../htsjdk/samtools/CRAMFileWriterTest.java | 104 +-
.../samtools/CRAMFileWriterWithIndexTest.java | 52 +-
.../samtools/CRAMIndexPermutationsTests.java | 280 ++--
.../htsjdk/samtools/CRAMIndexQueryTest.java | 1132 ++++++++------
.../htsjdk/samtools/CRAMIndexTestHelper.java | 112 +-
.../htsjdk/samtools/CRAMIteratorTest.java | 5 +-
.../java/htsjdk/samtools/CRAMMergerTest.java | 44 +-
.../samtools/CRAMReferencelessTest.java | 47 +-
.../htsjdk/samtools/CRAMSliceMD5Test.java | 37 +-
.../java/htsjdk/samtools/CRAMTestUtils.java | 55 +-
.../java/htsjdk/samtools/CSIIndexTest.java | 296 ++--
.../samtools/CachingBAMFileIndexTest.java | 60 +-
src/test/java/htsjdk/samtools/ChunkTest.java | 75 +-
.../java/htsjdk/samtools/CigarCodecTest.java | 52 +-
.../samtools/CigarOperatorUnitTest.java | 77 +-
src/test/java/htsjdk/samtools/CigarTest.java | 199 ++-
.../CramContainerHeaderIteratorTest.java | 52 +-
.../samtools/DownsamplingIteratorTests.java | 54 +-
.../DuplicateScoringStrategyTest.java | 17 +-
.../samtools/DuplicateSetIteratorTest.java | 29 +-
.../htsjdk/samtools/GenomicIndexUtilTest.java | 79 +-
.../samtools/HtsgetBAMFileReaderTest.java | 93 +-
.../java/htsjdk/samtools/HtsjdkTestUtils.java | 4 +-
.../java/htsjdk/samtools/LongReadsTest.java | 134 +-
...ngSamRecordIteratorGroupCollisionTest.java | 112 +-
.../MergingSamRecordIteratorTest.java | 43 +-
.../samtools/PathInputResourceTest.java | 70 +-
.../samtools/ProgramRecordChainingTest.java | 1 -
.../htsjdk/samtools/QueryIntervalTest.java | 30 +-
.../SAMBinaryTagAndValueUnitTest.java | 295 ++--
.../htsjdk/samtools/SAMFileHeaderTest.java | 58 +-
.../samtools/SAMFileWriterFactoryTest.java | 85 +-
.../htsjdk/samtools/SAMFileWriterTest.java | 11 +-
.../htsjdk/samtools/SAMIntegerTagTest.java | 183 ++-
.../htsjdk/samtools/SAMProgramRecordTest.java | 3 +-
.../samtools/SAMReadGroupRecordTest.java | 153 +-
.../SAMRecordDuplicateComparatorTest.java | 69 +-
.../SAMRecordQueryHashComparatorTest.java | 3 +-
.../SAMRecordQueryNameComparatorTest.java | 107 +-
.../samtools/SAMRecordSetBuilderTest.java | 44 +-
.../htsjdk/samtools/SAMRecordUnitTest.java | 375 +++--
.../SAMSequenceDictionaryCodecTest.java | 13 +-
.../samtools/SAMSequenceDictionaryTest.java | 73 +-
.../samtools/SAMSequenceRecordTest.java | 140 +-
.../htsjdk/samtools/SAMTextReaderTest.java | 59 +-
.../htsjdk/samtools/SAMTextWriterTest.java | 17 +-
.../java/htsjdk/samtools/SAMUtilsTest.java | 110 +-
.../samtools/SamFileHeaderMergerTest.java | 104 +-
.../java/htsjdk/samtools/SamFilesTest.java | 60 +-
.../htsjdk/samtools/SamFlagFieldTest.java | 9 +-
.../SamHeaderRecordComparatorTest.java | 71 +-
.../java/htsjdk/samtools/SamIndexesTest.java | 58 +-
.../java/htsjdk/samtools/SamPairUtilTest.java | 225 ++-
.../htsjdk/samtools/SamReaderFactoryTest.java | 290 ++--
.../htsjdk/samtools/SamReaderSortTest.java | 47 +-
.../java/htsjdk/samtools/SamReaderTest.java | 157 +-
.../java/htsjdk/samtools/SamSpecIntTest.java | 24 +-
.../java/htsjdk/samtools/SamStreamsTest.java | 117 +-
...quenceNameTruncationAndValidationTest.java | 47 +-
.../htsjdk/samtools/TextTagCodecTest.java | 117 +-
.../htsjdk/samtools/ValidateSamFileTest.java | 560 ++++---
.../htsjdk/samtools/cram/BAIEntryTest.java | 64 +-
.../htsjdk/samtools/cram/CRAIEntryTest.java | 137 +-
.../htsjdk/samtools/cram/CRAIIndexTest.java | 40 +-
.../htsjdk/samtools/cram/CRAIQueryTest.java | 75 +-
.../samtools/cram/CRAMInteropTestUtils.java | 18 +-
.../htsjdk/samtools/cram/CRAMVersionTest.java | 11 +-
.../samtools/cram/CramComparisonTest.java | 7 +-
.../samtools/cram/FQZCompInteropTest.java | 111 +-
.../samtools/cram/LosslessRoundTripTest.java | 147 +-
.../cram/NameTokenizationInteropTest.java | 100 +-
.../htsjdk/samtools/cram/RANSInteropTest.java | 120 +-
.../samtools/cram/RangeInteropTest.java | 68 +-
.../build/CompressionHeaderFactoryTest.java | 64 +-
.../cram/build/ContainerFactoryTest.java | 734 +++++----
.../samtools/cram/build/CramIOTest.java | 29 +-
.../samtools/cram/build/SliceFactoryTest.java | 432 ++++--
.../CodecRoundTripPropertyTest.java | 183 +--
.../compression/CompressionUtilsTest.java | 47 +-
.../cram/compression/CompressorCacheTest.java | 109 +-
.../compression/ExternalCompressionTest.java | 134 +-
.../cram/compression/TrialCompressorTest.java | 38 +-
.../NameTokenisationTest.java | 171 +--
.../cram/compression/range/RangeTest.java | 79 +-
.../cram/compression/rans/RansTest.java | 136 +-
.../cram31/CRAM31ArchiveFidelityTest.java | 7 +-
.../cram/cram31/CRAM31FastFidelityTest.java | 7 +-
.../cram/cram31/CRAM31FidelityTestBase.java | 69 +-
.../cram/cram31/CRAM31NormalFidelityTest.java | 7 +-
.../cram/cram31/CRAM31SmallFidelityTest.java | 7 +-
.../cram/encoding/ByteArrayLenCodecTest.java | 9 +-
.../encoding/ByteArrayLenEncodingTest.java | 77 +-
.../encoding/CramRecordWriterReaderTest.java | 18 +-
.../cram/encoding/DataSeriesReaderTest.java | 20 +-
.../cram/encoding/DataSeriesWriterTest.java | 7 +-
.../cram/encoding/ReadFeaturesTest.java | 9 +-
.../encoding/core/BetaIntegerCodecTest.java | 69 +-
.../core/BetaIntegerEncodingTest.java | 26 +-
.../CanoncialHuffmanByteEncodingTest.java | 4 +-
.../CanonicalHuffmanIntegerEncodingTest.java | 4 +-
.../encoding/core/GammaIntegerCodecTest.java | 73 +-
.../core/GammaIntegerEncodingTest.java | 16 +-
.../cram/encoding/core/HuffmanTest.java | 280 ++--
.../core/SubexponentialIntegerCodecTest.java | 88 +-
.../SubexponentialIntegerEncodingTest.java | 21 +-
.../external/ByteArrayStopCodecTest.java | 3 +-
.../external/ByteArrayStopEncodingTest.java | 16 +-
.../external/ExternalByteArrayCodecTest.java | 3 +-
.../external/ExternalByteCodecTest.java | 5 +-
.../ExternalCodecEquivalenceTest.java | 32 +-
.../external/ExternalEncodingTest.java | 10 +-
.../external/ExternalIntegerCodecTest.java | 5 +-
.../external/ExternalLongCodecTest.java | 5 +-
.../cram/io/CRAMByteReaderWriterTest.java | 32 +-
.../samtools/cram/io/CramIntArrayTest.java | 5 +-
.../htsjdk/samtools/cram/io/CramIntTest.java | 5 +-
.../htsjdk/samtools/cram/io/IOTestCases.java | 99 +-
.../htsjdk/samtools/cram/io/ITF8Test.java | 52 +-
.../cram/io/InputStreamUtilsTest.java | 9 +-
.../htsjdk/samtools/cram/io/LTF8Test.java | 50 +-
.../cram/ref/CRAMReferenceRegionTest.java | 306 ++--
.../samtools/cram/ref/EnaRefServiceTest.java | 8 +-
.../cram/ref/ReferenceContextTest.java | 71 +-
.../cram/ref/ReferenceSourceTest.java | 8 +-
.../spec30/HtsSpecsComplianceTestBase.java | 35 +-
.../cram/spec30/Spec30CompressionTest.java | 9 +-
.../cram/spec30/Spec30ContainerTest.java | 3 +-
.../cram/spec30/Spec30CornerCaseTest.java | 3 +-
.../cram/spec30/Spec30DataLayoutTest.java | 3 +-
.../cram/spec30/Spec30EmbeddedRefTest.java | 3 +-
.../cram/spec30/Spec30FileDefinitionTest.java | 9 +-
.../cram/spec30/Spec30HeaderTest.java | 3 +-
.../samtools/cram/spec30/Spec30IndexTest.java | 24 +-
.../samtools/cram/spec30/Spec30LevelTest.java | 3 +-
.../samtools/cram/spec30/Spec30LossyTest.java | 14 +-
.../cram/spec30/Spec30MappedNoRefTest.java | 3 +-
.../cram/spec30/Spec30MappedWithRefTest.java | 3 +-
.../cram/spec30/Spec30MultiContainerTest.java | 6 +-
.../cram/spec30/Spec30RoundTripBasicTest.java | 107 +-
.../cram/spec30/Spec30RoundTripIndexTest.java | 44 +-
.../Spec30RoundTripTagsAndLayoutTest.java | 117 +-
.../cram/spec30/Spec30SliceTagTest.java | 3 +-
.../samtools/cram/spec30/Spec30TagTest.java | 3 +-
.../cram/spec30/Spec30UnmappedTest.java | 3 +-
.../cram/spec30/Spec31ComplianceTest.java | 32 +-
.../cram/structure/AlignmentContextTest.java | 87 +-
.../cram/structure/AlignmentSpanTest.java | 39 +-
.../structure/CRAMCompressionProfileTest.java | 38 +-
.../structure/CRAMCompressionRecordTest.java | 105 +-
.../cram/structure/CRAMRecordTestHelper.java | 13 +-
.../structure/CRAMStructureTestHelper.java | 163 +-
.../CompressionHeaderEncodingMapTest.java | 48 +-
.../cram/structure/ContainerTest.java | 289 ++--
.../cram/structure/DataSeriesTest.java | 13 +-
.../samtools/cram/structure/ReadTagTest.java | 47 +-
.../structure/SliceBlockReadStreamTest.java | 23 +-
.../structure/SliceBlockWriteStreamTest.java | 15 +-
.../cram/structure/SliceBlocksTest.java | 80 +-
.../samtools/cram/structure/SliceTests.java | 281 ++--
.../cram/structure/StructureTestUtils.java | 25 +-
.../structure/SubstitutionMatrixTest.java | 243 ++-
.../cram/structure/TagKeyCacheTest.java | 34 +-
.../cram/structure/block/BlockTest.java | 43 +-
.../block/CRAMRecordReadFeaturesTest.java | 68 +-
.../samtools/fastq/BasicFastqWriterTest.java | 9 +-
.../samtools/fastq/FastqEncoderTest.java | 39 +-
.../samtools/fastq/FastqRecordTest.java | 35 +-
.../FailsVendorReadQualityFilterTest.java | 129 +-
.../samtools/filter/InsertSizeFilterTest.java | 13 +-
.../samtools/filter/IntervalFilterTest.java | 53 +-
.../filter/IntervalKeepPairFilterTest.java | 26 +-
.../filter/JavascriptSamRecordFilterTest.java | 16 +-
.../filter/MappingQualityFilterTest.java | 8 +-
.../filter/OverclippedReadFilterTest.java | 63 +-
.../samtools/filter/ReadNameFilterTest.java | 30 +-
.../filter/SecondaryAlignmentFilterTest.java | 103 +-
.../SecondaryOrSupplementaryFilterTest.java | 114 +-
.../filter/SolexaNoiseFilterTest.java | 151 +-
.../htsjdk/samtools/filter/TagFilterTest.java | 253 ++-
.../samtools/liftover/LiftOverTest.java | 924 ++++++-----
.../samtools/metrics/MetricBaseTest.java | 50 +-
.../samtools/metrics/MetricsFileTest.java | 115 +-
.../samtools/metrics/StringHeaderTest.java | 5 +-
.../samtools/metrics/VersionHeaderTest.java | 6 +-
.../AbstractFastaSequenceFileTest.java | 27 +-
.../AbstractIndexedFastaSequenceFileTest.java | 384 +++--
.../reference/FakeReferenceSequenceFile.java | 4 +-
.../reference/FastaReferenceWriterTest.java | 503 ++++--
.../reference/FastaSequenceFileTest.java | 12 +-
.../FastaSequenceIndexCreatorTest.java | 28 +-
.../reference/FastaSequenceIndexTest.java | 365 ++---
.../InMemoryReferenceSequenceFile.java | 20 +-
.../ReferenceSequenceFileFactoryTests.java | 172 ++-
.../ReferenceSequenceFileWalkerTest.java | 57 +-
.../reference/ReferenceSequenceTests.java | 36 +-
.../SamLocusAndReferenceIteratorTest.java | 44 +-
.../ByteArraySeekableStreamTest.java | 21 +-
.../SeekableBufferedStreamTest.java | 63 +-
.../seekablestream/SeekableFTPStreamTest.java | 16 +-
.../SeekableFileStreamTest.java | 3 +-
.../SeekableMemoryStreamTest.java | 10 +-
.../SeekablePathStreamTest.java | 5 +-
.../SeekableStreamFactoryTest.java | 78 +-
...eStreamGZIPinputStreamIntegrationTest.java | 28 +-
.../seekablestream/SeekableStreamTest.java | 15 +-
.../htsjdk/samtools/sra/AbstractSRATest.java | 22 +-
.../htsjdk/samtools/sra/SRAAccessionTest.java | 11 +-
.../htsjdk/samtools/sra/SRAIndexTest.java | 119 +-
.../samtools/sra/SRALazyRecordTest.java | 10 +-
.../htsjdk/samtools/sra/SRAQueryTest.java | 45 +-
.../htsjdk/samtools/sra/SRAReferenceTest.java | 44 +-
.../java/htsjdk/samtools/sra/SRATest.java | 405 +++--
.../samtools/util/AbstractLocusInfoTest.java | 9 +-
.../AbstractLocusIteratorTestTemplate.java | 14 +-
.../util/AbstractRecordAndOffsetTest.java | 13 +-
.../AsyncBlockCompressedInputStreamTest.java | 106 +-
.../util/AsyncBufferedIteratorTest.java | 35 +-
.../htsjdk/samtools/util/AsyncWriterTest.java | 6 +-
.../htsjdk/samtools/util/BinaryCodecTest.java | 67 +-
.../BlockCompressedFilePointerUtilTest.java | 101 +-
.../util/BlockCompressedInputStreamTest.java | 215 +--
.../util/BlockCompressedOutputStreamTest.java | 127 +-
.../util/BlockCompressedTerminatorTest.java | 45 +-
.../samtools/util/BufferedLineReaderTest.java | 19 +-
.../samtools/util/CigarElementUnitTest.java | 24 +-
.../htsjdk/samtools/util/CigarUtilTest.java | 634 ++++++--
.../samtools/util/CloseableIteratorTest.java | 13 +-
.../htsjdk/samtools/util/CodeUtilTest.java | 7 +-
.../samtools/util/ComparableTupleTest.java | 44 +-
.../util/CoordSpanInputSteamTest.java | 16 +-
.../htsjdk/samtools/util/DateParserTest.java | 22 +-
.../samtools/util/DiskBackedQueueTest.java | 34 +-
.../samtools/util/EdgeReadIteratorTest.java | 195 +--
.../util/EdgingRecordAndOffsetTest.java | 1 -
.../htsjdk/samtools/util/GZIIndexTest.java | 50 +-
.../htsjdk/samtools/util/GzipCodecTest.java | 27 +-
.../htsjdk/samtools/util/HistogramTest.java | 192 ++-
.../samtools/util/HtsgetRequestUnitTest.java | 121 +-
.../samtools/util/HtsgetResponseUnitTest.java | 36 +-
.../htsjdk/samtools/util/HttpUtilsTest.java | 11 +-
.../java/htsjdk/samtools/util/IOUtilTest.java | 380 ++---
.../samtools/util/IntervalCodecTest.java | 10 +-
.../samtools/util/IntervalListTest.java | 403 +++--
.../samtools/util/IntervalListWriterTest.java | 13 +-
.../htsjdk/samtools/util/IntervalTest.java | 18 +-
.../samtools/util/IntervalTreeMapTest.java | 24 +-
.../samtools/util/IntervalTreeTest.java | 218 +--
.../samtools/util/IntervalUtilTest.java | 24 +-
.../htsjdk/samtools/util/Iso8601DateTest.java | 3 +-
.../java/htsjdk/samtools/util/IupacTest.java | 13 +-
.../samtools/util/LocatableUnitTest.java | 174 ++-
.../java/htsjdk/samtools/util/LogTest.java | 5 +-
.../util/Md5CalculatingOutputStreamTest.java | 15 +-
.../samtools/util/MergingIteratorTest.java | 338 ++--
.../samtools/util/OverlapDetectorTest.java | 205 +--
.../util/PositionalOutputStreamTest.java | 8 +-
.../util/QualityEncodingDetectorTest.java | 68 +-
.../samtools/util/QuietTestWrapper.java | 6 +-
.../util/RelativeIso8601DateTest.java | 17 +-
.../SAMRecordPrefetchingIteratorTest.java | 45 +-
.../samtools/util/SamLocusIteratorTest.java | 168 +-
.../samtools/util/SequenceUtilTest.java | 702 +++++----
.../samtools/util/SnappyLoaderUnitTest.java | 21 +-
.../util/SolexaQualityConverterTest.java | 103 +-
.../samtools/util/SortingCollectionTest.java | 59 +-
.../util/SortingLongCollectionTest.java | 28 +-
.../samtools/util/TrimmingUtilTest.java | 24 +-
.../java/htsjdk/samtools/util/TupleTest.java | 16 +-
.../samtools/util/zip/LibdeflateTest.java | 35 +-
.../SeekableByteChannelFromBuffer.java | 120 +-
.../tribble/AbstractFeatureReaderTest.java | 165 +-
.../htsjdk/tribble/AsciiFeatureCodecTest.java | 5 +-
.../htsjdk/tribble/BinaryFeaturesTest.java | 30 +-
.../htsjdk/tribble/FeatureReaderTest.java | 82 +-
.../IntervalList/IntervalListCodecTest.java | 64 +-
src/test/java/htsjdk/tribble/TestUtils.java | 13 +-
.../TribbleIndexedFeatureReaderTest.java | 54 +-
src/test/java/htsjdk/tribble/TribbleTest.java | 22 +-
.../java/htsjdk/tribble/VCFRedirectCodec.java | 7 +-
.../htsjdk/tribble/annotation/StrandTest.java | 50 +-
.../java/htsjdk/tribble/bed/BEDCodecTest.java | 42 +-
.../htsjdk/tribble/gff/Gff3CodecTest.java | 826 ++++++++--
.../htsjdk/tribble/gff/Gff3FeatureTest.java | 624 +++++++-
.../htsjdk/tribble/gff/Gff3WriterTest.java | 98 +-
.../tribble/index/IndexFactoryTest.java | 99 +-
.../java/htsjdk/tribble/index/IndexTest.java | 63 +-
.../index/interval/IntervalTreeTest.java | 25 +-
.../tribble/index/linear/LinearIndexTest.java | 55 +-
.../tribble/index/tabix/TabixIndexTest.java | 121 +-
.../index/tabix/TbiEqualityChecker.java | 29 +-
.../tribble/readers/AsciiLineReaderTest.java | 38 +-
.../BlockCompressedAsciiLineReaderTest.java | 10 +-
.../readers/LongLineBufferedReaderTest.java | 10 +-
.../readers/PositionalBufferedStreamTest.java | 53 +-
.../htsjdk/tribble/readers/ReaderTest.java | 53 +-
.../SynchronousLineReaderUnitTest.java | 11 +-
.../tribble/readers/TabixReaderTest.java | 72 +-
.../htsjdk/tribble/util/ParsingUtilsTest.java | 93 +-
.../tribble/util/ftp/FTPClientTest.java | 32 +-
.../htsjdk/tribble/util/ftp/FTPUtilsTest.java | 19 +-
.../popgen/HardyWeinbergCalculationTest.java | 34 +-
.../java/htsjdk/utils/ClassFinderTest.java | 16 +-
.../java/htsjdk/utils/SamtoolsTestUtils.java | 34 +-
.../htsjdk/utils/SamtoolsTestUtilsTest.java | 13 +-
src/test/java/htsjdk/utils/TestNGUtils.java | 24 +-
.../java/htsjdk/utils/TestNGUtilsTest.java | 150 +-
.../variant/PrintVariantsExampleTest.java | 73 +-
.../java/htsjdk/variant/VariantBaseTest.java | 143 +-
.../bcf2/BCF2EncoderDecoderUnitTest.java | 291 ++--
.../variant/bcf2/BCF2UtilsUnitTest.java | 171 ++-
.../htsjdk/variant/bcf2/BCF2VersionTest.java | 38 +-
.../variant/bcf2/BCF2WriterUnitTest.java | 149 +-
.../htsjdk/variant/bcf2/BCFCodecTest.java | 15 +-
.../SAMSequenceDictionaryExtractorTest.java | 33 +-
.../variant/utils/VCFHeaderReaderTest.java | 22 +-
.../variantcontext/AlleleUnitTest.java | 126 +-
.../variantcontext/GenotypeBuilderTest.java | 65 +-
.../GenotypeLikelihoodsUnitTest.java | 315 ++--
.../variantcontext/GenotypeUnitTest.java | 189 ++-
.../GenotypesContextUnitTest.java | 100 +-
.../VariantContextBuilderTest.java | 159 +-
.../VariantContextTestProvider.java | 613 ++++----
.../VariantContextUnitTest.java | 765 +++++----
.../VariantJEXLContextUnitTest.java | 192 +--
.../filter/CompoundFilterTest.java | 21 +-
.../FilteringVariantContextIteratorTest.java | 34 +-
.../filter/GenotypeQualityFilterTest.java | 61 +-
.../filter/HeterozygosityFilterTest.java | 106 +-
.../filter/JavascriptVariantFilterTest.java | 14 +-
.../filter/PassingVariantFilterTest.java | 24 +-
.../variantcontext/filter/SnpFilterTest.java | 32 +-
.../AsyncVariantContextWriterUnitTest.java | 90 +-
.../TabixOnTheFlyIndexCreationTest.java | 9 +-
.../writer/VCFWriterUnitTest.java | 146 +-
.../VariantContextWriterBuilderUnitTest.java | 212 ++-
.../writer/VariantContextWritersUnitTest.java | 78 +-
.../variant/vcf/AbstractVCFCodecTest.java | 41 +-
.../variant/vcf/IndexFactoryUnitTest.java | 64 +-
.../variant/vcf/VCFCodec42FeaturesTest.java | 11 +-
.../variant/vcf/VCFCodec43FeaturesTest.java | 109 +-
.../vcf/VCFCompoundHeaderLineUnitTest.java | 47 +-
.../htsjdk/variant/vcf/VCFEncoderTest.java | 149 +-
.../htsjdk/variant/vcf/VCFFileReaderTest.java | 113 +-
.../vcf/VCFHeaderLineTranslatorUnitTest.java | 153 +-
.../variant/vcf/VCFHeaderLineUnitTest.java | 48 +-
.../htsjdk/variant/vcf/VCFHeaderUnitTest.java | 544 ++++---
.../variant/vcf/VCFHeaderVersionTest.java | 39 +-
.../htsjdk/variant/vcf/VCFIteratorTest.java | 112 +-
.../htsjdk/variant/vcf/VCFMergerTest.java | 46 +-
.../vcf/VCFStandardHeaderLinesUnitTest.java | 288 ++--
.../variant/vcf/VCFTextTransformerTest.java | 58 +-
.../java/htsjdk/variant/vcf/VCFUtilsTest.java | 63 +-
1155 files changed, 42518 insertions(+), 35586 deletions(-)
diff --git a/src/main/java/htsjdk/annotations/BetaAPI.java b/src/main/java/htsjdk/annotations/BetaAPI.java
index 1d4e5beaec..cee4709c45 100644
--- a/src/main/java/htsjdk/annotations/BetaAPI.java
+++ b/src/main/java/htsjdk/annotations/BetaAPI.java
@@ -1,13 +1,13 @@
package htsjdk.annotations;
+import static java.lang.annotation.ElementType.*;
+
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
-import static java.lang.annotation.ElementType.*;
-
/**
* Annotation indicating that a package, class, method, or type is release level "BETA", and is not part
* of the stable public API. BETA APIs are published for evaluation, and may be changed or removed without a
@@ -17,5 +17,4 @@
@Retention(RetentionPolicy.SOURCE)
@Inherited
@Documented
-public @interface BetaAPI {
-}
+public @interface BetaAPI {}
diff --git a/src/main/java/htsjdk/annotations/InternalAPI.java b/src/main/java/htsjdk/annotations/InternalAPI.java
index faf0730a01..1eb73861c8 100644
--- a/src/main/java/htsjdk/annotations/InternalAPI.java
+++ b/src/main/java/htsjdk/annotations/InternalAPI.java
@@ -1,13 +1,13 @@
package htsjdk.annotations;
+import static java.lang.annotation.ElementType.*;
+
import java.lang.annotation.Documented;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
-import static java.lang.annotation.ElementType.*;
-
/**
* Annotation indicating that a package, class, method, or type is release level "internal", even if the
* access modifier is "public". {@link InternalAPI} types are intended to be for internal use only, and
@@ -18,5 +18,4 @@
@Retention(RetentionPolicy.SOURCE)
@Inherited
@Documented
-public @interface InternalAPI {
-}
+public @interface InternalAPI {}
diff --git a/src/main/java/htsjdk/beta/codecs/hapref/fasta/FASTACodecV1_0.java b/src/main/java/htsjdk/beta/codecs/hapref/fasta/FASTACodecV1_0.java
index db3d633407..fc7a5f3d3f 100644
--- a/src/main/java/htsjdk/beta/codecs/hapref/fasta/FASTACodecV1_0.java
+++ b/src/main/java/htsjdk/beta/codecs/hapref/fasta/FASTACodecV1_0.java
@@ -1,22 +1,21 @@
package htsjdk.beta.codecs.hapref.fasta;
+import htsjdk.beta.exception.HtsjdkIOException;
+import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.io.bundle.SignatureStream;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.hapref.HaploidReferenceCodec;
import htsjdk.beta.plugin.hapref.HaploidReferenceDecoder;
import htsjdk.beta.plugin.hapref.HaploidReferenceDecoderOptions;
import htsjdk.beta.plugin.hapref.HaploidReferenceEncoder;
-import htsjdk.beta.io.bundle.SignatureStream;
-import htsjdk.beta.exception.HtsjdkIOException;
-import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
import htsjdk.beta.plugin.hapref.HaploidReferenceEncoderOptions;
-import htsjdk.io.IOPath;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.hapref.HaploidReferenceFormats;
+import htsjdk.io.IOPath;
import htsjdk.samtools.util.BlockCompressedStreamConstants;
import htsjdk.samtools.util.FileExtensions;
import htsjdk.samtools.util.IOUtil;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
@@ -38,7 +37,9 @@ public String getFileFormat() {
}
@Override
- public int getSignatureLength() { return BlockCompressedStreamConstants.MAX_COMPRESSED_BLOCK_SIZE; }
+ public int getSignatureLength() {
+ return BlockCompressedStreamConstants.MAX_COMPRESSED_BLOCK_SIZE;
+ }
@Override
public boolean canDecodeSignature(final SignatureStream signatureStream, final String sourceName) {
@@ -46,15 +47,14 @@ public boolean canDecodeSignature(final SignatureStream signatureStream, final S
ValidationUtils.nonNull(sourceName, "sourceName");
try {
- final InputStream wrappedInputStream = IOUtil.isGZIPInputStream(signatureStream) ?
- new GZIPInputStream(signatureStream) :
- signatureStream;
+ final InputStream wrappedInputStream =
+ IOUtil.isGZIPInputStream(signatureStream) ? new GZIPInputStream(signatureStream) : signatureStream;
int ch = wrappedInputStream.read();
if (ch == -1) {
- throw new HtsjdkIOException(
- String.format("Codec %s failed probing signature for resource %s", this.getDisplayName(), sourceName));
+ throw new HtsjdkIOException(String.format(
+ "Codec %s failed probing signature for resource %s", this.getDisplayName(), sourceName));
}
- return ((char) ch) == '>'; // for FASTA, this is all we have to go on...
+ return ((char) ch) == '>'; // for FASTA, this is all we have to go on...
} catch (IOException e) {
throw new HtsjdkIOException(String.format("Failure reading signature from stream for %s", sourceName), e);
}
@@ -63,13 +63,13 @@ public boolean canDecodeSignature(final SignatureStream signatureStream, final S
@Override
public boolean canDecodeURI(final IOPath ioPath) {
ValidationUtils.nonNull(ioPath, "ioPath");
- return FileExtensions.FASTA.stream().anyMatch(ext-> ioPath.hasExtension(ext));
+ return FileExtensions.FASTA.stream().anyMatch(ext -> ioPath.hasExtension(ext));
}
- @Override
+ @Override
public HaploidReferenceDecoder getDecoder(final Bundle inputBundle, final HaploidReferenceDecoderOptions options) {
- ValidationUtils.nonNull(inputBundle, "input bundle");
- ValidationUtils.nonNull(options, "reference encoder options");
+ ValidationUtils.nonNull(inputBundle, "input bundle");
+ ValidationUtils.nonNull(options, "reference encoder options");
return new FASTADecoderV1_0(inputBundle);
}
diff --git a/src/main/java/htsjdk/beta/codecs/hapref/fasta/FASTADecoderV1_0.java b/src/main/java/htsjdk/beta/codecs/hapref/fasta/FASTADecoderV1_0.java
index 45b50eb35e..7aca489388 100644
--- a/src/main/java/htsjdk/beta/codecs/hapref/fasta/FASTADecoderV1_0.java
+++ b/src/main/java/htsjdk/beta/codecs/hapref/fasta/FASTADecoderV1_0.java
@@ -1,20 +1,19 @@
package htsjdk.beta.codecs.hapref.fasta;
+import htsjdk.annotations.InternalAPI;
+import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResource;
import htsjdk.beta.io.bundle.BundleResourceType;
import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.hapref.HaploidReferenceDecoder;
import htsjdk.beta.plugin.hapref.HaploidReferenceFormats;
-import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.samtools.SAMSequenceDictionary;
import htsjdk.samtools.reference.ReferenceSequence;
import htsjdk.samtools.reference.ReferenceSequenceFile;
import htsjdk.samtools.reference.ReferenceSequenceFileFactory;
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.samtools.util.CloseableIterator;
-import htsjdk.annotations.InternalAPI;
-
import java.io.IOException;
/**
@@ -25,7 +24,9 @@ public class FASTADecoderV1_0 implements HaploidReferenceDecoder {
protected Bundle inputBundle;
@Override
- public String getDisplayName() { return displayName; }
+ public String getDisplayName() {
+ return displayName;
+ }
private final ReferenceSequenceFile referenceSequenceFile;
@@ -34,22 +35,23 @@ public FASTADecoderV1_0(final Bundle inputBundle) {
this.displayName = inputBundle.getPrimaryResource().getDisplayName();
final BundleResource referenceResource = inputBundle.getOrThrow(BundleResourceType.CT_HAPLOID_REFERENCE);
if (referenceResource.getIOPath().isPresent()) {
- referenceSequenceFile = ReferenceSequenceFileFactory.getReferenceSequenceFileFromBundle(inputBundle, true, true);
+ referenceSequenceFile =
+ ReferenceSequenceFileFactory.getReferenceSequenceFileFromBundle(inputBundle, true, true);
} else {
- final SeekableStream seekableStream = referenceResource.getSeekableStream().orElseThrow(
- () -> new IllegalArgumentException(
- String.format("The reference resource %s is not able to supply the required seekable stream",
- referenceResource.getDisplayName())));
+ final SeekableStream seekableStream = referenceResource
+ .getSeekableStream()
+ .orElseThrow(() -> new IllegalArgumentException(String.format(
+ "The reference resource %s is not able to supply the required seekable stream",
+ referenceResource.getDisplayName())));
referenceSequenceFile = ReferenceSequenceFileFactory.getReferenceSequenceFile(
- referenceResource.getDisplayName(),
- seekableStream,
- null
- );
+ referenceResource.getDisplayName(), seekableStream, null);
}
}
@Override
- final public String getFileFormat() { return HaploidReferenceFormats.FASTA; }
+ public final String getFileFormat() {
+ return HaploidReferenceFormats.FASTA;
+ }
@Override
public SAMSequenceDictionary getHeader() {
@@ -83,7 +85,7 @@ public ReferenceSequence next() {
public void close() {
try {
referenceSequenceFile.close();
- } catch(final IOException e) {
+ } catch (final IOException e) {
throw new HtsjdkIOException(e);
}
}
@@ -100,7 +102,7 @@ public boolean hasIndex() {
return bundleContainsIndex(inputBundle) && referenceSequenceFile.isIndexed();
}
- //TODO: we need a solution here that doesn't depend on this getter...its necessary because
+ // TODO: we need a solution here that doesn't depend on this getter...its necessary because
// the generic decoder interface exports an iterable, but we need the native
// (indexed by contig) interface implemented on ReferenceSequenceFile to create a ReferenceSource,
// it might be possible to write a CRAMReferenceSource implementation that uses the HtsQuery
@@ -130,5 +132,4 @@ public void close() {
private static boolean bundleContainsIndex(final Bundle inputBundle) {
return inputBundle.get(BundleResourceType.CT_READS_INDEX).isPresent();
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/ReadsCodecUtils.java b/src/main/java/htsjdk/beta/codecs/reads/ReadsCodecUtils.java
index 9e08c9559d..e1d337a3b8 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/ReadsCodecUtils.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/ReadsCodecUtils.java
@@ -1,5 +1,6 @@
package htsjdk.beta.codecs.reads;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.codecs.reads.bam.BAMDecoderOptions;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResource;
@@ -8,8 +9,6 @@
import htsjdk.samtools.SamInputResource;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
-import htsjdk.annotations.InternalAPI;
-
import java.util.Optional;
/**
@@ -18,7 +17,7 @@
* Utilities for use by reads encoder/decoder implementations.
*/
@InternalAPI
-final public class ReadsCodecUtils {
+public final class ReadsCodecUtils {
/**
* InternalAPI
@@ -32,17 +31,10 @@ final public class ReadsCodecUtils {
*/
@InternalAPI
public static SamInputResource bundleToSamInputResource(
- final Bundle inputBundle,
- final ReadsDecoderOptions readsDecoderOptions) {
- final SamInputResource samInputResource = readsToSamInputResource(
- inputBundle,
- BundleResourceType.CT_ALIGNED_READS,
- readsDecoderOptions);
- indexToSamInputResource(
- inputBundle,
- BundleResourceType.CT_READS_INDEX,
- readsDecoderOptions,
- samInputResource);
+ final Bundle inputBundle, final ReadsDecoderOptions readsDecoderOptions) {
+ final SamInputResource samInputResource =
+ readsToSamInputResource(inputBundle, BundleResourceType.CT_ALIGNED_READS, readsDecoderOptions);
+ indexToSamInputResource(inputBundle, BundleResourceType.CT_READS_INDEX, readsDecoderOptions, samInputResource);
return samInputResource;
}
@@ -56,15 +48,14 @@ public static SamInputResource bundleToSamInputResource(
*/
@InternalAPI
public static void readsDecoderOptionsToSamReaderFactory(
- final ReadsDecoderOptions readsDecoderOptions,
- final SamReaderFactory samReaderFactory) {
+ final ReadsDecoderOptions readsDecoderOptions, final SamReaderFactory samReaderFactory) {
samReaderFactory.validationStringency(readsDecoderOptions.getValidationStringency());
samReaderFactory.setOption(SamReaderFactory.Option.EAGERLY_DECODE, readsDecoderOptions.isDecodeEagerly());
- samReaderFactory.setOption(SamReaderFactory.Option.CACHE_FILE_BASED_INDEXES,
- readsDecoderOptions.isFileBasedIndexCached());
+ samReaderFactory.setOption(
+ SamReaderFactory.Option.CACHE_FILE_BASED_INDEXES, readsDecoderOptions.isFileBasedIndexCached());
// note that this option is the revers polarity from SamReaderFactory, so negate it
- samReaderFactory.setOption(SamReaderFactory.Option.DONT_MEMORY_MAP_INDEX,
- !readsDecoderOptions.isMemoryMapIndexes());
+ samReaderFactory.setOption(
+ SamReaderFactory.Option.DONT_MEMORY_MAP_INDEX, !readsDecoderOptions.isMemoryMapIndexes());
}
/**
@@ -95,8 +86,7 @@ public static void assertBundleContainsIndex(final Bundle inputBundle) {
if (!bundleContainsIndex(inputBundle)) {
throw new IllegalArgumentException(String.format(
"To make index queries, an index resource must be provided in the resource bundle: %s",
- inputBundle
- ));
+ inputBundle));
}
}
@@ -121,19 +111,16 @@ public static SamReader getSamReader(
@InternalAPI
public static void bamDecoderOptionsToSamReaderFactory(
- final SamReaderFactory samReaderFactory,
- final BAMDecoderOptions bamDecoderOptions) {
+ final SamReaderFactory samReaderFactory, final BAMDecoderOptions bamDecoderOptions) {
samReaderFactory.inflaterFactory(bamDecoderOptions.getInflaterFactory());
samReaderFactory.setUseAsyncIo(bamDecoderOptions.isAsyncIO());
- samReaderFactory.setOption(SamReaderFactory.Option.VALIDATE_CRC_CHECKSUMS,
- bamDecoderOptions.isValidateCRCChecksums());
+ samReaderFactory.setOption(
+ SamReaderFactory.Option.VALIDATE_CRC_CHECKSUMS, bamDecoderOptions.isValidateCRCChecksums());
}
// convert an input bundle to a SamInputResource
private static SamInputResource readsToSamInputResource(
- final Bundle inputBundle,
- final String contentType,
- final ReadsDecoderOptions readsDecoderOptions) {
+ final Bundle inputBundle, final String contentType, final ReadsDecoderOptions readsDecoderOptions) {
final BundleResource readsInput = inputBundle.getOrThrow(contentType);
if (!readsInput.hasInputType()) {
throw new IllegalArgumentException(String.format(
@@ -143,8 +130,9 @@ private static SamInputResource readsToSamInputResource(
if (readsInput.hasSeekableStream()) {
if (readsInput.getIOPath().isPresent()) {
if (readsDecoderOptions.getReadsChannelTransformer().isPresent()) {
- //TODO: use a local cloud channel wrapper instead of requiring the user to pass a lambda
- return SamInputResource.of(readsInput.getIOPath().get().toPath(),
+ // TODO: use a local cloud channel wrapper instead of requiring the user to pass a lambda
+ return SamInputResource.of(
+ readsInput.getIOPath().get().toPath(),
readsDecoderOptions.getReadsChannelTransformer().get());
} else {
return SamInputResource.of(readsInput.getIOPath().get().toPath());
@@ -168,8 +156,9 @@ private static void indexToSamInputResource(
if (indexResource.getIOPath().isPresent()) {
if (indexResource.getIOPath().isPresent()) {
if (readsDecoderOptions.getIndexChannelTransformer().isPresent()) {
- //TODO: use a local cloud channel wrapper instead of requiring the user to pass a lambda
- SamInputResource.of(indexResource.getIOPath().get().toPath(),
+ // TODO: use a local cloud channel wrapper instead of requiring the user to pass a lambda
+ SamInputResource.of(
+ indexResource.getIOPath().get().toPath(),
readsDecoderOptions.getIndexChannelTransformer().get());
samInputResource.index(indexResource.getIOPath().get().toPath());
} else if (indexResource.getSeekableStream().isPresent()) {
@@ -181,5 +170,4 @@ private static void indexToSamInputResource(
}
}
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/bam/BAMCodec.java b/src/main/java/htsjdk/beta/codecs/reads/bam/BAMCodec.java
index f1e2c4b611..f3e306ace3 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/bam/BAMCodec.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/bam/BAMCodec.java
@@ -1,14 +1,13 @@
package htsjdk.beta.codecs.reads.bam;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.io.bundle.BundleResourceType;
-import htsjdk.io.IOPath;
import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsCodec;
import htsjdk.beta.plugin.reads.ReadsFormats;
+import htsjdk.io.IOPath;
import htsjdk.samtools.util.FileExtensions;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
-
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
@@ -20,17 +19,18 @@
*/
@InternalAPI
public abstract class BAMCodec implements ReadsCodec {
- public static final HtsVersion BAM_DEFAULT_VERSION = new HtsVersion(1, 0,0);
+ public static final HtsVersion BAM_DEFAULT_VERSION = new HtsVersion(1, 0, 0);
private static final Set extensionMap = new HashSet<>(Arrays.asList(FileExtensions.BAM));
@Override
- public String getFileFormat() { return ReadsFormats.BAM; }
+ public String getFileFormat() {
+ return ReadsFormats.BAM;
+ }
@Override
public boolean canDecodeURI(final IOPath ioPath) {
ValidationUtils.nonNull(ioPath, "ioPath");
- return extensionMap.stream().anyMatch(ext-> ioPath.hasExtension(ext));
+ return extensionMap.stream().anyMatch(ext -> ioPath.hasExtension(ext));
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/bam/BAMDecoder.java b/src/main/java/htsjdk/beta/codecs/reads/bam/BAMDecoder.java
index 4190c3b8ba..34c0227ac6 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/bam/BAMDecoder.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/bam/BAMDecoder.java
@@ -1,11 +1,11 @@
package htsjdk.beta.codecs.reads.bam;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.plugin.reads.ReadsDecoder;
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
import htsjdk.beta.plugin.reads.ReadsFormats;
-import htsjdk.beta.plugin.reads.ReadsDecoder;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
/**
@@ -30,19 +30,24 @@ public abstract class BAMDecoder implements ReadsDecoder {
*/
@InternalAPI
public BAMDecoder(final Bundle inputBundle, final ReadsDecoderOptions readsDecoderOptions) {
- ValidationUtils.nonNull(inputBundle,"inputBundle");
+ ValidationUtils.nonNull(inputBundle, "inputBundle");
ValidationUtils.nonNull(readsDecoderOptions, "readsDecoderOptions");
this.inputBundle = inputBundle;
- this.displayName = inputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
+ this.displayName =
+ inputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
this.readsDecoderOptions = readsDecoderOptions;
}
@Override
- final public String getFileFormat() { return ReadsFormats.BAM; }
+ public final String getFileFormat() {
+ return ReadsFormats.BAM;
+ }
@Override
- final public String getDisplayName() { return displayName; }
+ public final String getDisplayName() {
+ return displayName;
+ }
/**
* Get the input {@link Bundle} for this decoder.
diff --git a/src/main/java/htsjdk/beta/codecs/reads/bam/BAMDecoderOptions.java b/src/main/java/htsjdk/beta/codecs/reads/bam/BAMDecoderOptions.java
index 34b6e0307f..df04eb5cbc 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/bam/BAMDecoderOptions.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/bam/BAMDecoderOptions.java
@@ -9,7 +9,7 @@
* Decoder options specific to BAM decoders.
*/
public class BAMDecoderOptions {
- //SAMRecordFactory isn't carried over from SAMReaderFactory as an option, since it doesn't appear to
+ // SAMRecordFactory isn't carried over from SAMReaderFactory as an option, since it doesn't appear to
// actually be used anywhere anymore (??)
//
// includeInSource isn't carried over since it populates SAMRecords with a SamReader, which the plugin
@@ -19,8 +19,8 @@ public class BAMDecoderOptions {
// (all, including splitting) index creation into htsjdk.
private InflaterFactory inflaterFactory = BlockGunzipper.getDefaultInflaterFactory();
- private boolean asyncIO = Defaults.USE_ASYNC_IO_READ_FOR_SAMTOOLS;
- private boolean validateCRCChecksums = false;
+ private boolean asyncIO = Defaults.USE_ASYNC_IO_READ_FOR_SAMTOOLS;
+ private boolean validateCRCChecksums = false;
/**
* Get the {@link InflaterFactory} used for these options. Defaults to
@@ -85,5 +85,4 @@ public BAMDecoderOptions setValidateCRCChecksums(final boolean validateCRCChecks
this.validateCRCChecksums = validateCRCChecksums;
return this;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/bam/BAMEncoder.java b/src/main/java/htsjdk/beta/codecs/reads/bam/BAMEncoder.java
index dc9d5f7010..9b09f1d6d7 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/bam/BAMEncoder.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/bam/BAMEncoder.java
@@ -2,9 +2,9 @@
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.plugin.reads.ReadsEncoder;
import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
import htsjdk.beta.plugin.reads.ReadsFormats;
-import htsjdk.beta.plugin.reads.ReadsEncoder;
import htsjdk.utils.ValidationUtils;
/**
@@ -31,19 +31,24 @@ public abstract class BAMEncoder implements ReadsEncoder {
* @param readsEncoderOptions {@link ReadsEncoderOptions} to use
*/
public BAMEncoder(final Bundle outputBundle, final ReadsEncoderOptions readsEncoderOptions) {
- ValidationUtils.nonNull(outputBundle,"outputBundle");
+ ValidationUtils.nonNull(outputBundle, "outputBundle");
ValidationUtils.nonNull(readsEncoderOptions, "readsEncoderOptions");
this.outputBundle = outputBundle;
this.readsEncoderOptions = readsEncoderOptions;
- this.displayName = outputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
+ this.displayName =
+ outputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
}
@Override
- final public String getFileFormat() { return ReadsFormats.BAM; }
+ public final String getFileFormat() {
+ return ReadsFormats.BAM;
+ }
@Override
- final public String getDisplayName() { return displayName; }
+ public final String getDisplayName() {
+ return displayName;
+ }
/**
* Get the output {@link Bundle} for this encoder.
@@ -62,5 +67,4 @@ public Bundle getOutputBundle() {
public ReadsEncoderOptions getReadsEncoderOptions() {
return readsEncoderOptions;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/bam/BAMEncoderOptions.java b/src/main/java/htsjdk/beta/codecs/reads/bam/BAMEncoderOptions.java
index 30ae57424f..3ceb40bb9d 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/bam/BAMEncoderOptions.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/bam/BAMEncoderOptions.java
@@ -15,13 +15,13 @@
public class BAMEncoderOptions {
public static final int DEAFULT_MAX_RECORDS_IN_RAM = 500000;
- private int outputBufferSize = Defaults.BUFFER_SIZE;
- private boolean asyncIO = Defaults.USE_ASYNC_IO_WRITE_FOR_SAMTOOLS;
- private int asyncOutputBufferSize = AbstractAsyncWriter.DEFAULT_QUEUE_SIZE;
- private IOPath tempDirPath = new HtsPath(IOUtil.getDefaultTmpDirPath().toString());
- private int compressionLevel = BlockCompressedOutputStream.getDefaultCompressionLevel();
- private Integer maxRecordsInRAM = DEAFULT_MAX_RECORDS_IN_RAM;
- private DeflaterFactory deflaterFactory = BlockCompressedOutputStream.getDefaultDeflaterFactory();
+ private int outputBufferSize = Defaults.BUFFER_SIZE;
+ private boolean asyncIO = Defaults.USE_ASYNC_IO_WRITE_FOR_SAMTOOLS;
+ private int asyncOutputBufferSize = AbstractAsyncWriter.DEFAULT_QUEUE_SIZE;
+ private IOPath tempDirPath = new HtsPath(IOUtil.getDefaultTmpDirPath().toString());
+ private int compressionLevel = BlockCompressedOutputStream.getDefaultCompressionLevel();
+ private Integer maxRecordsInRAM = DEAFULT_MAX_RECORDS_IN_RAM;
+ private DeflaterFactory deflaterFactory = BlockCompressedOutputStream.getDefaultDeflaterFactory();
// SAM only ?: private SamFlagField samFlagFieldOutput = SamFlagField.NONE;
/**
@@ -194,5 +194,4 @@ public BAMEncoderOptions setDeflaterFactory(DeflaterFactory deflaterFactory) {
this.deflaterFactory = deflaterFactory;
return this;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMCodecV1_0.java b/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMCodecV1_0.java
index 1f13c92672..18fac5c1e9 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMCodecV1_0.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMCodecV1_0.java
@@ -3,17 +3,16 @@
import htsjdk.beta.codecs.reads.bam.BAMCodec;
import htsjdk.beta.codecs.reads.bam.BAMDecoder;
import htsjdk.beta.codecs.reads.bam.BAMEncoder;
+import htsjdk.beta.exception.HtsjdkIOException;
+import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.SignatureStream;
-import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
-import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
import htsjdk.samtools.SamStreams;
import htsjdk.samtools.util.BlockCompressedStreamConstants;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
/**
@@ -28,7 +27,9 @@ public HtsVersion getVersion() {
}
@Override
- public int getSignatureProbeLength() { return BlockCompressedStreamConstants.MAX_COMPRESSED_BLOCK_SIZE; }
+ public int getSignatureProbeLength() {
+ return BlockCompressedStreamConstants.MAX_COMPRESSED_BLOCK_SIZE;
+ }
@Override
public int getSignatureLength() {
@@ -62,5 +63,4 @@ public BAMEncoder getEncoder(final Bundle outputBundle, final ReadsEncoderOption
public boolean runVersionUpgrade(final HtsVersion sourceCodecVersion, final HtsVersion targetCodecVersion) {
throw new HtsjdkUnsupportedOperationException("Upgrade not yet implemented");
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMDecoderV1_0.java b/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMDecoderV1_0.java
index f802fc0797..e4a1fb275e 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMDecoderV1_0.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMDecoderV1_0.java
@@ -2,14 +2,13 @@
import htsjdk.beta.codecs.reads.ReadsCodecUtils;
import htsjdk.beta.codecs.reads.bam.BAMDecoder;
+import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResourceType;
-import htsjdk.beta.plugin.interval.HtsIntervalUtils;
-import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.interval.HtsInterval;
+import htsjdk.beta.plugin.interval.HtsIntervalUtils;
import htsjdk.beta.plugin.interval.HtsQueryRule;
-
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
import htsjdk.samtools.QueryInterval;
import htsjdk.samtools.SAMFileHeader;
@@ -18,13 +17,12 @@
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.util.CloseableIterator;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
import java.util.List;
import java.util.Optional;
/**
- * BAM v1.0 decoder.
+ * BAM v1.0 decoder.
*/
public class BAMDecoderV1_0 extends BAMDecoder {
private final SamReader samReader;
@@ -78,9 +76,8 @@ public CloseableIterator query(final List intervals, fin
ValidationUtils.nonNull(queryRule, "queryRule");
ReadsCodecUtils.assertBundleContainsIndex(getInputBundle());
- final QueryInterval[] queryIntervals = HtsIntervalUtils.toQueryIntervalArray(
- intervals,
- samFileHeader.getSequenceDictionary());
+ final QueryInterval[] queryIntervals =
+ HtsIntervalUtils.toQueryIntervalArray(intervals, samFileHeader.getSequenceDictionary());
return samReader.query(queryIntervals, queryRule == HtsQueryRule.CONTAINED);
}
@@ -116,5 +113,4 @@ public void close() {
throw new HtsjdkIOException(String.format("Exception closing reader for %s", getInputBundle()), e);
}
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMEncoderV1_0.java b/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMEncoderV1_0.java
index b0fa567229..fd2230250d 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMEncoderV1_0.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/bam/bamV1_0/BAMEncoderV1_0.java
@@ -4,16 +4,15 @@
import htsjdk.beta.codecs.reads.bam.BAMEncoderOptions;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
import htsjdk.beta.io.bundle.Bundle;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.BundleResource;
import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMRecord;
import htsjdk.utils.ValidationUtils;
-
import java.util.Optional;
/**
@@ -50,8 +49,7 @@ public void write(final SAMRecord record) {
ValidationUtils.nonNull(record, "record");
if (samFileWriter == null) {
throw new IllegalStateException(String.format(
- "A SAMFileHeader must be established before records can be written for %s",
- getDisplayName()));
+ "A SAMFileHeader must be established before records can be written for %s", getDisplayName()));
}
samFileWriter.addAlignment(record);
}
@@ -67,11 +65,11 @@ public void close() {
* Propagate BAMEncoderOptions to a SAMFileWriterFactory.
*/
private static void bamEncoderOptionsToSamWriterFactory(
- final BAMEncoderOptions bamEncoderOptions,
- final SAMFileWriterFactory samFileWriterFactory) {
+ final BAMEncoderOptions bamEncoderOptions, final SAMFileWriterFactory samFileWriterFactory) {
samFileWriterFactory.setDeflaterFactory(bamEncoderOptions.getDeflaterFactory());
samFileWriterFactory.setCompressionLevel(bamEncoderOptions.getCompressionLevel());
- samFileWriterFactory.setTempDirectory(bamEncoderOptions.getTemporaryDirectory().toPath().toFile());
+ samFileWriterFactory.setTempDirectory(
+ bamEncoderOptions.getTemporaryDirectory().toPath().toFile());
samFileWriterFactory.setBufferSize(bamEncoderOptions.getOutputBufferSize());
samFileWriterFactory.setUseAsyncIo(bamEncoderOptions.isAsyncIO());
samFileWriterFactory.setAsyncOutputBufferSize(bamEncoderOptions.getAsyncOutputBufferSize());
@@ -79,8 +77,7 @@ private static void bamEncoderOptionsToSamWriterFactory(
}
private SAMFileWriter getBAMFileWriter(
- final ReadsEncoderOptions readsEncoderOptions,
- final SAMFileHeader samFileHeader) {
+ final ReadsEncoderOptions readsEncoderOptions, final SAMFileHeader samFileHeader) {
final BAMEncoderOptions bamEncoderOptions = readsEncoderOptions.getBAMEncoderOptions();
final SAMFileWriterFactory samFileWriterFactory = new SAMFileWriterFactory();
bamEncoderOptionsToSamWriterFactory(bamEncoderOptions, samFileWriterFactory);
@@ -91,7 +88,7 @@ private SAMFileWriter getBAMFileWriter(
final Optional optIndexResource = getOutputBundle().get(BundleResourceType.CT_READS_INDEX);
final Optional optMD5Resource = getOutputBundle().get(BundleResourceType.CT_MD5);
- //TODO: BAMFileWriter currently only supports writing an index to a plain file, so for now
+ // TODO: BAMFileWriter currently only supports writing an index to a plain file, so for now
// throw if an index is requested on any other type
if (optIndexResource.isPresent()) {
final BundleResource indexResource = optIndexResource.get();
@@ -102,25 +99,20 @@ private SAMFileWriter getBAMFileWriter(
}
}
- //TODO: BAMFileWriter currently only supports writing an md5 to a plain file with a name that
+ // TODO: BAMFileWriter currently only supports writing an md5 to a plain file with a name that
// it chooses, so throw if an md5 resource is specified since we can't direct it to the specified
// resource
if (optMD5Resource.isPresent()) {
- throw new HtsjdkUnsupportedOperationException(String.format(
- "Specifying an an MD5 resource name not yet implemented on %s", getDisplayName()));
+ throw new HtsjdkUnsupportedOperationException(
+ String.format("Specifying an an MD5 resource name not yet implemented on %s", getDisplayName()));
}
if (readsResource.getIOPath().isPresent()) {
return samFileWriterFactory.makeBAMWriter(
- samFileHeader,
- preSorted,
- readsResource.getIOPath().get().toPath());
+ samFileHeader, preSorted, readsResource.getIOPath().get().toPath());
} else {
return samFileWriterFactory.makeBAMWriter(
- samFileHeader,
- preSorted,
- readsResource.getOutputStream().get());
+ samFileHeader, preSorted, readsResource.getOutputStream().get());
}
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMCodec.java b/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMCodec.java
index 1e56bf7bc0..2899e69b0e 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMCodec.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMCodec.java
@@ -1,23 +1,22 @@
package htsjdk.beta.codecs.reads.cram;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.codecs.hapref.fasta.FASTADecoderV1_0;
+import htsjdk.beta.exception.HtsjdkException;
import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
-import htsjdk.beta.exception.HtsjdkException;
import htsjdk.beta.io.bundle.BundleResourceType;
import htsjdk.beta.io.bundle.SignatureStream;
-import htsjdk.io.IOPath;
import htsjdk.beta.plugin.HtsVersion;
-import htsjdk.beta.plugin.registry.HtsDefaultRegistry;
import htsjdk.beta.plugin.reads.ReadsCodec;
import htsjdk.beta.plugin.reads.ReadsFormats;
+import htsjdk.beta.plugin.registry.HtsDefaultRegistry;
+import htsjdk.io.IOPath;
import htsjdk.samtools.cram.ref.CRAMReferenceSource;
import htsjdk.samtools.cram.ref.ReferenceSource;
import htsjdk.samtools.reference.ReferenceSequenceFile;
import htsjdk.samtools.util.FileExtensions;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
@@ -33,13 +32,15 @@ public abstract class CRAMCodec implements ReadsCodec {
protected static final Set extensionMap = new HashSet<>(Arrays.asList(FileExtensions.CRAM));
@Override
- public String getFileFormat() { return ReadsFormats.CRAM; }
+ public String getFileFormat() {
+ return ReadsFormats.CRAM;
+ }
@Override
public boolean canDecodeURI(final IOPath ioPath) {
ValidationUtils.nonNull(ioPath, "ioPath");
- return extensionMap.stream().anyMatch(ext-> ioPath.hasExtension(ext));
+ return extensionMap.stream().anyMatch(ext -> ioPath.hasExtension(ext));
}
@Override
@@ -74,7 +75,7 @@ static CRAMReferenceSource getCRAMReferenceSource(final IOPath referencePath) {
throw new HtsjdkException(String.format("Unable to get reference codec for %s", referencePath));
}
- //TODO: we need a solution here doesn't require access to this getter...its necessary because
+ // TODO: we need a solution here doesn't require access to this getter...its necessary because
// the generic decoder interface is an iterable, but we need the native (indexed
// by contig) interface implemented on ReferenceSequenceFile to create a ReferenceSource, so we
// need to cast the decoder to get access to the ReferenceSequenceFile; it might be possible to
@@ -89,5 +90,4 @@ static CRAMReferenceSource getCRAMReferenceSource(final IOPath referencePath) {
* @return the signature string for this codec
*/
protected abstract String getSignatureString();
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMDecoder.java b/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMDecoder.java
index 86136f96f7..c8e2365403 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMDecoder.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMDecoder.java
@@ -1,5 +1,6 @@
package htsjdk.beta.codecs.reads.cram;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.codecs.reads.ReadsCodecUtils;
import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.beta.io.bundle.Bundle;
@@ -7,9 +8,9 @@
import htsjdk.beta.plugin.interval.HtsInterval;
import htsjdk.beta.plugin.interval.HtsIntervalUtils;
import htsjdk.beta.plugin.interval.HtsQueryRule;
+import htsjdk.beta.plugin.reads.ReadsDecoder;
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
import htsjdk.beta.plugin.reads.ReadsFormats;
-import htsjdk.beta.plugin.reads.ReadsDecoder;
import htsjdk.samtools.QueryInterval;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFormatException;
@@ -20,9 +21,7 @@
import htsjdk.samtools.cram.ref.CRAMReferenceSource;
import htsjdk.samtools.cram.ref.ReferenceSource;
import htsjdk.samtools.util.CloseableIterator;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
import java.util.List;
import java.util.Optional;
@@ -57,17 +56,22 @@ public CRAMDecoder(final Bundle inputBundle, final ReadsDecoderOptions readsDeco
this.inputBundle = inputBundle;
this.readsDecoderOptions = readsDecoderOptions;
- this.displayName = inputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
+ this.displayName =
+ inputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
samReader = getSamReaderForCRAM(inputBundle, readsDecoderOptions);
samFileHeader = samReader.getFileHeader();
}
@Override
- final public String getFileFormat() { return ReadsFormats.CRAM; }
+ public final String getFileFormat() {
+ return ReadsFormats.CRAM;
+ }
@Override
- final public String getDisplayName() { return displayName; }
+ public final String getDisplayName() {
+ return displayName;
+ }
@Override
public SAMFileHeader getHeader() {
@@ -84,7 +88,9 @@ public void close() {
}
@Override
- public CloseableIterator iterator() { return getIteratorMonitor(() -> samReader.iterator()); }
+ public CloseableIterator iterator() {
+ return getIteratorMonitor(() -> samReader.iterator());
+ }
@Override
public boolean isQueryable() {
@@ -101,16 +107,16 @@ public CloseableIterator query(final List intervals, fin
ValidationUtils.nonNull(intervals, "intervals");
ValidationUtils.nonNull(queryRule, "queryRule");
- final QueryInterval[] queryIntervals = HtsIntervalUtils.toQueryIntervalArray(
- intervals,
- samFileHeader.getSequenceDictionary());
+ final QueryInterval[] queryIntervals =
+ HtsIntervalUtils.toQueryIntervalArray(intervals, samFileHeader.getSequenceDictionary());
return getIteratorMonitor(() -> samReader.query(queryIntervals, queryRule == HtsQueryRule.CONTAINED));
}
@Override
public CloseableIterator queryStart(final String queryName, final long start) {
ValidationUtils.nonNull(queryName, "queryName");
- return getIteratorMonitor(() -> samReader.queryAlignmentStart(queryName, HtsIntervalUtils.toIntegerSafe(start)));
+ return getIteratorMonitor(
+ () -> samReader.queryAlignmentStart(queryName, HtsIntervalUtils.toIntegerSafe(start)));
}
@Override
@@ -126,27 +132,28 @@ public Optional queryMate(SAMRecord rec) {
ValidationUtils.nonNull(rec, "rec");
if (!rec.getReadPairedFlag()) {
- throw new IllegalArgumentException(String.format("queryMate called for unpaired read on %s.", getDisplayName()));
+ throw new IllegalArgumentException(
+ String.format("queryMate called for unpaired read on %s.", getDisplayName()));
}
if (rec.getFirstOfPairFlag() == rec.getSecondOfPairFlag()) {
- throw new IllegalArgumentException(String.format("SAMRecord must be either first and second of pair, but not both (%s).",
- getDisplayName()));
+ throw new IllegalArgumentException(String.format(
+ "SAMRecord must be either first and second of pair, but not both (%s).", getDisplayName()));
}
final boolean firstOfPair = rec.getFirstOfPairFlag();
// its important that this method closes the iterators it creates, since otherwise the caller
// will never be able to create another iterator after calling this method
try (final CloseableIterator it =
- rec.getMateReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX ?
- queryUnmapped() :
- queryStart(rec.getMateReferenceName(), rec.getMateAlignmentStart())) {
+ rec.getMateReferenceIndex() == SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX
+ ? queryUnmapped()
+ : queryStart(rec.getMateReferenceName(), rec.getMateAlignmentStart())) {
SAMRecord mateRec = null;
while (it.hasNext()) {
final SAMRecord next = it.next();
if (!next.getReadPairedFlag()) {
if (rec.getReadName().equals(next.getReadName())) {
- throw new SAMFormatException(String.format("Paired and unpaired reads with same name: %s (on %s)",
- rec.getReadName(),
- getInputBundle()));
+ throw new SAMFormatException(String.format(
+ "Paired and unpaired reads with same name: %s (on %s)",
+ rec.getReadName(), getInputBundle()));
}
continue;
}
@@ -157,11 +164,9 @@ public Optional queryMate(SAMRecord rec) {
}
if (rec.getReadName().equals(next.getReadName())) {
if (mateRec != null) {
- throw new SAMFormatException(
- String.format("Multiple SAMRecord with read name %s for %s end on %s.",
- rec.getReadName(),
- (firstOfPair ? "second" : "first"),
- getInputBundle()));
+ throw new SAMFormatException(String.format(
+ "Multiple SAMRecord with read name %s for %s end on %s.",
+ rec.getReadName(), (firstOfPair ? "second" : "first"), getInputBundle()));
}
mateRec = next;
}
@@ -190,7 +195,7 @@ public ReadsDecoderOptions getReadsDecoderOptions() {
// TODO: If we've been handed a CRAMReferenceSource from the caller, then we don't want to close it
// when the decoder is closed, but if we create it, then we need to close it.
- //TODO: creation of the source should be separate from the getting of the source, and the result
+ // TODO: creation of the source should be separate from the getting of the source, and the result
// cached, so we don't create multiple reference Sources
@InternalAPI
public static CRAMReferenceSource getCRAMReferenceSource(final CRAMDecoderOptions cramDecoderOptions) {
@@ -199,7 +204,8 @@ public static CRAMReferenceSource getCRAMReferenceSource(final CRAMDecoderOption
if (cramDecoderOptions.getReferenceSource().isPresent()) {
return cramDecoderOptions.getReferenceSource().get();
} else if (cramDecoderOptions.getReferencePath().isPresent()) {
- return CRAMCodec.getCRAMReferenceSource(cramDecoderOptions.getReferencePath().get());
+ return CRAMCodec.getCRAMReferenceSource(
+ cramDecoderOptions.getReferencePath().get());
}
// if none is specified, get the default "lazy" reference source that throws when queried, to allow
// operations that don't require a reference
@@ -220,7 +226,8 @@ private void toggleIteratorExists(final boolean newState) {
"The previous iterator must be closed before starting a new iterator on %s", getDisplayName()));
} else {
// this indicates a problem with this codec
- throw new IllegalStateException(String.format("No outstanding iterator exists for %s", getDisplayName()));
+ throw new IllegalStateException(
+ String.format("No outstanding iterator exists for %s", getDisplayName()));
}
}
// reset the iterator monitor
@@ -244,7 +251,9 @@ public void close() {
}
@Override
- public boolean hasNext() { return wrappedIterator.hasNext(); }
+ public boolean hasNext() {
+ return wrappedIterator.hasNext();
+ }
@Override
public T next() {
@@ -255,8 +264,7 @@ public T next() {
// Propagate all reads decoder options and all bam decoder options to either a SamReaderFactory
// or a SamInputResource, and return the resulting SamReader
private static SamReader getSamReaderForCRAM(
- final Bundle inputBundle,
- final ReadsDecoderOptions readsDecoderOptions) {
+ final Bundle inputBundle, final ReadsDecoderOptions readsDecoderOptions) {
// note that some reads decoder options, such as cloud wrapper values, need to be propagated
// to the samInputResource, not to the SamReaderFactory
final SamInputResource samInputResource =
@@ -269,11 +277,9 @@ private static SamReader getSamReaderForCRAM(
}
private static void cramDecoderOptionsToSamReaderFactory(
- final SamReaderFactory samReaderFactory,
- final CRAMDecoderOptions cramDecoderOptions) {
- //TODO: CRAMFileReader doesn't honor the requested inflater, but it should
- //samReaderFactory.inflaterFactory(cramDecoderOptions.getInflaterFactory());
+ final SamReaderFactory samReaderFactory, final CRAMDecoderOptions cramDecoderOptions) {
+ // TODO: CRAMFileReader doesn't honor the requested inflater, but it should
+ // samReaderFactory.inflaterFactory(cramDecoderOptions.getInflaterFactory());
samReaderFactory.referenceSource(getCRAMReferenceSource(cramDecoderOptions));
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMDecoderOptions.java b/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMDecoderOptions.java
index 798ef70181..b989330a65 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMDecoderOptions.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMDecoderOptions.java
@@ -2,7 +2,6 @@
import htsjdk.io.IOPath;
import htsjdk.samtools.cram.ref.CRAMReferenceSource;
-
import java.util.Optional;
/**
@@ -32,8 +31,8 @@ public Optional getReferenceSource() {
public CRAMDecoderOptions setReferenceSource(final CRAMReferenceSource referenceSource) {
if (referencePath != null) {
throw new IllegalStateException(String.format(
- "Reference source and reference path are mutually exclusive. Reference path already has value %s.",
- referencePath.getRawInputString()));
+ "Reference source and reference path are mutually exclusive. Reference path already has value %s.",
+ referencePath.getRawInputString()));
}
this.referencePath = null;
this.referenceSource = referenceSource;
@@ -67,5 +66,4 @@ public CRAMDecoderOptions setReferencePath(final IOPath referencePath) {
this.referencePath = referencePath;
return this;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMEncoder.java b/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMEncoder.java
index 7a4f6caa58..5e7581fdc2 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMEncoder.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMEncoder.java
@@ -1,21 +1,20 @@
package htsjdk.beta.codecs.reads.cram;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResource;
import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.plugin.reads.ReadsEncoder;
import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
import htsjdk.beta.plugin.reads.ReadsFormats;
-import htsjdk.beta.plugin.reads.ReadsEncoder;
import htsjdk.samtools.CRAMFileWriter;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.cram.ref.CRAMReferenceSource;
import htsjdk.samtools.cram.ref.ReferenceSource;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
-
import java.util.Optional;
/**
@@ -47,14 +46,19 @@ public CRAMEncoder(final Bundle outputBundle, final ReadsEncoderOptions readsEnc
this.outputBundle = outputBundle;
this.readsEncoderOptions = readsEncoderOptions;
- this.displayName = outputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
+ this.displayName =
+ outputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
}
@Override
- final public String getFileFormat() { return ReadsFormats.CRAM; }
+ public final String getFileFormat() {
+ return ReadsFormats.CRAM;
+ }
@Override
- final public String getDisplayName() { return displayName; }
+ public final String getDisplayName() {
+ return displayName;
+ }
@Override
public void setHeader(final SAMFileHeader samFileHeader) {
@@ -116,7 +120,8 @@ public static CRAMReferenceSource getCRAMReferenceSource(final CRAMEncoderOption
if (cramEncoderOptions.getReferenceSource().isPresent()) {
return cramEncoderOptions.getReferenceSource().get();
} else if (cramEncoderOptions.getReferencePath().isPresent()) {
- return CRAMCodec.getCRAMReferenceSource(cramEncoderOptions.getReferencePath().get());
+ return CRAMCodec.getCRAMReferenceSource(
+ cramEncoderOptions.getReferencePath().get());
}
// if none is specified, get the default "lazy" reference source that throws when queried, to allow
@@ -124,7 +129,8 @@ public static CRAMReferenceSource getCRAMReferenceSource(final CRAMEncoderOption
return ReferenceSource.getDefaultCRAMReferenceSource();
}
- private CRAMFileWriter getCRAMWriter(final SAMFileHeader samFileHeader, final ReadsEncoderOptions readsEncoderOptions) {
+ private CRAMFileWriter getCRAMWriter(
+ final SAMFileHeader samFileHeader, final ReadsEncoderOptions readsEncoderOptions) {
// the CRAMFileWriter constructors assume presorted; so if we're presorted, use the CRAMFileWriters
// directly so we can support writing to a stream
if (readsEncoderOptions.isPreSorted()) {
@@ -153,18 +159,19 @@ private CRAMFileWriter getCRAMWriter(final SAMFileHeader samFileHeader, final Re
final Optional optIndexResource = getOutputBundle().get(BundleResourceType.CT_READS_INDEX);
final Optional optMD5Resource = getOutputBundle().get(BundleResourceType.CT_MD5);
- //TODO: SamFileWriterFactory code paths currently only support writing an index to a plain file, so
+ // TODO: SamFileWriterFactory code paths currently only support writing an index to a plain file, so
// for now throw if an index is requested on any other type
if (optIndexResource.isPresent()) {
final BundleResource indexResource = optIndexResource.get();
if (indexResource.getIOPath().isPresent()) {
samFileWriterFactory.setCreateIndex(true);
} else {
- throw new HtsjdkUnsupportedOperationException("Writing a CRAM index to a stream is not yet supported");
+ throw new HtsjdkUnsupportedOperationException(
+ "Writing a CRAM index to a stream is not yet supported");
}
}
- //TODO: CRAMFileWriter currently only supports writing an md5 to a plain file with a name that
+ // TODO: CRAMFileWriter currently only supports writing an md5 to a plain file with a name that
// it chooses, so throw if an md5 resource is specified since we can't direct it to the specified
// resource
if (optMD5Resource.isPresent()) {
@@ -187,5 +194,4 @@ private CRAMFileWriter getCRAMWriter(final SAMFileHeader samFileHeader, final Re
}
}
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMEncoderOptions.java b/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMEncoderOptions.java
index a64bae5c4b..3a7b1d4e30 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMEncoderOptions.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/CRAMEncoderOptions.java
@@ -2,8 +2,6 @@
import htsjdk.io.IOPath;
import htsjdk.samtools.cram.ref.CRAMReferenceSource;
-import htsjdk.utils.ValidationUtils;
-
import java.util.Optional;
/**
@@ -68,5 +66,4 @@ public CRAMEncoderOptions setReferencePath(final IOPath referencePath) {
this.referencePath = referencePath;
return this;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMCodecV2_1.java b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMCodecV2_1.java
index a3b4a8c5ef..a53c3faa6a 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMCodecV2_1.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMCodecV2_1.java
@@ -3,8 +3,8 @@
import htsjdk.beta.codecs.reads.cram.CRAMCodec;
import htsjdk.beta.codecs.reads.cram.CRAMDecoder;
import htsjdk.beta.codecs.reads.cram.CRAMEncoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
import htsjdk.samtools.cram.structure.CramHeader;
@@ -44,6 +44,7 @@ public CRAMEncoder getEncoder(final Bundle outputBundle, final ReadsEncoderOptio
}
@Override
- protected String getSignatureString() { return CRAM_MAGIC_2_1; }
-
+ protected String getSignatureString() {
+ return CRAM_MAGIC_2_1;
+ }
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMDecoderV2_1.java b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMDecoderV2_1.java
index c91d381208..2b29ff3b32 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMDecoderV2_1.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMDecoderV2_1.java
@@ -1,9 +1,9 @@
package htsjdk.beta.codecs.reads.cram.cramV2_1;
import htsjdk.beta.codecs.reads.cram.CRAMDecoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
/**
@@ -27,5 +27,4 @@ public CRAMDecoderV2_1(final Bundle bundle, final ReadsDecoderOptions readsDecod
public HtsVersion getVersion() {
return CRAMCodecV2_1.VERSION_2_1;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMEncoderV2_1.java b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMEncoderV2_1.java
index bae7c8a87b..57c57c8b2c 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMEncoderV2_1.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV2_1/CRAMEncoderV2_1.java
@@ -1,9 +1,9 @@
package htsjdk.beta.codecs.reads.cram.cramV2_1;
import htsjdk.beta.codecs.reads.cram.CRAMEncoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
/**
@@ -27,5 +27,4 @@ public CRAMEncoderV2_1(final Bundle outputBundle, final ReadsEncoderOptions read
public HtsVersion getVersion() {
return CRAMCodecV2_1.VERSION_2_1;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMCodecV3_0.java b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMCodecV3_0.java
index bcb4fba356..d907cdb668 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMCodecV3_0.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMCodecV3_0.java
@@ -3,14 +3,13 @@
import htsjdk.beta.codecs.reads.cram.CRAMCodec;
import htsjdk.beta.codecs.reads.cram.CRAMDecoder;
import htsjdk.beta.codecs.reads.cram.CRAMEncoder;
+import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.SignatureStream;
-import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
import htsjdk.samtools.cram.structure.CramHeader;
-
import java.io.IOException;
import java.util.Arrays;
@@ -56,6 +55,7 @@ public CRAMEncoder getEncoder(final Bundle outputBundle, final ReadsEncoderOptio
}
@Override
- protected String getSignatureString() { return CRAM_MAGIC_3_0; }
-
+ protected String getSignatureString() {
+ return CRAM_MAGIC_3_0;
+ }
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMDecoderV3_0.java b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMDecoderV3_0.java
index ff86467844..ebc57bce3a 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMDecoderV3_0.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMDecoderV3_0.java
@@ -27,5 +27,4 @@ public CRAMDecoderV3_0(final Bundle bundle, final ReadsDecoderOptions readsDecod
public HtsVersion getVersion() {
return CRAMCodecV3_0.VERSION_3_0;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMEncoderV3_0.java b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMEncoderV3_0.java
index 19dfade893..cbb6639ddd 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMEncoderV3_0.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_0/CRAMEncoderV3_0.java
@@ -27,5 +27,4 @@ public CRAMEncoderV3_0(final Bundle outputBundle, final ReadsEncoderOptions read
public HtsVersion getVersion() {
return CRAMCodecV3_0.VERSION_3_0;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMCodecV3_1.java b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMCodecV3_1.java
index 5f0606d069..e221188015 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMCodecV3_1.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMCodecV3_1.java
@@ -10,7 +10,6 @@
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
import htsjdk.samtools.cram.structure.CramHeader;
-
import java.io.IOException;
import java.util.Arrays;
@@ -56,6 +55,7 @@ public CRAMEncoder getEncoder(final Bundle outputBundle, final ReadsEncoderOptio
}
@Override
- protected String getSignatureString() { return CRAM_MAGIC_3_1; }
-
+ protected String getSignatureString() {
+ return CRAM_MAGIC_3_1;
+ }
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMDecoderV3_1.java b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMDecoderV3_1.java
index ccfd90a141..895589dab5 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMDecoderV3_1.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMDecoderV3_1.java
@@ -27,5 +27,4 @@ public CRAMDecoderV3_1(final Bundle bundle, final ReadsDecoderOptions readsDecod
public HtsVersion getVersion() {
return CRAMCodecV3_1.VERSION_3_1;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMEncoderV3_1.java b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMEncoderV3_1.java
index 4ae82e91e1..0d2618fc2e 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMEncoderV3_1.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/cram/cramV3_1/CRAMEncoderV3_1.java
@@ -5,7 +5,6 @@
import htsjdk.beta.io.bundle.BundleResourceType;
import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
-import htsjdk.samtools.cram.CRAMException;
/**
* CRAM v3.1 encoder.
@@ -28,5 +27,4 @@ public CRAMEncoderV3_1(final Bundle outputBundle, final ReadsEncoderOptions read
public HtsVersion getVersion() {
return CRAMCodecV3_1.VERSION_3_1;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/htsget/HtsgetBAMCodec.java b/src/main/java/htsjdk/beta/codecs/reads/htsget/HtsgetBAMCodec.java
index c8adccbf7a..f2934f1579 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/htsget/HtsgetBAMCodec.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/htsget/HtsgetBAMCodec.java
@@ -10,12 +10,10 @@
import htsjdk.samtools.util.FileExtensions;
import htsjdk.samtools.util.htsget.HtsgetFormat;
import htsjdk.samtools.util.htsget.HtsgetRequest;
-
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
-
/**
* Base class for concrete implementations of reads codecs that handle
* {@link BundleResourceType#FMT_READS_HTSGET_BAM} codecs.
@@ -31,10 +29,14 @@ public abstract class HtsgetBAMCodec implements ReadsCodec {
/**
* The HtsGet protocol doesn't seem to have a version number ?
*/
- public HtsVersion getVersion() { return HTSGET_VERSION; }
+ public HtsVersion getVersion() {
+ return HTSGET_VERSION;
+ }
@Override
- public String getFileFormat() { return ReadsFormats.HTSGET_BAM; }
+ public String getFileFormat() {
+ return ReadsFormats.HTSGET_BAM;
+ }
@Override
public int getSignatureLength() {
@@ -48,25 +50,26 @@ public boolean ownsURI(final IOPath ioPath) {
private boolean matchesScheme(final IOPath ioPath) {
final String scheme = ioPath.getScheme();
- return scheme.equals(HtsgetBAMFileReader.HTSGET_SCHEME) ||
- scheme.equals("https") ||
- scheme.equals("http");
+ return scheme.equals(HtsgetBAMFileReader.HTSGET_SCHEME) || scheme.equals("https") || scheme.equals("http");
}
public boolean handlesURI(final IOPath ioPath) {
- final boolean hasExtension = extensionMap.stream().anyMatch(ext-> ioPath.hasExtension(ext));
+ final boolean hasExtension = extensionMap.stream().anyMatch(ext -> ioPath.hasExtension(ext));
final boolean hasScheme = matchesScheme(ioPath);
- //TODO: does this check for "/reads/" at the start of the path ? should it ?
+ // TODO: does this check for "/reads/" at the start of the path ? should it ?
final HtsgetRequest htsgetRequest = new HtsgetRequest(ioPath.getURI());
// no format == default == BAM
- final boolean matchesRequestType = htsgetRequest.getFormat() == null || htsgetRequest.getFormat() == HtsgetFormat.BAM;
+ final boolean matchesRequestType =
+ htsgetRequest.getFormat() == null || htsgetRequest.getFormat() == HtsgetFormat.BAM;
return hasExtension && hasScheme && matchesRequestType;
}
@Override
- public boolean canDecodeURI(final IOPath ioPath) { return handlesURI(ioPath); }
+ public boolean canDecodeURI(final IOPath ioPath) {
+ return handlesURI(ioPath);
+ }
@Override
public boolean canDecodeSignature(final SignatureStream probingInputStream, final String sourceName) {
@@ -74,11 +77,13 @@ public boolean canDecodeSignature(final SignatureStream probingInputStream, fina
}
boolean isQueryable() {
- //is this correct ??
+ // is this correct ??
return true;
}
- boolean hasIndex() { return false; }
+ boolean hasIndex() {
+ return false;
+ }
@Override
public boolean runVersionUpgrade(final HtsVersion sourceCodecVersion, final HtsVersion targetCodecVersion) {
diff --git a/src/main/java/htsjdk/beta/codecs/reads/htsget/HtsgetBAMDecoder.java b/src/main/java/htsjdk/beta/codecs/reads/htsget/HtsgetBAMDecoder.java
index 59bc35e6a1..ebb71992f9 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/htsget/HtsgetBAMDecoder.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/htsget/HtsgetBAMDecoder.java
@@ -19,11 +19,14 @@ public abstract class HtsgetBAMDecoder implements ReadsDecoder {
public HtsgetBAMDecoder(final Bundle inputBundle, final ReadsDecoderOptions readsDecoderOptions) {
this.inputBundle = inputBundle;
this.readsDecoderOptions = readsDecoderOptions;
- this.displayName = inputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
+ this.displayName =
+ inputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
}
@Override
- public String getFileFormat() { return ReadsFormats.HTSGET_BAM; }
+ public String getFileFormat() {
+ return ReadsFormats.HTSGET_BAM;
+ }
@Override
public HtsVersion getVersion() {
@@ -31,7 +34,9 @@ public HtsVersion getVersion() {
}
@Override
- final public String getDisplayName() { return displayName; }
+ public final String getDisplayName() {
+ return displayName;
+ }
/**
* Get the input {@link Bundle} for this decoder.
diff --git a/src/main/java/htsjdk/beta/codecs/reads/htsget/htsgetBAMV1_2/HtsgetBAMCodecV1_2.java b/src/main/java/htsjdk/beta/codecs/reads/htsget/htsgetBAMV1_2/HtsgetBAMCodecV1_2.java
index 2a870beab7..4560d9c8ee 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/htsget/htsgetBAMV1_2/HtsgetBAMCodecV1_2.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/htsget/htsgetBAMV1_2/HtsgetBAMCodecV1_2.java
@@ -2,15 +2,14 @@
import htsjdk.beta.codecs.reads.htsget.HtsgetBAMCodec;
import htsjdk.beta.codecs.reads.htsget.HtsgetBAMDecoder;
-import htsjdk.beta.plugin.HtsEncoder;
-import htsjdk.beta.plugin.HtsRecord;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResource;
import htsjdk.beta.io.bundle.BundleResourceType;
-import htsjdk.io.IOPath;
-import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
+import htsjdk.beta.plugin.HtsEncoder;
+import htsjdk.beta.plugin.HtsRecord;
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
-
+import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
+import htsjdk.io.IOPath;
import java.util.Optional;
/**
@@ -19,8 +18,7 @@
public class HtsgetBAMCodecV1_2 extends HtsgetBAMCodec {
@Override
- public HtsgetBAMDecoder getDecoder(final Bundle inputBundle,
- final ReadsDecoderOptions decodeOptions) {
+ public HtsgetBAMDecoder getDecoder(final Bundle inputBundle, final ReadsDecoderOptions decodeOptions) {
final BundleResource readsResource = inputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS);
final Optional inputPath = readsResource.getIOPath();
if (!inputPath.isPresent()) {
@@ -33,5 +31,4 @@ public HtsgetBAMDecoder getDecoder(final Bundle inputBundle,
public HtsEncoder, ? extends HtsRecord> getEncoder(Bundle outputBundle, ReadsEncoderOptions encodeOptions) {
throw new IllegalArgumentException("Htsget is read only - no Htsget BAM encoder component is available.");
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/htsget/htsgetBAMV1_2/HtsgetBAMDecoderV1_2.java b/src/main/java/htsjdk/beta/codecs/reads/htsget/htsgetBAMV1_2/HtsgetBAMDecoderV1_2.java
index e3593ea5f1..3bb51eff7a 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/htsget/htsgetBAMV1_2/HtsgetBAMDecoderV1_2.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/htsget/htsgetBAMV1_2/HtsgetBAMDecoderV1_2.java
@@ -1,6 +1,8 @@
package htsjdk.beta.codecs.reads.htsget.htsgetBAMV1_2;
import htsjdk.beta.codecs.reads.htsget.HtsgetBAMDecoder;
+import htsjdk.beta.exception.HtsjdkIOException;
+import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResource;
import htsjdk.beta.io.bundle.BundleResourceType;
@@ -8,15 +10,12 @@
import htsjdk.beta.plugin.interval.HtsIntervalUtils;
import htsjdk.beta.plugin.interval.HtsQueryRule;
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
-import htsjdk.beta.exception.HtsjdkIOException;
-import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
import htsjdk.samtools.DefaultSAMRecordFactory;
import htsjdk.samtools.HtsgetBAMFileReader;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.ValidationStringency;
import htsjdk.samtools.util.CloseableIterator;
-
import java.io.IOException;
import java.util.List;
import java.util.Optional;
@@ -45,7 +44,10 @@ public HtsgetBAMDecoderV1_2(final Bundle inputBundle, final ReadsDecoderOptions
false);
} catch (IOException e) {
throw new HtsjdkIOException(
- String.format("Failure opening Htsget reader on %s", readsResource.getIOPath().get()), e);
+ String.format(
+ "Failure opening Htsget reader on %s",
+ readsResource.getIOPath().get()),
+ e);
}
}
@@ -84,8 +86,7 @@ public CloseableIterator query(final String queryString) {
@Override
public CloseableIterator query(final List intervals, final HtsQueryRule queryRule) {
return htsgetReader.query(
- HtsIntervalUtils.toLocatableList(intervals),
- (queryRule == HtsQueryRule.CONTAINED) == true);
+ HtsIntervalUtils.toLocatableList(intervals), (queryRule == HtsQueryRule.CONTAINED) == true);
}
@Override
@@ -100,7 +101,7 @@ public CloseableIterator queryUnmapped() {
@Override
public Optional queryMate(final SAMRecord rec) {
- //reader doesn't support this
+ // reader doesn't support this
throw new HtsjdkUnsupportedOperationException("queryMate not implemented for htsget BAM reader");
}
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/sam/SAMCodec.java b/src/main/java/htsjdk/beta/codecs/reads/sam/SAMCodec.java
index 7e88ddac2b..580c5d9a47 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/sam/SAMCodec.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/sam/SAMCodec.java
@@ -1,14 +1,13 @@
package htsjdk.beta.codecs.reads.sam;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.beta.io.bundle.BundleResourceType;
import htsjdk.beta.io.bundle.SignatureStream;
import htsjdk.beta.plugin.reads.ReadsCodec;
import htsjdk.beta.plugin.reads.ReadsFormats;
import htsjdk.io.IOPath;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
import java.util.Arrays;
@@ -23,7 +22,9 @@ public abstract class SAMCodec implements ReadsCodec {
private static String SAM_EXTENSION = ".sam";
@Override
- public String getFileFormat() { return ReadsFormats.SAM; }
+ public String getFileFormat() {
+ return ReadsFormats.SAM;
+ }
@Override
public String getDisplayName() {
@@ -31,7 +32,9 @@ public String getDisplayName() {
}
@Override
- public boolean ownsURI(IOPath ioPath) { return false; }
+ public boolean ownsURI(IOPath ioPath) {
+ return false;
+ }
@Override
public boolean canDecodeURI(IOPath ioPath) {
@@ -53,11 +56,12 @@ public boolean canDecodeSignature(final SignatureStream probingInputStream, fina
}
@Override
- public int getSignatureProbeLength() { return SAM_HEADER_SENTINEL.length(); }
+ public int getSignatureProbeLength() {
+ return SAM_HEADER_SENTINEL.length();
+ }
@Override
public int getSignatureLength() {
return SAM_HEADER_SENTINEL.length();
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/sam/SAMDecoder.java b/src/main/java/htsjdk/beta/codecs/reads/sam/SAMDecoder.java
index 32aca0067c..411de1f397 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/sam/SAMDecoder.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/sam/SAMDecoder.java
@@ -1,11 +1,11 @@
package htsjdk.beta.codecs.reads.sam;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResourceType;
import htsjdk.beta.plugin.reads.ReadsDecoder;
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
import htsjdk.beta.plugin.reads.ReadsFormats;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
/**
@@ -30,18 +30,23 @@ public abstract class SAMDecoder implements ReadsDecoder {
*/
@InternalAPI
public SAMDecoder(final Bundle inputBundle, final ReadsDecoderOptions readsDecoderOptions) {
- ValidationUtils.nonNull(inputBundle,"inputBundle");
+ ValidationUtils.nonNull(inputBundle, "inputBundle");
ValidationUtils.nonNull(readsDecoderOptions, "readsDecoderOptions");
this.inputBundle = inputBundle;
- this.displayName = inputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
+ this.displayName =
+ inputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
this.readsDecoderOptions = readsDecoderOptions;
}
@Override
- final public String getFileFormat() { return ReadsFormats.SAM; }
+ public final String getFileFormat() {
+ return ReadsFormats.SAM;
+ }
@Override
- final public String getDisplayName() { return displayName; }
+ public final String getDisplayName() {
+ return displayName;
+ }
/**
* Get the input {@link Bundle} for this decoder.
diff --git a/src/main/java/htsjdk/beta/codecs/reads/sam/SAMEncoder.java b/src/main/java/htsjdk/beta/codecs/reads/sam/SAMEncoder.java
index 2eda3fcf69..d0bea8bc59 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/sam/SAMEncoder.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/sam/SAMEncoder.java
@@ -32,14 +32,19 @@ public abstract class SAMEncoder implements ReadsEncoder {
public SAMEncoder(final Bundle outputBundle, final ReadsEncoderOptions readsEncoderOptions) {
this.outputBundle = outputBundle;
this.readsEncoderOptions = readsEncoderOptions;
- this.displayName = outputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
+ this.displayName =
+ outputBundle.getOrThrow(BundleResourceType.CT_ALIGNED_READS).getDisplayName();
}
@Override
- final public String getFileFormat() { return ReadsFormats.SAM; }
+ public final String getFileFormat() {
+ return ReadsFormats.SAM;
+ }
@Override
- final public String getDisplayName() { return displayName; }
+ public final String getDisplayName() {
+ return displayName;
+ }
/**
* Get the output {@link Bundle} for this encoder.
@@ -58,5 +63,4 @@ public Bundle getOutputBundle() {
public ReadsEncoderOptions getReadsEncoderOptions() {
return readsEncoderOptions;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMCodecV1_0.java b/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMCodecV1_0.java
index e858734f66..5ef9849858 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMCodecV1_0.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMCodecV1_0.java
@@ -4,8 +4,8 @@
import htsjdk.beta.codecs.reads.sam.SAMDecoder;
import htsjdk.beta.codecs.reads.sam.SAMEncoder;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
@@ -16,7 +16,9 @@ public class SAMCodecV1_0 extends SAMCodec {
public static final HtsVersion VERSION_1 = new HtsVersion(1, 0, 0);
@Override
- public HtsVersion getVersion() { return VERSION_1; }
+ public HtsVersion getVersion() {
+ return VERSION_1;
+ }
@Override
public SAMDecoder getDecoder(final Bundle inputBundle, final ReadsDecoderOptions decoderOptions) {
@@ -32,5 +34,4 @@ public SAMEncoder getEncoder(final Bundle outputBundle, final ReadsEncoderOption
public boolean runVersionUpgrade(final HtsVersion sourceCodecVersion, final HtsVersion targetCodecVersion) {
throw new HtsjdkUnsupportedOperationException("Version upgrade not yet implemented");
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMDecoderV1_0.java b/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMDecoderV1_0.java
index 9fad68240b..e87e3e9d74 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMDecoderV1_0.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMDecoderV1_0.java
@@ -3,16 +3,15 @@
import htsjdk.beta.codecs.reads.ReadsCodecUtils;
import htsjdk.beta.codecs.reads.sam.SAMDecoder;
import htsjdk.beta.exception.HtsjdkIOException;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsDecoderOptions;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.util.CloseableIterator;
-
import java.io.IOException;
import java.util.Optional;
@@ -56,7 +55,9 @@ public CloseableIterator iterator() {
}
@Override
- public boolean isQueryable() { return false; }
+ public boolean isQueryable() {
+ return false;
+ }
@Override
public boolean hasIndex() {
diff --git a/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMEncoderV1_0.java b/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMEncoderV1_0.java
index 0274a49d54..4b1f4e231e 100644
--- a/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMEncoderV1_0.java
+++ b/src/main/java/htsjdk/beta/codecs/reads/sam/samV1_0/SAMEncoderV1_0.java
@@ -1,18 +1,17 @@
package htsjdk.beta.codecs.reads.sam.samV1_0;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.codecs.reads.sam.SAMEncoder;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResource;
import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsEncoderOptions;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMRecord;
-import htsjdk.annotations.InternalAPI;
-
import java.util.Optional;
/**
@@ -48,8 +47,7 @@ public void setHeader(final SAMFileHeader samFileHeader) {
public void write(final SAMRecord record) {
if (samFileWriter == null) {
throw new IllegalStateException(String.format(
- "A SAMFileHeader must be established before a SAM writer can be established %s",
- getDisplayName()));
+ "A SAMFileHeader must be established before a SAM writer can be established %s", getDisplayName()));
}
samFileWriter.addAlignment(record);
}
@@ -62,8 +60,7 @@ public void close() {
}
private SAMFileWriter getSAMFileWriter(
- final ReadsEncoderOptions readsEncoderOptions,
- final SAMFileHeader samFileHeader) {
+ final ReadsEncoderOptions readsEncoderOptions, final SAMFileHeader samFileHeader) {
final SAMFileWriterFactory samFileWriterFactory = new SAMFileWriterFactory();
final boolean preSorted = readsEncoderOptions.isPreSorted();
@@ -72,7 +69,7 @@ private SAMFileWriter getSAMFileWriter(
final Optional optIndexResource = getOutputBundle().get(BundleResourceType.CT_READS_INDEX);
final Optional optMD5Resource = getOutputBundle().get(BundleResourceType.CT_MD5);
- //TODO: BAMFileWriter currently only supports writing an index to a plain file, so for now
+ // TODO: BAMFileWriter currently only supports writing an index to a plain file, so for now
// throw if an index is requested on any other type
if (optIndexResource.isPresent()) {
final BundleResource indexResource = optIndexResource.get();
@@ -83,24 +80,20 @@ private SAMFileWriter getSAMFileWriter(
}
}
- //TODO: BAMFileWriter currently only supports writing an md5 to a plain file with a name that
+ // TODO: BAMFileWriter currently only supports writing an md5 to a plain file with a name that
// it chooses, so throw if an md5 resource is specified since we can't direct it to the specified
// resource
if (optMD5Resource.isPresent()) {
- throw new HtsjdkUnsupportedOperationException(String.format(
- "Specifying an an MD5 resource name not yet implemented on %s", getDisplayName()));
+ throw new HtsjdkUnsupportedOperationException(
+ String.format("Specifying an an MD5 resource name not yet implemented on %s", getDisplayName()));
}
if (readsResource.getIOPath().isPresent()) {
return samFileWriterFactory.makeSAMWriter(
- samFileHeader,
- preSorted,
- readsResource.getIOPath().get().toPath());
+ samFileHeader, preSorted, readsResource.getIOPath().get().toPath());
} else {
return samFileWriterFactory.makeSAMWriter(
- samFileHeader,
- preSorted,
- readsResource.getOutputStream().get());
+ samFileHeader, preSorted, readsResource.getOutputStream().get());
}
}
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFCodec.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFCodec.java
index c18a60b34e..adc17f8689 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFCodec.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFCodec.java
@@ -1,17 +1,16 @@
package htsjdk.beta.codecs.variants.vcf;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.exception.HtsjdkIOException;
-import htsjdk.beta.plugin.HtsContentType;
import htsjdk.beta.io.bundle.SignatureStream;
-import htsjdk.io.IOPath;
+import htsjdk.beta.plugin.HtsContentType;
import htsjdk.beta.plugin.variants.VariantsCodec;
import htsjdk.beta.plugin.variants.VariantsFormats;
+import htsjdk.io.IOPath;
import htsjdk.samtools.util.BlockCompressedStreamConstants;
import htsjdk.samtools.util.FileExtensions;
import htsjdk.samtools.util.IOUtil;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
@@ -29,6 +28,7 @@ public abstract class VCFCodec implements VariantsCodec {
// FileExtensions.VCF_LIST includes BCF, which we don't want included here
private static final Set extensionMap = new HashSet() {
private static final long serialVersionUID = 1L;
+
{
add(FileExtensions.VCF);
add(FileExtensions.COMPRESSED_VCF);
@@ -37,13 +37,15 @@ public abstract class VCFCodec implements VariantsCodec {
};
@Override
- public String getFileFormat() { return VariantsFormats.VCF; }
+ public String getFileFormat() {
+ return VariantsFormats.VCF;
+ }
@Override
public boolean canDecodeURI(final IOPath ioPath) {
ValidationUtils.nonNull(ioPath, "ioPath");
- return extensionMap.stream().anyMatch(ext-> ioPath.hasExtension(ext));
+ return extensionMap.stream().anyMatch(ext -> ioPath.hasExtension(ext));
}
@Override
@@ -52,7 +54,9 @@ public int getSignatureLength() {
}
@Override
- public int getSignatureProbeLength() { return BlockCompressedStreamConstants.MAX_COMPRESSED_BLOCK_SIZE; }
+ public int getSignatureProbeLength() {
+ return BlockCompressedStreamConstants.MAX_COMPRESSED_BLOCK_SIZE;
+ }
@Override
public boolean canDecodeSignature(final SignatureStream probingInputStream, final String sourceName) {
@@ -61,9 +65,9 @@ public boolean canDecodeSignature(final SignatureStream probingInputStream, fina
final byte[] signatureBytes = new byte[getSignatureLength()];
try {
- final InputStream wrappedInputStream = IOUtil.isGZIPInputStream(probingInputStream) ?
- new GZIPInputStream(probingInputStream) :
- probingInputStream;
+ final InputStream wrappedInputStream = IOUtil.isGZIPInputStream(probingInputStream)
+ ? new GZIPInputStream(probingInputStream)
+ : probingInputStream;
final int numRead = wrappedInputStream.read(signatureBytes);
if (numRead < 0) {
throw new HtsjdkIOException(String.format("0 bytes read from input stream for %s", sourceName));
@@ -80,5 +84,4 @@ public boolean canDecodeSignature(final SignatureStream probingInputStream, fina
* @return the signature string for this codec
*/
protected abstract String getSignatureString();
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFDecoder.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFDecoder.java
index 31674fa064..82e80e28a5 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFDecoder.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFDecoder.java
@@ -1,12 +1,13 @@
package htsjdk.beta.codecs.variants.vcf;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.exception.HtsjdkException;
import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
-import htsjdk.beta.plugin.HtsContentType;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResource;
import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.plugin.HtsContentType;
import htsjdk.beta.plugin.interval.HtsInterval;
import htsjdk.beta.plugin.interval.HtsIntervalUtils;
import htsjdk.beta.plugin.interval.HtsQueryRule;
@@ -19,17 +20,13 @@
import htsjdk.samtools.util.CloseableIterator;
import htsjdk.tribble.AbstractFeatureReader;
import htsjdk.tribble.FeatureReader;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.vcf.AbstractVCFCodec;
import htsjdk.variant.vcf.VCFHeader;
-
import java.io.IOException;
-import java.nio.channels.SeekableByteChannel;
import java.util.List;
import java.util.Optional;
-import java.util.function.Function;
/**
* InternalAPII
@@ -65,16 +62,21 @@ public VCFDecoder(
this.inputBundle = inputBundle;
this.variantsDecoderOptions = variantsDecoderOptions;
- this.displayName = inputBundle.getOrThrow(BundleResourceType.CT_VARIANT_CONTEXTS).getDisplayName();
+ this.displayName =
+ inputBundle.getOrThrow(BundleResourceType.CT_VARIANT_CONTEXTS).getDisplayName();
vcfReader = getVCFReader(inputBundle, vcfCodec, variantsDecoderOptions);
vcfHeader = (VCFHeader) vcfReader.getHeader();
}
@Override
- final public String getFileFormat() { return VariantsFormats.VCF; }
+ public final String getFileFormat() {
+ return VariantsFormats.VCF;
+ }
@Override
- final public String getDisplayName() { return displayName; }
+ public final String getDisplayName() {
+ return displayName;
+ }
@Override
public VCFHeader getHeader() {
@@ -86,7 +88,8 @@ public CloseableIterator iterator() {
try {
return vcfReader.iterator();
} catch (IOException e) {
- throw new HtsjdkIOException(String.format("Exception creating variant context iterator for %s", displayName), e);
+ throw new HtsjdkIOException(
+ String.format("Exception creating variant context iterator for %s", displayName), e);
}
}
@@ -108,13 +111,15 @@ public CloseableIterator query(final List intervals
VariantsCodecUtils.assertBundleContainsIndex(getInputBundle());
if (intervals.size() > 1) {
- //TODO: implement lists, sorting, merging, and ensuring that features that overlap more than one interval
+ // TODO: implement lists, sorting, merging, and ensuring that features that overlap more than one interval
// are only returned once
- throw new HtsjdkUnsupportedOperationException(String.format("query for lists not yet implemented for decoder %s", displayName));
+ throw new HtsjdkUnsupportedOperationException(
+ String.format("query for lists not yet implemented for decoder %s", displayName));
}
if (queryRule != HtsQueryRule.OVERLAPPING) {
- //TODO: implement overlapping
- throw new HtsjdkUnsupportedOperationException(String.format("query for contained intervals not implemented for this decoder %s", displayName));
+ // TODO: implement overlapping
+ throw new HtsjdkUnsupportedOperationException(
+ String.format("query for contained intervals not implemented for this decoder %s", displayName));
}
try {
@@ -140,19 +145,18 @@ public CloseableIterator queryStart(final String queryName, fina
if (vcfHeader == null) {
throw new HtsjdkException(String.format(
- "A valid VCF header is required to execute a query, but is not present: %s.",
- displayName));
+ "A valid VCF header is required to execute a query, but is not present: %s.", displayName));
}
final SAMSequenceDictionary seqDict = vcfHeader.getSequenceDictionary();
if (seqDict == null) {
- throw new HtsjdkException(String.format("No sequence dictionary is present in the input: %s.", displayName));
+ throw new HtsjdkException(
+ String.format("No sequence dictionary is present in the input: %s.", displayName));
}
final SAMSequenceRecord samSequenceRecord = seqDict.getSequence(queryName);
if (samSequenceRecord == null) {
throw new HtsjdkException(String.format(
"The query name %s is not present in the dictionary provided in the input: %s.",
- queryName,
- displayName));
+ queryName, displayName));
}
final int length = samSequenceRecord.getSequenceLength();
try {
@@ -190,22 +194,19 @@ public VariantsDecoderOptions getReadsDecoderOptions() {
}
private static FeatureReader getVCFReader(
- final Bundle inputBundle,
- final AbstractVCFCodec vcfCodec,
- final VariantsDecoderOptions decoderOptions) {
+ final Bundle inputBundle, final AbstractVCFCodec vcfCodec, final VariantsDecoderOptions decoderOptions) {
final BundleResource variantsResource = inputBundle.getOrThrow(BundleResourceType.CT_VARIANT_CONTEXTS);
if (!variantsResource.hasInputType()) {
throw new IllegalArgumentException(String.format(
"The provided %s resource (%s) must be a readable/input resource",
- BundleResourceType.CT_VARIANT_CONTEXTS,
- variantsResource));
+ BundleResourceType.CT_VARIANT_CONTEXTS, variantsResource));
} else if (variantsResource.getIOPath().isEmpty()) {
throw new HtsjdkUnsupportedOperationException("VCF reader from stream not implemented");
}
final IOPath variantsIOPath = variantsResource.getIOPath().get();
final Optional indexIOPath = getIndexIOPath(inputBundle);
- //TODO: this resolves the index automatically. it should check to make sure the provided index
+ // TODO: this resolves the index automatically. it should check to make sure the provided index
// matches the one that is automatically resolved, otherwise throw since the request will not be honored
return AbstractFeatureReader.getFeatureReader(
variantsIOPath.getURIString(),
@@ -213,8 +214,7 @@ private static FeatureReader getVCFReader(
vcfCodec,
indexIOPath.isPresent(),
decoderOptions.getVariantsChannelTransformer().orElse(null),
- decoderOptions.getIndexChannelTransformer().orElse(null)
- );
+ decoderOptions.getIndexChannelTransformer().orElse(null));
}
// the underlying readers can't handle index streams, so for now we can only handle IOPaths
@@ -226,14 +226,12 @@ private static Optional getIndexIOPath(final Bundle inputBundle) {
final BundleResource indexResource = optIndexResource.get();
if (!indexResource.hasInputType()) {
throw new IllegalArgumentException(String.format(
- "The provided %s index resource (%s) must be a readable/input resource",
- BundleResourceType.CT_VARIANTS_INDEX,
- indexResource));
+ "The provided %s index resource (%s) must be a readable/input resource",
+ BundleResourceType.CT_VARIANTS_INDEX, indexResource));
}
if (indexResource.getIOPath().isEmpty()) {
throw new HtsjdkUnsupportedOperationException("Reading a VCF index from a stream not implemented");
}
return indexResource.getIOPath();
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFEncoder.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFEncoder.java
index ab17269024..a30a40c29e 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFEncoder.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/VCFEncoder.java
@@ -1,26 +1,24 @@
package htsjdk.beta.codecs.variants.vcf;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.exception.HtsjdkPluginException;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
-import htsjdk.beta.plugin.HtsContentType;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResource;
import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.plugin.HtsContentType;
import htsjdk.beta.plugin.variants.VariantsEncoder;
import htsjdk.beta.plugin.variants.VariantsEncoderOptions;
import htsjdk.beta.plugin.variants.VariantsFormats;
import htsjdk.io.IOPath;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.variantcontext.writer.Options;
import htsjdk.variant.variantcontext.writer.VariantContextWriter;
import htsjdk.variant.variantcontext.writer.VariantContextWriterBuilder;
import htsjdk.variant.vcf.VCFHeader;
-
import java.util.Optional;
-
/**
* InternalAPI
*
@@ -51,14 +49,19 @@ public VCFEncoder(final Bundle outputBundle, final VariantsEncoderOptions varian
this.outputBundle = outputBundle;
this.variantsEncoderOptions = variantsEncoderOptions;
- this.displayName = outputBundle.getOrThrow(BundleResourceType.CT_VARIANT_CONTEXTS).getDisplayName();
+ this.displayName =
+ outputBundle.getOrThrow(BundleResourceType.CT_VARIANT_CONTEXTS).getDisplayName();
}
- @Override
- final public String getFileFormat() { return VariantsFormats.VCF; }
+ @Override
+ public final String getFileFormat() {
+ return VariantsFormats.VCF;
+ }
@Override
- final public String getDisplayName() { return displayName; }
+ public final String getDisplayName() {
+ return displayName;
+ }
@Override
public void setHeader(final VCFHeader vcfHeader) {
@@ -104,21 +107,17 @@ public VariantsEncoderOptions getVariantsEncoderOptions() {
}
private static VariantContextWriter getVCFWriter(
- final Bundle outputBundle,
- final VariantsEncoderOptions variantsEncoderOptions) {
- final VariantContextWriterBuilder writerBuilder =
- variantsEncoderOptionsToVariantContextWriterBuilder(
- variantsEncoderOptions,
- outputBundle.get(BundleResourceType.CT_VARIANTS_INDEX).isPresent()
- );
+ final Bundle outputBundle, final VariantsEncoderOptions variantsEncoderOptions) {
+ final VariantContextWriterBuilder writerBuilder = variantsEncoderOptionsToVariantContextWriterBuilder(
+ variantsEncoderOptions,
+ outputBundle.get(BundleResourceType.CT_VARIANTS_INDEX).isPresent());
setWriterBuilderOutputs(writerBuilder, outputBundle);
return writerBuilder.build();
}
// propagate VariantsEncoderOptions -> VariantContextWriterBuilder
private static VariantContextWriterBuilder variantsEncoderOptionsToVariantContextWriterBuilder(
- final VariantsEncoderOptions variantsEncoderOptions,
- final boolean createIndex) {
+ final VariantsEncoderOptions variantsEncoderOptions, final boolean createIndex) {
final VariantContextWriterBuilder vcWriterBuilder = new VariantContextWriterBuilder();
vcWriterBuilder.clearOptions();
@@ -152,21 +151,19 @@ private static VariantContextWriterBuilder variantsEncoderOptionsToVariantContex
}
private static void setWriterBuilderOutputs(
- final VariantContextWriterBuilder writerBuilder,
- final Bundle outputBundle) {
+ final VariantContextWriterBuilder writerBuilder, final Bundle outputBundle) {
final BundleResource variantsResource = outputBundle.getOrThrow(BundleResourceType.CT_VARIANT_CONTEXTS);
if (!variantsResource.hasOutputType()) {
throw new IllegalArgumentException(String.format(
"The provided %s resource (%s) must be a writeable/output resource",
- BundleResourceType.CT_VARIANT_CONTEXTS,
- variantsResource));
+ BundleResourceType.CT_VARIANT_CONTEXTS, variantsResource));
}
final Optional optIndexIOPath = getIndexIOPath(outputBundle);
if (variantsResource.getIOPath().isPresent()) {
final IOPath variantsIOPath = variantsResource.getIOPath().get();
if (optIndexIOPath.isPresent()) {
- //TODO: this resolves the index automatically. it should check to make sure the provided index
+ // TODO: this resolves the index automatically. it should check to make sure the provided index
// matches the one that is automatically resolved, otherwise throw since the request will not be honored
}
writerBuilder.setOutputPath(variantsIOPath.toPath());
@@ -175,8 +172,7 @@ private static void setWriterBuilderOutputs(
if (optIndexIOPath.isPresent()) {
throw new HtsjdkUnsupportedOperationException(String.format(
"Can't write a VCF index to file %s when output is written to a stream %s",
- optIndexIOPath.get(),
- variantsResource));
+ optIndexIOPath.get(), variantsResource));
}
// VariantContextWriterBuilder doesn't provide any buffering, but if we were to wrap the provided
// stream in a buffered stream here, we wouldn't be able to properly control the flushing or lifetime
@@ -197,13 +193,11 @@ private static void setWriterBuilderOutputs(
private static void validateImputedOutputType(final IOPath variantsIOPath) {
final VariantContextWriterBuilder.OutputType imputedOutputType =
VariantContextWriterBuilder.determineOutputTypeFromFile(variantsIOPath.toPath());
- if (imputedOutputType != VariantContextWriterBuilder.OutputType.VCF &&
- imputedOutputType != VariantContextWriterBuilder.OutputType.BLOCK_COMPRESSED_VCF) {
+ if (imputedOutputType != VariantContextWriterBuilder.OutputType.VCF
+ && imputedOutputType != VariantContextWriterBuilder.OutputType.BLOCK_COMPRESSED_VCF) {
throw new HtsjdkPluginException(String.format(
"An unsupported output type %s was derived for the resource %s ",
- imputedOutputType,
- variantsIOPath.getRawInputString()
- ));
+ imputedOutputType, variantsIOPath.getRawInputString()));
}
}
@@ -216,13 +210,11 @@ private static Optional getIndexIOPath(final Bundle outputBundle) {
if (!indexResource.hasOutputType()) {
throw new IllegalArgumentException(String.format(
"The provided %s index resource (%s) must be a writeable/output resource",
- BundleResourceType.CT_VARIANTS_INDEX,
- indexResource));
+ BundleResourceType.CT_VARIANTS_INDEX, indexResource));
}
if (!indexResource.getIOPath().isPresent()) {
throw new HtsjdkUnsupportedOperationException("Writing a VCF index to a stream not implemented");
}
return indexResource.getIOPath();
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/VariantsCodecUtils.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/VariantsCodecUtils.java
index ecf5375f42..82410b37f9 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/VariantsCodecUtils.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/VariantsCodecUtils.java
@@ -1,8 +1,8 @@
package htsjdk.beta.codecs.variants.vcf;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResourceType;
-import htsjdk.annotations.InternalAPI;
/**
* Utilities for VCF codec implementations.
@@ -38,8 +38,7 @@ public static void assertBundleContainsIndex(final Bundle inputBundle) {
if (!bundleContainsIndex(inputBundle)) {
throw new IllegalArgumentException(String.format(
"To make index queries, an index resource must be provided in the resource bundle: %s",
- inputBundle
- ));
+ inputBundle));
}
}
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFCodecV3_2.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFCodecV3_2.java
index 5956aedc0a..711e32c0cc 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFCodecV3_2.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFCodecV3_2.java
@@ -4,8 +4,8 @@
import htsjdk.beta.codecs.variants.vcf.VCFDecoder;
import htsjdk.beta.codecs.variants.vcf.VCFEncoder;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsDecoderOptions;
import htsjdk.beta.plugin.variants.VariantsEncoderOptions;
import htsjdk.utils.ValidationUtils;
@@ -14,12 +14,14 @@
* VCF V3.2 codec.
*/
public class VCFCodecV3_2 extends VCFCodec {
- public static final HtsVersion VCF_V32_VERSION = new HtsVersion(3,2,0);
+ public static final HtsVersion VCF_V32_VERSION = new HtsVersion(3, 2, 0);
private static final String VCF_V32_MAGIC = "##format=VCRv3.2";
@Override
- public HtsVersion getVersion() { return VCF_V32_VERSION; }
+ public HtsVersion getVersion() {
+ return VCF_V32_VERSION;
+ }
@Override
public VCFDecoder getDecoder(final Bundle inputBundle, final VariantsDecoderOptions decoderOptions) {
@@ -43,6 +45,7 @@ public boolean runVersionUpgrade(final HtsVersion sourceCodecVersion, final HtsV
}
@Override
- protected String getSignatureString() { return VCF_V32_MAGIC; }
-
+ protected String getSignatureString() {
+ return VCF_V32_MAGIC;
+ }
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFDecoderV3_2.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFDecoderV3_2.java
index 8b692266fd..b4547b9cfd 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFDecoderV3_2.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFDecoderV3_2.java
@@ -1,8 +1,8 @@
package htsjdk.beta.codecs.variants.vcf.vcfv3_2;
import htsjdk.beta.codecs.variants.vcf.VCFDecoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsDecoderOptions;
import htsjdk.variant.vcf.VCF3Codec;
@@ -25,5 +25,4 @@ public VCFDecoderV3_2(final Bundle inputBundle, final VariantsDecoderOptions var
public HtsVersion getVersion() {
return VCFCodecV3_2.VCF_V32_VERSION;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFEncoderV3_2.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFEncoderV3_2.java
index 3367de3f17..967e618cd6 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFEncoderV3_2.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_2/VCFEncoderV3_2.java
@@ -1,8 +1,8 @@
package htsjdk.beta.codecs.variants.vcf.vcfv3_2;
import htsjdk.beta.codecs.variants.vcf.VCFEncoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsEncoderOptions;
/**
@@ -17,12 +17,11 @@ public class VCFEncoderV3_2 extends VCFEncoder {
* @param variantsEncoderOptions the {@link VariantsEncoderOptions} to use
*/
public VCFEncoderV3_2(final Bundle outputBundle, final VariantsEncoderOptions variantsEncoderOptions) {
- super(outputBundle,variantsEncoderOptions);
+ super(outputBundle, variantsEncoderOptions);
}
@Override
public HtsVersion getVersion() {
return VCFCodecV3_2.VCF_V32_VERSION;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFCodecV3_3.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFCodecV3_3.java
index df865c0208..64072b7af0 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFCodecV3_3.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFCodecV3_3.java
@@ -4,8 +4,8 @@
import htsjdk.beta.codecs.variants.vcf.VCFDecoder;
import htsjdk.beta.codecs.variants.vcf.VCFEncoder;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsDecoderOptions;
import htsjdk.beta.plugin.variants.VariantsEncoderOptions;
import htsjdk.utils.ValidationUtils;
@@ -14,12 +14,14 @@
* VCF V3.3 codec.
*/
public class VCFCodecV3_3 extends VCFCodec {
- public static final HtsVersion VCF_V33_VERSION = new HtsVersion(3,3,0);
+ public static final HtsVersion VCF_V33_VERSION = new HtsVersion(3, 3, 0);
private static final String VCF_V33_MAGIC = "##fileformat=VCFv3.3";
@Override
- public HtsVersion getVersion() { return VCF_V33_VERSION; }
+ public HtsVersion getVersion() {
+ return VCF_V33_VERSION;
+ }
@Override
public VCFDecoder getDecoder(final Bundle inputBundle, final VariantsDecoderOptions decoderOptions) {
@@ -43,6 +45,7 @@ public boolean runVersionUpgrade(final HtsVersion sourceCodecVersion, final HtsV
}
@Override
- protected String getSignatureString() { return VCF_V33_MAGIC; }
-
+ protected String getSignatureString() {
+ return VCF_V33_MAGIC;
+ }
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFDecoderV3_3.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFDecoderV3_3.java
index 69a1485009..43a1700f9b 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFDecoderV3_3.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFDecoderV3_3.java
@@ -1,8 +1,8 @@
package htsjdk.beta.codecs.variants.vcf.vcfv3_3;
import htsjdk.beta.codecs.variants.vcf.VCFDecoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsDecoderOptions;
import htsjdk.variant.vcf.VCF3Codec;
@@ -25,5 +25,4 @@ public VCFDecoderV3_3(final Bundle inputBundle, final VariantsDecoderOptions var
public HtsVersion getVersion() {
return VCFCodecV3_3.VCF_V33_VERSION;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFEncoderV3_3.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFEncoderV3_3.java
index 2e848ab4fd..82e57f63cc 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFEncoderV3_3.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv3_3/VCFEncoderV3_3.java
@@ -1,8 +1,8 @@
package htsjdk.beta.codecs.variants.vcf.vcfv3_3;
import htsjdk.beta.codecs.variants.vcf.VCFEncoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsEncoderOptions;
/**
@@ -17,12 +17,11 @@ public class VCFEncoderV3_3 extends VCFEncoder {
* @param variantsEncoderOptions the {@link VariantsEncoderOptions} to use
*/
public VCFEncoderV3_3(final Bundle outputBundle, final VariantsEncoderOptions variantsEncoderOptions) {
- super(outputBundle,variantsEncoderOptions);
+ super(outputBundle, variantsEncoderOptions);
}
@Override
public HtsVersion getVersion() {
return VCFCodecV3_3.VCF_V33_VERSION;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFCodecV4_0.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFCodecV4_0.java
index 88d1453f1f..b7ccc4bab3 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFCodecV4_0.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFCodecV4_0.java
@@ -4,8 +4,8 @@
import htsjdk.beta.codecs.variants.vcf.VCFDecoder;
import htsjdk.beta.codecs.variants.vcf.VCFEncoder;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsDecoderOptions;
import htsjdk.beta.plugin.variants.VariantsEncoderOptions;
import htsjdk.utils.ValidationUtils;
@@ -14,12 +14,14 @@
* VCF V4.0 codec.
*/
public class VCFCodecV4_0 extends VCFCodec {
- public static final HtsVersion VCF_V40_VERSION = new HtsVersion(4,0,0);
+ public static final HtsVersion VCF_V40_VERSION = new HtsVersion(4, 0, 0);
private static final String VCF_V40_MAGIC = "##fileformat=VCFv4.0";
@Override
- public HtsVersion getVersion() { return VCF_V40_VERSION; }
+ public HtsVersion getVersion() {
+ return VCF_V40_VERSION;
+ }
@Override
public VCFDecoder getDecoder(final Bundle inputBundle, final VariantsDecoderOptions decoderOptions) {
@@ -43,6 +45,7 @@ public boolean runVersionUpgrade(final HtsVersion sourceCodecVersion, final HtsV
}
@Override
- protected String getSignatureString() { return VCF_V40_MAGIC; }
-
+ protected String getSignatureString() {
+ return VCF_V40_MAGIC;
+ }
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFDecoderV4_0.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFDecoderV4_0.java
index fb0e57facc..459fc249cb 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFDecoderV4_0.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFDecoderV4_0.java
@@ -1,8 +1,8 @@
package htsjdk.beta.codecs.variants.vcf.vcfv4_0;
import htsjdk.beta.codecs.variants.vcf.VCFDecoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsDecoderOptions;
/**
@@ -24,5 +24,4 @@ public VCFDecoderV4_0(final Bundle inputBundle, final VariantsDecoderOptions var
public HtsVersion getVersion() {
return VCFCodecV4_0.VCF_V40_VERSION;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFEncoderV4_0.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFEncoderV4_0.java
index 77b42a5318..a68b0b7ad4 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFEncoderV4_0.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_0/VCFEncoderV4_0.java
@@ -1,8 +1,8 @@
package htsjdk.beta.codecs.variants.vcf.vcfv4_0;
import htsjdk.beta.codecs.variants.vcf.VCFEncoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsEncoderOptions;
/**
@@ -17,12 +17,11 @@ public class VCFEncoderV4_0 extends VCFEncoder {
* @param variantsEncoderOptions the {@link VariantsEncoderOptions} to use
*/
public VCFEncoderV4_0(final Bundle outputBundle, final VariantsEncoderOptions variantsEncoderOptions) {
- super(outputBundle,variantsEncoderOptions);
+ super(outputBundle, variantsEncoderOptions);
}
@Override
public HtsVersion getVersion() {
return VCFCodecV4_0.VCF_V40_VERSION;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFCodecV4_1.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFCodecV4_1.java
index 6b114fad34..adbc44d000 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFCodecV4_1.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFCodecV4_1.java
@@ -4,8 +4,8 @@
import htsjdk.beta.codecs.variants.vcf.VCFDecoder;
import htsjdk.beta.codecs.variants.vcf.VCFEncoder;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsDecoderOptions;
import htsjdk.beta.plugin.variants.VariantsEncoderOptions;
import htsjdk.utils.ValidationUtils;
@@ -14,12 +14,14 @@
* VCF V4.1 codec.
*/
public class VCFCodecV4_1 extends VCFCodec {
- public static final HtsVersion VCF_V41_VERSION = new HtsVersion(4,1,0);
+ public static final HtsVersion VCF_V41_VERSION = new HtsVersion(4, 1, 0);
private static final String VCF_V41_MAGIC = "##fileformat=VCFv4.1";
@Override
- public HtsVersion getVersion() { return VCF_V41_VERSION; }
+ public HtsVersion getVersion() {
+ return VCF_V41_VERSION;
+ }
@Override
public VCFDecoder getDecoder(final Bundle inputBundle, final VariantsDecoderOptions decoderOptions) {
@@ -43,6 +45,7 @@ public boolean runVersionUpgrade(final HtsVersion sourceCodecVersion, final HtsV
}
@Override
- protected String getSignatureString() { return VCF_V41_MAGIC; }
-
+ protected String getSignatureString() {
+ return VCF_V41_MAGIC;
+ }
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFDecoderV4_1.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFDecoderV4_1.java
index 9651ba11e0..8c85525f8e 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFDecoderV4_1.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFDecoderV4_1.java
@@ -1,8 +1,8 @@
package htsjdk.beta.codecs.variants.vcf.vcfv4_1;
import htsjdk.beta.codecs.variants.vcf.VCFDecoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsDecoderOptions;
/**
@@ -24,5 +24,4 @@ public VCFDecoderV4_1(final Bundle inputBundle, final VariantsDecoderOptions var
public HtsVersion getVersion() {
return VCFCodecV4_1.VCF_V41_VERSION;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFEncoderV4_1.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFEncoderV4_1.java
index 0418befb3e..b7db01c2fe 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFEncoderV4_1.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_1/VCFEncoderV4_1.java
@@ -1,8 +1,8 @@
package htsjdk.beta.codecs.variants.vcf.vcfv4_1;
import htsjdk.beta.codecs.variants.vcf.VCFEncoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsEncoderOptions;
/**
@@ -17,12 +17,11 @@ public class VCFEncoderV4_1 extends VCFEncoder {
* @param variantsEncoderOptions the {@link VariantsEncoderOptions} to use
*/
public VCFEncoderV4_1(final Bundle outputBundle, final VariantsEncoderOptions variantsEncoderOptions) {
- super(outputBundle,variantsEncoderOptions);
+ super(outputBundle, variantsEncoderOptions);
}
@Override
public HtsVersion getVersion() {
return VCFCodecV4_1.VCF_V41_VERSION;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFCodecV4_2.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFCodecV4_2.java
index 30214c4dc1..3eaf1d26a7 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFCodecV4_2.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFCodecV4_2.java
@@ -14,12 +14,14 @@
* VCF V4.2 codec.
*/
public class VCFCodecV4_2 extends VCFCodec {
- public static final HtsVersion VCF_V42_VERSION = new HtsVersion(4,2,0);
+ public static final HtsVersion VCF_V42_VERSION = new HtsVersion(4, 2, 0);
private static final String VCF_V42_MAGIC = "##fileformat=VCFv4.2";
@Override
- public HtsVersion getVersion() { return VCF_V42_VERSION; }
+ public HtsVersion getVersion() {
+ return VCF_V42_VERSION;
+ }
@Override
public VCFDecoder getDecoder(final Bundle inputBundle, final VariantsDecoderOptions decoderOptions) {
@@ -43,6 +45,7 @@ public boolean runVersionUpgrade(final HtsVersion sourceCodecVersion, final HtsV
}
@Override
- protected String getSignatureString() { return VCF_V42_MAGIC; }
-
+ protected String getSignatureString() {
+ return VCF_V42_MAGIC;
+ }
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFDecoderV4_2.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFDecoderV4_2.java
index 097a7a3d74..e30e376df3 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFDecoderV4_2.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFDecoderV4_2.java
@@ -24,5 +24,4 @@ public VCFDecoderV4_2(final Bundle inputBundle, final VariantsDecoderOptions var
public HtsVersion getVersion() {
return VCFCodecV4_2.VCF_V42_VERSION;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFEncoderV4_2.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFEncoderV4_2.java
index e23d976aaf..622acb37e1 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFEncoderV4_2.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_2/VCFEncoderV4_2.java
@@ -17,12 +17,11 @@ public class VCFEncoderV4_2 extends VCFEncoder {
* @param variantsEncoderOptions the {@link VariantsEncoderOptions} to use
*/
public VCFEncoderV4_2(final Bundle outputBundle, final VariantsEncoderOptions variantsEncoderOptions) {
- super(outputBundle,variantsEncoderOptions);
+ super(outputBundle, variantsEncoderOptions);
}
@Override
public HtsVersion getVersion() {
return VCFCodecV4_2.VCF_V42_VERSION;
}
-
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_3/VCFCodecV4_3.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_3/VCFCodecV4_3.java
index 44516b4a72..7593928df0 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_3/VCFCodecV4_3.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_3/VCFCodecV4_3.java
@@ -4,8 +4,8 @@
import htsjdk.beta.codecs.variants.vcf.VCFDecoder;
import htsjdk.beta.codecs.variants.vcf.VCFEncoder;
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsDecoderOptions;
import htsjdk.beta.plugin.variants.VariantsEncoderOptions;
import htsjdk.utils.ValidationUtils;
@@ -14,12 +14,14 @@
* VCF V4.3 codec.
*/
public class VCFCodecV4_3 extends VCFCodec {
- public static final HtsVersion VCF_V43_VERSION = new HtsVersion(4,3,0);
+ public static final HtsVersion VCF_V43_VERSION = new HtsVersion(4, 3, 0);
private static final String VCF_V43_MAGIC = "##fileformat=VCFv4.3";
@Override
- public HtsVersion getVersion() { return VCF_V43_VERSION; }
+ public HtsVersion getVersion() {
+ return VCF_V43_VERSION;
+ }
@Override
public VCFDecoder getDecoder(final Bundle inputBundle, final VariantsDecoderOptions decoderOptions) {
@@ -40,6 +42,7 @@ public boolean runVersionUpgrade(final HtsVersion sourceCodecVersion, final HtsV
}
@Override
- protected String getSignatureString() { return VCF_V43_MAGIC; }
-
+ protected String getSignatureString() {
+ return VCF_V43_MAGIC;
+ }
}
diff --git a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_3/VCFDecoderV4_3.java b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_3/VCFDecoderV4_3.java
index 32de5539fa..92a9051a3d 100644
--- a/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_3/VCFDecoderV4_3.java
+++ b/src/main/java/htsjdk/beta/codecs/variants/vcf/vcfv4_3/VCFDecoderV4_3.java
@@ -1,8 +1,8 @@
package htsjdk.beta.codecs.variants.vcf.vcfv4_3;
import htsjdk.beta.codecs.variants.vcf.VCFDecoder;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsDecoderOptions;
/**
@@ -24,5 +24,4 @@ public VCFDecoderV4_3(final Bundle inputBundle, final VariantsDecoderOptions var
public HtsVersion getVersion() {
return VCFCodecV4_3.VCF_V43_VERSION;
}
-
}
diff --git a/src/main/java/htsjdk/beta/exception/HtsjdkPluginException.java b/src/main/java/htsjdk/beta/exception/HtsjdkPluginException.java
index 470b0eb96c..1adebb012b 100644
--- a/src/main/java/htsjdk/beta/exception/HtsjdkPluginException.java
+++ b/src/main/java/htsjdk/beta/exception/HtsjdkPluginException.java
@@ -14,5 +14,4 @@ public class HtsjdkPluginException extends HtsjdkException {
public HtsjdkPluginException(String message) {
super(message);
}
-
}
diff --git a/src/main/java/htsjdk/beta/io/IOPathUtils.java b/src/main/java/htsjdk/beta/io/IOPathUtils.java
index 965c850a59..fe5476af6a 100644
--- a/src/main/java/htsjdk/beta/io/IOPathUtils.java
+++ b/src/main/java/htsjdk/beta/io/IOPathUtils.java
@@ -3,8 +3,6 @@
import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.io.HtsPath;
import htsjdk.io.IOPath;
-import htsjdk.utils.ValidationUtils;
-
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
@@ -42,17 +40,14 @@ public static IOPath createTempPath(final String prefix, final String suffix) {
public static String getStringFromPath(final IOPath ioPath) {
try {
final StringWriter stringWriter = new StringWriter();
- //TODO: the UTF-8 encoding of these should be codified somewhere else...
- Files.lines(ioPath.toPath(), StandardCharsets.UTF_8).forEach(
- line -> {
- stringWriter.write(line);
- stringWriter.append("\n");
- });
+ // TODO: the UTF-8 encoding of these should be codified somewhere else...
+ Files.lines(ioPath.toPath(), StandardCharsets.UTF_8).forEach(line -> {
+ stringWriter.write(line);
+ stringWriter.append("\n");
+ });
return stringWriter.toString();
} catch (final IOException e) {
- throw new HtsjdkIOException(
- String.format("Failed to read from: %s", ioPath.getRawInputString()),
- e);
+ throw new HtsjdkIOException(String.format("Failed to read from: %s", ioPath.getRawInputString()), e);
}
}
@@ -66,9 +61,7 @@ public static void writeStringToPath(final IOPath ioPath, final String contents)
try (final BufferedOutputStream bos = new BufferedOutputStream(ioPath.getOutputStream())) {
bos.write(contents.getBytes());
} catch (final IOException e) {
- throw new HtsjdkIOException(
- String.format("Failed to write to: %s", ioPath.getRawInputString()),
- e);
+ throw new HtsjdkIOException(String.format("Failed to write to: %s", ioPath.getRawInputString()), e);
}
}
@@ -91,19 +84,16 @@ public static void writeStringToPath(final IOPath ioPath, final String contents)
* @return A new IOPath object with the new extension
*/
public static T replaceExtension(
- final IOPath path,
- final String newExtension,
- final Function ioPathConstructor){
- final String extensionToUse = newExtension.startsWith(".") ?
- newExtension :
- "." + newExtension;
+ final IOPath path, final String newExtension, final Function ioPathConstructor) {
+ final String extensionToUse = newExtension.startsWith(".") ? newExtension : "." + newExtension;
final Optional oldExtension = path.getExtension();
- if (oldExtension.isEmpty()){
+ if (oldExtension.isEmpty()) {
throw new RuntimeException("The original path has no extension to replace" + path.getURIString());
}
final String oldFileName = path.toPath().getFileName().toString();
final String newFileName = oldFileName.replaceAll(oldExtension.get() + "$", extensionToUse);
- return ioPathConstructor.apply(path.toPath().resolveSibling(newFileName).toUri().toString());
+ return ioPathConstructor.apply(
+ path.toPath().resolveSibling(newFileName).toUri().toString());
}
/**
@@ -123,13 +113,10 @@ public static T replaceExtension(
* @return A new IOPath object with the new extension
*/
public static T appendExtension(
- final IOPath path,
- final String extension,
- final Function ioPathConstructor){
+ final IOPath path, final String extension, final Function ioPathConstructor) {
final String oldFileName = path.toPath().getFileName().toString();
- final String newExtension = extension.startsWith(".") ?
- extension :
- "." + extension;
- return ioPathConstructor.apply(path.toPath().resolveSibling(oldFileName + newExtension).toUri().toString());
+ final String newExtension = extension.startsWith(".") ? extension : "." + extension;
+ return ioPathConstructor.apply(
+ path.toPath().resolveSibling(oldFileName + newExtension).toUri().toString());
}
}
diff --git a/src/main/java/htsjdk/beta/io/bundle/Bundle.java b/src/main/java/htsjdk/beta/io/bundle/Bundle.java
index 06ef7d12dd..9b7187401c 100644
--- a/src/main/java/htsjdk/beta/io/bundle/Bundle.java
+++ b/src/main/java/htsjdk/beta/io/bundle/Bundle.java
@@ -2,7 +2,6 @@
import htsjdk.io.IOPath;
import htsjdk.utils.ValidationUtils;
-
import java.io.Serializable;
import java.util.*;
@@ -50,8 +49,8 @@ public class Bundle implements Iterable, Serializable {
*/
public Bundle(final String primaryContentType, final Collection resources) {
ValidationUtils.nonNull(primaryContentType, "primary content type");
- ValidationUtils.validateArg(primaryContentType.length() > 0,
- "A non-zero length primary resource content type must be provided");
+ ValidationUtils.validateArg(
+ primaryContentType.length() > 0, "A non-zero length primary resource content type must be provided");
ValidationUtils.nonNull(resources, "resource collection");
if (resources.isEmpty()) {
throw new IllegalArgumentException("A bundle must contain at least one resource");
@@ -67,9 +66,8 @@ public Bundle(final String primaryContentType, final Collection
// validate that the primary resource actually exists in the resources
if (!this.resources.containsKey(primaryContentType)) {
- throw new IllegalArgumentException(
- String.format("Primary resource content type %s is not present in the bundle's resources",
- primaryContentType));
+ throw new IllegalArgumentException(String.format(
+ "Primary resource content type %s is not present in the bundle's resources", primaryContentType));
}
}
@@ -94,12 +92,9 @@ public Optional get(final String targetContentType) {
*/
public BundleResource getOrThrow(final String requiredContentType) {
ValidationUtils.nonNull(requiredContentType, "target content string");
- return get(requiredContentType).orElseThrow(
- () -> new IllegalArgumentException(
- String.format("No resource found in bundle %s with content type %s",
- this,
- requiredContentType
- )));
+ return get(requiredContentType)
+ .orElseThrow(() -> new IllegalArgumentException(String.format(
+ "No resource found in bundle %s with content type %s", this, requiredContentType)));
}
/**
@@ -107,7 +102,9 @@ public BundleResource getOrThrow(final String requiredContentType) {
*
* @return the primary content type for this bundle
*/
- public String getPrimaryContentType() { return primaryContentType; }
+ public String getPrimaryContentType() {
+ return primaryContentType;
+ }
/**
* Get the primary {@link BundleResource} for this bundle.
@@ -131,7 +128,9 @@ public Collection getResources() {
* @return iterator of BundleResources for this bundle.
*/
@Override
- public Iterator iterator() { return resources.values().iterator(); }
+ public Iterator iterator() {
+ return resources.values().iterator();
+ }
@Override
public boolean equals(Object o) {
diff --git a/src/main/java/htsjdk/beta/io/bundle/BundleBuilder.java b/src/main/java/htsjdk/beta/io/bundle/BundleBuilder.java
index 4affc3dbfb..139eba5958 100644
--- a/src/main/java/htsjdk/beta/io/bundle/BundleBuilder.java
+++ b/src/main/java/htsjdk/beta/io/bundle/BundleBuilder.java
@@ -1,7 +1,6 @@
package htsjdk.beta.io.bundle;
import htsjdk.utils.ValidationUtils;
-
import java.util.ArrayList;
import java.util.List;
@@ -16,7 +15,7 @@ public final class BundleBuilder {
/**
* Start a new bundle builder.
*/
- public BundleBuilder() { }
+ public BundleBuilder() {}
/**
* Add the primary resource to the bundle. The content type of resource will be the bundle's primary key.
@@ -27,10 +26,9 @@ public BundleBuilder() { }
public BundleBuilder addPrimary(final BundleResource resource) {
ValidationUtils.nonNull(resource, "resource");
if (primaryResource != null) {
- throw new IllegalStateException(String.format(
- "Can't add primary resource %s to a bundle that already has primary resource %s",
- resource.getContentType(),
- primaryResource));
+ throw new IllegalStateException(String.format(
+ "Can't add primary resource %s to a bundle that already has primary resource %s",
+ resource.getContentType(), primaryResource));
}
primaryResource = resource.getContentType();
addSecondary(resource);
@@ -66,5 +64,3 @@ public Bundle build() {
return bundle;
}
}
-
-
diff --git a/src/main/java/htsjdk/beta/io/bundle/BundleJSON.java b/src/main/java/htsjdk/beta/io/bundle/BundleJSON.java
index 95d4d7aaac..f367e9516e 100644
--- a/src/main/java/htsjdk/beta/io/bundle/BundleJSON.java
+++ b/src/main/java/htsjdk/beta/io/bundle/BundleJSON.java
@@ -4,10 +4,6 @@
import htsjdk.io.IOPath;
import htsjdk.samtools.util.Log;
import htsjdk.utils.ValidationUtils;
-import org.json.JSONArray;
-import org.json.JSONException;
-import org.json.JSONObject;
-
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@@ -15,8 +11,11 @@
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
-//TODO: Once the schema is finalized, we need to bump the version # to 1.0, and publish it.
+// TODO: Once the schema is finalized, we need to bump the version # to 1.0, and publish it.
/**
* Methods for serializing and deserializing Bundles to and from JSON strings.
@@ -25,17 +24,17 @@ public class BundleJSON {
public static final String BUNDLE_EXTENSION = ".json";
private static final Log LOG = Log.getInstance(BundleJSON.class);
- public static final String JSON_PROPERTY_SCHEMA = "schema";
- public static final String JSON_PROPERTY_SCHEMA_NAME = "schemaName";
- public static final String JSON_PROPERTY_SCHEMA_VERSION = "schemaVersion";
- public static final String JSON_PROPERTY_PRIMARY = "primary";
- public static final String JSON_PROPERTY_PATH = "path";
- public static final String JSON_PROPERTY_FORMAT = "format";
+ public static final String JSON_PROPERTY_SCHEMA = "schema";
+ public static final String JSON_PROPERTY_SCHEMA_NAME = "schemaName";
+ public static final String JSON_PROPERTY_SCHEMA_VERSION = "schemaVersion";
+ public static final String JSON_PROPERTY_PRIMARY = "primary";
+ public static final String JSON_PROPERTY_PATH = "path";
+ public static final String JSON_PROPERTY_FORMAT = "format";
- public static final String JSON_SCHEMA_NAME = "htsbundle";
- public static final String JSON_SCHEMA_VERSION = "0.1.0"; // TODO: bump this to 1.0.0
+ public static final String JSON_SCHEMA_NAME = "htsbundle";
+ public static final String JSON_SCHEMA_VERSION = "0.1.0"; // TODO: bump this to 1.0.0
- final private static Set TOP_LEVEL_PROPERTIES = Set.of(JSON_PROPERTY_SCHEMA, JSON_PROPERTY_PRIMARY);
+ private static final Set TOP_LEVEL_PROPERTIES = Set.of(JSON_PROPERTY_SCHEMA, JSON_PROPERTY_PRIMARY);
/**
* Serialize a bundle to a JSON string representation. All resources in the bundle must
@@ -53,8 +52,8 @@ public static String toJSON(final Bundle bundle) {
.put(JSON_PROPERTY_SCHEMA_NAME, JSON_SCHEMA_NAME)
.put(JSON_PROPERTY_SCHEMA_VERSION, JSON_SCHEMA_VERSION);
final JSONObject outerJSON = new JSONObject()
- .put(JSON_PROPERTY_SCHEMA, schemaMap)
- .put(JSON_PROPERTY_PRIMARY, bundle.getPrimaryContentType());
+ .put(JSON_PROPERTY_SCHEMA, schemaMap)
+ .put(JSON_PROPERTY_PRIMARY, bundle.getPrimaryContentType());
bundle.forEach(bundleResource -> {
final Optional resourcePath = bundleResource.getIOPath();
@@ -63,9 +62,11 @@ public static String toJSON(final Bundle bundle) {
}
// generate JSON for each bundle resource
- final JSONObject resourceJSON = new JSONObject().put(JSON_PROPERTY_PATH, resourcePath.get().getURIString());
+ final JSONObject resourceJSON =
+ new JSONObject().put(JSON_PROPERTY_PATH, resourcePath.get().getURIString());
if (bundleResource.getFileFormat().isPresent()) {
- resourceJSON.put(JSON_PROPERTY_FORMAT, bundleResource.getFileFormat().get());
+ resourceJSON.put(
+ JSON_PROPERTY_FORMAT, bundleResource.getFileFormat().get());
}
outerJSON.put(bundleResource.getContentType(), resourceJSON);
});
@@ -83,21 +84,19 @@ public static String toJSON(final List bundles) {
if (bundles.isEmpty()) {
throw new IllegalArgumentException("A bundle list must contain at least one bundle");
}
- return bundles.stream()
- .map(BundleJSON::toJSON)
- .collect(Collectors.joining(",\n", "[", "]"));
+ return bundles.stream().map(BundleJSON::toJSON).collect(Collectors.joining(",\n", "[", "]"));
}
- /**
- * Create a Bundle from a jsonString.
- *
- * @param jsonString a valid JSON string conforming to the bundle schema (for compatibility, a bundle list is also
- * accepted, as long as it only contains a single bundle)
- * @return a {@link Bundle} created from jsonString
- */
- public static Bundle toBundle(final String jsonString) {
+ /**
+ * Create a Bundle from a jsonString.
+ *
+ * @param jsonString a valid JSON string conforming to the bundle schema (for compatibility, a bundle list is also
+ * accepted, as long as it only contains a single bundle)
+ * @return a {@link Bundle} created from jsonString
+ */
+ public static Bundle toBundle(final String jsonString) {
return toBundle(ValidationUtils.nonEmpty(jsonString, "resource list"), HtsPath::new);
- }
+ }
/**
* Create a Bundle from jsonString using a custom class that implements {@link IOPath} for all resources.
@@ -109,8 +108,7 @@ public static Bundle toBundle(final String jsonString) {
* @return a newly created {@link Bundle}
*/
public static Bundle toBundle(
- final String jsonString,
- final Function ioPathConstructor) {
+ final String jsonString, final Function ioPathConstructor) {
ValidationUtils.nonEmpty(jsonString, "JSON string");
ValidationUtils.nonNull(ioPathConstructor, "IOPath-derived class constructor");
try {
@@ -121,16 +119,16 @@ public static Bundle toBundle(
try {
final List bundles = toBundleList(jsonString, ioPathConstructor);
if (bundles.size() > 1) {
- throw new IllegalArgumentException(
- String.format("A JSON string with more than one bundle was provided but only a single bundle is allowed in this context (%s)",
- e.getMessage()));
+ throw new IllegalArgumentException(String.format(
+ "A JSON string with more than one bundle was provided but only a single bundle is allowed in this context (%s)",
+ e.getMessage()));
}
return bundles.get(0);
} catch (JSONException | UnsupportedOperationException e2) {
throw new IllegalArgumentException(
- String.format("The JSON can be interpreted neither as an individual bundle (%s) nor as a bundle collection (%s)",
- e.getMessage(),
- e2.getMessage()),
+ String.format(
+ "The JSON can be interpreted neither as an individual bundle (%s) nor as a bundle collection (%s)",
+ e.getMessage(), e2.getMessage()),
e);
}
}
@@ -145,8 +143,7 @@ public static Bundle toBundle(
* @param IOPath-derived class to use for IOPathResources
*/
public static List toBundleList(
- final String jsonString,
- final Function ioPathConstructor) {
+ final String jsonString, final Function ioPathConstructor) {
ValidationUtils.nonEmpty(jsonString, "json bundle string");
ValidationUtils.nonNull(ioPathConstructor, "IOPath-derived class constructor");
@@ -154,10 +151,9 @@ public static List toBundleList(
try {
final JSONArray jsonArray = new JSONArray(jsonString);
jsonArray.forEach(element -> {
- if (! (element instanceof JSONObject jsonObject)) {
- throw new IllegalArgumentException(
- String.format("Bundle collections may contain only Bundle objects, found %s",
- element.toString()));
+ if (!(element instanceof JSONObject jsonObject)) {
+ throw new IllegalArgumentException(String.format(
+ "Bundle collections may contain only Bundle objects, found %s", element.toString()));
}
bundles.add(toBundle(jsonObject, ioPathConstructor));
});
@@ -167,9 +163,9 @@ public static List toBundleList(
bundles.add(toBundle(new JSONObject(jsonString), ioPathConstructor));
} catch (JSONException | UnsupportedOperationException e2) {
throw new IllegalArgumentException(
- String.format("JSON can be interpreted neither as an individual bundle (%s) nor as a bundle collection (%s)",
- e2.getMessage(),
- e.getMessage()),
+ String.format(
+ "JSON can be interpreted neither as an individual bundle (%s) nor as a bundle collection (%s)",
+ e2.getMessage(), e.getMessage()),
e);
}
}
@@ -205,8 +201,8 @@ private static Bundle toBundle(
}
final String schemaVersion = getRequiredPropertyAsString(schemaMap, JSON_PROPERTY_SCHEMA_VERSION);
if (!schemaVersion.equals(JSON_SCHEMA_VERSION)) {
- throw new IllegalArgumentException(String.format("Expected bundle schema version %s but found %s",
- JSON_SCHEMA_VERSION, schemaVersion));
+ throw new IllegalArgumentException(String.format(
+ "Expected bundle schema version %s but found %s", JSON_SCHEMA_VERSION, schemaVersion));
}
final String primaryContentType = getRequiredPropertyAsString(jsonObject, JSON_PROPERTY_PRIMARY);
@@ -216,19 +212,18 @@ private static Bundle toBundle(
throw new IllegalArgumentException(e);
}
}
+
private static IOPathResource toBundleResource(
- final String contentType,
- final JSONObject jsonObject,
- final Function ioPathConstructor) {
+ final String contentType, final JSONObject jsonObject, final Function ioPathConstructor) {
final String format = jsonObject.optString(JSON_PROPERTY_FORMAT, null);
return new IOPathResource(
ioPathConstructor.apply(getRequiredPropertyAsString(jsonObject, JSON_PROPERTY_PATH)),
contentType,
format);
}
+
private static Collection toBundleResources(
- final JSONObject jsonResources,
- final Function ioPathConstructor) {
+ final JSONObject jsonResources, final Function ioPathConstructor) {
final List bundleResources = new ArrayList<>(); // default capacity of 10 seems right
jsonResources.keySet().forEach(key -> {
@@ -248,9 +243,7 @@ private static String getRequiredPropertyAsString(final JSONObject jsonDocument,
final String propertyValue = jsonDocument.optString(propertyName, null);
if (propertyValue == null) {
throw new IllegalArgumentException(
- String.format("JSON bundle is missing the required property %s (%s)",
- propertyName,
- jsonDocument));
+ String.format("JSON bundle is missing the required property %s (%s)", propertyName, jsonDocument));
}
return propertyValue;
diff --git a/src/main/java/htsjdk/beta/io/bundle/BundleResource.java b/src/main/java/htsjdk/beta/io/bundle/BundleResource.java
index 2eb610cb0e..b281b4fe56 100644
--- a/src/main/java/htsjdk/beta/io/bundle/BundleResource.java
+++ b/src/main/java/htsjdk/beta/io/bundle/BundleResource.java
@@ -2,7 +2,6 @@
import htsjdk.io.IOPath;
import htsjdk.samtools.seekablestream.SeekableStream;
-
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Optional;
@@ -130,5 +129,4 @@ public interface BundleResource {
* @return true if this resource can be rendered as a {@link SeekableStream} (see {@link #getSeekableStream})
*/
boolean hasSeekableStream();
-
}
diff --git a/src/main/java/htsjdk/beta/io/bundle/BundleResourceBase.java b/src/main/java/htsjdk/beta/io/bundle/BundleResourceBase.java
index dacf766f5b..500aab3d34 100644
--- a/src/main/java/htsjdk/beta/io/bundle/BundleResourceBase.java
+++ b/src/main/java/htsjdk/beta/io/bundle/BundleResourceBase.java
@@ -3,7 +3,6 @@
import htsjdk.io.IOPath;
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.utils.ValidationUtils;
-
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
@@ -29,10 +28,7 @@ public abstract class BundleResourceBase implements BundleResource, Serializable
* a resource with content type "READS". Predefined format strings are defined
* in {@link BundleResourceType}.
*/
- public BundleResourceBase(
- final String displayName,
- final String contentType,
- final String format) {
+ public BundleResourceBase(final String displayName, final String contentType, final String format) {
ValidationUtils.nonEmpty(displayName, "display name");
ValidationUtils.nonEmpty(contentType, "content type");
this.displayName = displayName;
@@ -41,7 +37,9 @@ public BundleResourceBase(
}
@Override
- public String getDisplayName() { return displayName; }
+ public String getDisplayName() {
+ return displayName;
+ }
@Override
public String getContentType() {
@@ -54,25 +52,39 @@ public Optional getFileFormat() {
}
@Override
- public Optional getIOPath() { return Optional.empty(); }
+ public Optional getIOPath() {
+ return Optional.empty();
+ }
@Override
- public Optional getInputStream() { return Optional.empty(); }
+ public Optional getInputStream() {
+ return Optional.empty();
+ }
@Override
- public Optional getOutputStream() { return Optional.empty(); }
+ public Optional getOutputStream() {
+ return Optional.empty();
+ }
@Override
- public Optional getSeekableStream() { return Optional.empty(); }
+ public Optional getSeekableStream() {
+ return Optional.empty();
+ }
@Override
- public boolean hasSeekableStream() { return false; }
+ public boolean hasSeekableStream() {
+ return false;
+ }
@Override
- public boolean hasInputType() { return false; }
+ public boolean hasInputType() {
+ return false;
+ }
@Override
- public boolean hasOutputType() { return false; }
+ public boolean hasOutputType() {
+ return false;
+ }
@Override
public String toString() {
diff --git a/src/main/java/htsjdk/beta/io/bundle/BundleResourceType.java b/src/main/java/htsjdk/beta/io/bundle/BundleResourceType.java
index d083b06107..83f0d07a5e 100644
--- a/src/main/java/htsjdk/beta/io/bundle/BundleResourceType.java
+++ b/src/main/java/htsjdk/beta/io/bundle/BundleResourceType.java
@@ -1,6 +1,5 @@
package htsjdk.beta.io.bundle;
-import htsjdk.beta.plugin.HtsContentType;
import htsjdk.beta.plugin.reads.ReadsFormats;
import htsjdk.beta.plugin.variants.VariantsFormats;
@@ -26,6 +25,7 @@ public class BundleResourceType {
/**************************************** Common primary content types ******************************************/
public static final String CT_ALIGNED_READS = "ALIGNED_READS";
+
public static final String CT_VARIANT_CONTEXTS = "VARIANT_CONTEXTS";
public static final String CT_HAPLOID_REFERENCE = "HAPLOID_REFERENCE";
public static final String CT_FEATURES = "FEATURES";
@@ -33,6 +33,7 @@ public class BundleResourceType {
/****************************************** Resource types for READS ********************************************/
/** Formats for primary content type {@link BundleResourceType#CT_ALIGNED_READS} */
public static final String FMT_READS_SAM = ReadsFormats.SAM;
+
public static final String FMT_READS_BAM = ReadsFormats.BAM;
public static final String FMT_READS_CRAM = ReadsFormats.CRAM;
public static final String FMT_READS_HTSGET_BAM = ReadsFormats.HTSGET_BAM;
@@ -41,12 +42,14 @@ public class BundleResourceType {
public static final String CT_READS_INDEX = "READS_INDEX";
/** Formats for secondary content type {@link BundleResourceType#CT_READS_INDEX} resources */
public static final String FMT_READS_INDEX_BAI = "BAI";
+
public static final String FMT_READS_INDEX_CRAI = "CRAI";
public static final String FMT_READS_INDEX_CSI = "CSI";
/****************************************** Resource types for VARIANTS ******************************************/
/** Format names for content type {@link BundleResourceType#CT_VARIANT_CONTEXTS} */
public static final String FMT_VARIANTS_VCF = VariantsFormats.VCF;
+
public static final String FMT_VARIANTS_BCF = VariantsFormats.BCF;
/** Secondary content types for primary content type {@link #CT_VARIANT_CONTEXTS} resources */
@@ -55,14 +58,12 @@ public class BundleResourceType {
/****************************************** Resource types for HAPLOID REFERENCES ********************************/
/** Secondary content types for {@link BundleResourceType#CT_HAPLOID_REFERENCE} resources*/
public static final String CT_REFERENCE_DICTIONARY = "REFERENCE_DICTIONARY";
+
public static final String CT_REFERENCE_INDEX = "REFERENCE_INDEX";
public static final String CT_REFERENCE_INDEX_GZI = "REFERENCE_INDEX_GZI";
-
/****************************************** Resource types for FEATURES ********************************/
-
/****************************************** MISCELLANEOUS Resource types ********************************/
public static final String CT_MD5 = "MD5";
-
}
diff --git a/src/main/java/htsjdk/beta/io/bundle/IOPathResource.java b/src/main/java/htsjdk/beta/io/bundle/IOPathResource.java
index be200942a4..580f8bbde4 100644
--- a/src/main/java/htsjdk/beta/io/bundle/IOPathResource.java
+++ b/src/main/java/htsjdk/beta/io/bundle/IOPathResource.java
@@ -5,7 +5,6 @@
import htsjdk.samtools.seekablestream.SeekablePathStream;
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -31,20 +30,20 @@ public IOPathResource(final IOPath ioPath, final String contentType) {
/**
* Create a {@link BundleResource} backed by an IOPath, specifying a content type string and format string.
-
+ *
* @param ioPath The IOPath for this resource. May not be null.
* @param contentType The content type for this resource. May not be mull or 0-length.
* @param format The format for this resource. May not be null or 0-length.
*/
public IOPathResource(final IOPath ioPath, final String contentType, final String format) {
- super(ValidationUtils.nonNull(ioPath, "ioPath").getRawInputString(),
- contentType,
- format);
+ super(ValidationUtils.nonNull(ioPath, "ioPath").getRawInputString(), contentType, format);
this.ioPath = ioPath;
}
@Override
- public Optional getIOPath() { return Optional.of(ioPath); }
+ public Optional getIOPath() {
+ return Optional.of(ioPath);
+ }
/**
* {@inheritDoc}
@@ -59,13 +58,19 @@ public Optional getInputStream() {
}
@Override
- public Optional getOutputStream() { return Optional.of(ioPath.getOutputStream()); }
+ public Optional getOutputStream() {
+ return Optional.of(ioPath.getOutputStream());
+ }
@Override
- public boolean hasInputType() { return true; }
+ public boolean hasInputType() {
+ return true;
+ }
@Override
- public boolean hasOutputType() { return true; }
+ public boolean hasOutputType() {
+ return true;
+ }
@Override
public boolean hasSeekableStream() {
@@ -119,5 +124,4 @@ public int hashCode() {
result = 31 * result + ioPath.hashCode();
return result;
}
-
}
diff --git a/src/main/java/htsjdk/beta/io/bundle/InputStreamResource.java b/src/main/java/htsjdk/beta/io/bundle/InputStreamResource.java
index 2bde148b22..b86158c2c7 100644
--- a/src/main/java/htsjdk/beta/io/bundle/InputStreamResource.java
+++ b/src/main/java/htsjdk/beta/io/bundle/InputStreamResource.java
@@ -2,7 +2,6 @@
import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.utils.ValidationUtils;
-
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
@@ -13,9 +12,9 @@
*/
public class InputStreamResource extends BundleResourceBase {
private static final long serialVersionUID = 1L;
- private static final int MINIMUM_STREAM_BUFFER_SIZE = 64*1024;
- private final InputStream rawInputStream; // the stream as provided by the caller
- private BufferedInputStream bufferedInputStream; // buffered stream wrapper to compensate for signature probing
+ private static final int MINIMUM_STREAM_BUFFER_SIZE = 64 * 1024;
+ private final InputStream rawInputStream; // the stream as provided by the caller
+ private BufferedInputStream bufferedInputStream; // buffered stream wrapper to compensate for signature probing
/**
* Create a {@link BundleResource} backed by an InputStream.
@@ -44,10 +43,7 @@ public InputStreamResource(final InputStream inputStream, final String displayNa
* @param format The format for this resource. May not be null or 0-length.
*/
public InputStreamResource(
- final InputStream inputStream,
- final String displayName,
- final String contentType,
- final String format) {
+ final InputStream inputStream, final String displayName, final String contentType, final String format) {
super(displayName, contentType, format);
ValidationUtils.nonNull(inputStream, "input stream");
this.rawInputStream = inputStream;
@@ -76,14 +72,14 @@ public SignatureStream getSignatureStream(final int signatureProbeLength) {
// is ultimately consumed once signature probing is complete, it will be consumed from the
// beginning.
bufferedInputStream = new BufferedInputStream(
- rawInputStream,
- Integer.max(signatureProbeLength, MINIMUM_STREAM_BUFFER_SIZE));
+ rawInputStream, Integer.max(signatureProbeLength, MINIMUM_STREAM_BUFFER_SIZE));
bufferedInputStream.mark(signatureProbeLength);
bufferedInputStream.read(signaturePrefix);
bufferedInputStream.reset();
} catch (final IOException e) {
throw new HtsjdkIOException(
- String.format("Error during signature probing on %s with prefix size %d",
+ String.format(
+ "Error during signature probing on %s with prefix size %d",
this.getDisplayName(), signatureProbeLength),
e);
}
@@ -91,7 +87,9 @@ public SignatureStream getSignatureStream(final int signatureProbeLength) {
}
@Override
- public boolean hasInputType() { return true; }
+ public boolean hasInputType() {
+ return true;
+ }
@Override
public boolean equals(Object o) {
diff --git a/src/main/java/htsjdk/beta/io/bundle/OutputStreamResource.java b/src/main/java/htsjdk/beta/io/bundle/OutputStreamResource.java
index 56fa46ca22..d176f74ddd 100644
--- a/src/main/java/htsjdk/beta/io/bundle/OutputStreamResource.java
+++ b/src/main/java/htsjdk/beta/io/bundle/OutputStreamResource.java
@@ -2,7 +2,6 @@
import htsjdk.beta.exception.HtsjdkException;
import htsjdk.utils.ValidationUtils;
-
import java.io.OutputStream;
import java.util.Optional;
@@ -33,10 +32,7 @@ public OutputStreamResource(final OutputStream outputStream, final String displa
* @param format The format for this resource. May not be null or 0-length.
*/
public OutputStreamResource(
- final OutputStream outputStream,
- final String displayName,
- final String contentType,
- final String format) {
+ final OutputStream outputStream, final String displayName, final String contentType, final String format) {
super(displayName, contentType, format);
ValidationUtils.nonNull(outputStream, "output stream");
this.outputStream = outputStream;
@@ -54,7 +50,9 @@ public SignatureStream getSignatureStream(int signatureProbeLength) {
}
@Override
- public boolean hasOutputType() { return true; }
+ public boolean hasOutputType() {
+ return true;
+ }
@Override
public boolean equals(Object o) {
diff --git a/src/main/java/htsjdk/beta/io/bundle/SeekableStreamResource.java b/src/main/java/htsjdk/beta/io/bundle/SeekableStreamResource.java
index 642f53f572..5c9fe39748 100644
--- a/src/main/java/htsjdk/beta/io/bundle/SeekableStreamResource.java
+++ b/src/main/java/htsjdk/beta/io/bundle/SeekableStreamResource.java
@@ -3,7 +3,6 @@
import htsjdk.beta.exception.HtsjdkIOException;
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
@@ -23,7 +22,8 @@ public class SeekableStreamResource extends InputStreamResource {
* @param displayName The display name for this resource. May not be null or 0-length.
* @param contentType The content type for this resource. May not be null or 0-length.
*/
- public SeekableStreamResource(final SeekableStream seekableStream, final String displayName, final String contentType) {
+ public SeekableStreamResource(
+ final SeekableStream seekableStream, final String displayName, final String contentType) {
this(seekableStream, displayName, contentType, null);
}
@@ -59,7 +59,9 @@ public Optional getInputStream() {
}
@Override
- public Optional getSeekableStream() { return Optional.of(seekableStream); }
+ public Optional getSeekableStream() {
+ return Optional.of(seekableStream);
+ }
/**
* {@inheritDoc}
@@ -69,7 +71,7 @@ public Optional getInputStream() {
*/
@Override
public SignatureStream getSignatureStream(final int signatureProbeLength) {
- //we don't want to call the super class' implementation here
+ // we don't want to call the super class' implementation here
final byte[] signaturePrefix = new byte[signatureProbeLength];
try {
// for a SeekableStreamResource, we don't want this code to close the actual SeekableStream that
@@ -81,19 +83,23 @@ public SignatureStream getSignatureStream(final int signatureProbeLength) {
seekableStream.seek(0);
} catch (final IOException e) {
throw new HtsjdkIOException(
- String.format("Error creating signature probe for seekable stream resource with prefix size %d",
+ String.format(
+ "Error creating signature probe for seekable stream resource with prefix size %d",
signatureProbeLength),
e);
}
return new SignatureStream(signatureProbeLength, signaturePrefix);
-
}
@Override
- public boolean hasInputType() { return true; }
+ public boolean hasInputType() {
+ return true;
+ }
@Override
- public boolean hasSeekableStream() { return true; }
+ public boolean hasSeekableStream() {
+ return true;
+ }
@Override
public boolean equals(Object o) {
diff --git a/src/main/java/htsjdk/beta/io/bundle/SignatureStream.java b/src/main/java/htsjdk/beta/io/bundle/SignatureStream.java
index 4feaa88433..32a631a7fd 100644
--- a/src/main/java/htsjdk/beta/io/bundle/SignatureStream.java
+++ b/src/main/java/htsjdk/beta/io/bundle/SignatureStream.java
@@ -32,6 +32,7 @@ public SignatureStream(final int signaturePrefixLength, final byte[] signaturePr
*
* @return the maximum number of bytes that can be consumed from this stream.
*/
- public final int getSignaturePrefixLength() { return signaturePrefixLength;}
-
+ public final int getSignaturePrefixLength() {
+ return signaturePrefixLength;
+ }
}
diff --git a/src/main/java/htsjdk/beta/package-info.java b/src/main/java/htsjdk/beta/package-info.java
index 181e0e1c1b..a039f8ef0d 100644
--- a/src/main/java/htsjdk/beta/package-info.java
+++ b/src/main/java/htsjdk/beta/package-info.java
@@ -9,5 +9,3 @@
* {@link htsjdk.annotations.BetaAPI}. Subpackages may be subsequently released as part of the public API,
* at which time they will be moved out of the {@link htsjdk.beta} package.
*/
-
-
diff --git a/src/main/java/htsjdk/beta/plugin/HtsCodec.java b/src/main/java/htsjdk/beta/plugin/HtsCodec.java
index a128fc19b8..4bfa33e36e 100644
--- a/src/main/java/htsjdk/beta/plugin/HtsCodec.java
+++ b/src/main/java/htsjdk/beta/plugin/HtsCodec.java
@@ -1,12 +1,12 @@
package htsjdk.beta.plugin;
+import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResource;
import htsjdk.beta.io.bundle.BundleResourceType;
import htsjdk.beta.io.bundle.SignatureStream;
import htsjdk.beta.plugin.reads.ReadsFormats;
import htsjdk.beta.plugin.registry.HtsCodecRegistry;
import htsjdk.io.IOPath;
-import htsjdk.beta.io.bundle.Bundle;
/**
* Base interface implemented by all {@link htsjdk.beta.plugin} codecs.
@@ -221,7 +221,8 @@ public interface HtsCodecioPath (obtained via {@link IOPath#getURI()})
@@ -362,7 +365,9 @@ default String getDisplayName() {
* may throw exceptions.
*
*/
- default int getSignatureProbeLength() { return getSignatureLength(); }
+ default int getSignatureProbeLength() {
+ return getSignatureLength();
+ }
/**
* Get an {@link HtsDecoder} to decode the provided inputs. The input bundle must contain
@@ -397,5 +402,4 @@ default String getDisplayName() {
* @return an {@link HtsEncoder} suitable for writing to the provided outputs
*/
HtsEncoder, ? extends HtsRecord> getEncoder(final Bundle outputBundle, final E encoderOptions);
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/HtsContentType.java b/src/main/java/htsjdk/beta/plugin/HtsContentType.java
index abe4312fd7..fb0dbfa6fb 100644
--- a/src/main/java/htsjdk/beta/plugin/HtsContentType.java
+++ b/src/main/java/htsjdk/beta/plugin/HtsContentType.java
@@ -26,7 +26,7 @@
*/
public enum HtsContentType {
- //where would a FASTQ codec fit ? in the same category (which implies the same interfaces) ?
+ // where would a FASTQ codec fit ? in the same category (which implies the same interfaces) ?
/**
* Haploid reference content type (see {@link HaploidReferenceFormats} for related formats)
*/
diff --git a/src/main/java/htsjdk/beta/plugin/HtsDecoder.java b/src/main/java/htsjdk/beta/plugin/HtsDecoder.java
index 4040f1ce3a..b5d4693a66 100644
--- a/src/main/java/htsjdk/beta/plugin/HtsDecoder.java
+++ b/src/main/java/htsjdk/beta/plugin/HtsDecoder.java
@@ -15,8 +15,7 @@
* @param type param for the header for this format (i.e. SAMFileHeader)
* @param type param for the record for this format (i.e. SAMRecord)
*/
-public interface HtsDecoder
- extends HtsQuery, Closeable {
+public interface HtsDecoder extends HtsQuery, Closeable {
/**
* Get the name of the file format supported by this decoder.The format name defines the underlying
@@ -52,5 +51,4 @@ public interface HtsDecoder
*/
@Override
void close();
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/HtsDecoderOptions.java b/src/main/java/htsjdk/beta/plugin/HtsDecoderOptions.java
index cb4ae04d53..ab4f686dad 100644
--- a/src/main/java/htsjdk/beta/plugin/HtsDecoderOptions.java
+++ b/src/main/java/htsjdk/beta/plugin/HtsDecoderOptions.java
@@ -3,5 +3,4 @@
/**
* Base tag interface for options for {@link HtsDecoder}s.
*/
-public interface HtsDecoderOptions {
-}
+public interface HtsDecoderOptions {}
diff --git a/src/main/java/htsjdk/beta/plugin/HtsEncoder.java b/src/main/java/htsjdk/beta/plugin/HtsEncoder.java
index 824dfcfc79..c8cb9d17cb 100644
--- a/src/main/java/htsjdk/beta/plugin/HtsEncoder.java
+++ b/src/main/java/htsjdk/beta/plugin/HtsEncoder.java
@@ -2,7 +2,6 @@
import htsjdk.beta.io.bundle.BundleResource;
import htsjdk.beta.io.bundle.BundleResourceType;
-
import java.io.Closeable;
/**
@@ -56,5 +55,4 @@ public interface HtsEncoder extends Cl
*/
@Override
void close();
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/HtsEncoderOptions.java b/src/main/java/htsjdk/beta/plugin/HtsEncoderOptions.java
index 6067aaaafd..093ab3fb92 100644
--- a/src/main/java/htsjdk/beta/plugin/HtsEncoderOptions.java
+++ b/src/main/java/htsjdk/beta/plugin/HtsEncoderOptions.java
@@ -3,5 +3,4 @@
/**
* Base tag interface for options for {@link HtsEncoder}s.
*/
-public interface HtsEncoderOptions {
-}
+public interface HtsEncoderOptions {}
diff --git a/src/main/java/htsjdk/beta/plugin/HtsHeader.java b/src/main/java/htsjdk/beta/plugin/HtsHeader.java
index 5f93d1153d..c2f6e5a583 100644
--- a/src/main/java/htsjdk/beta/plugin/HtsHeader.java
+++ b/src/main/java/htsjdk/beta/plugin/HtsHeader.java
@@ -1,10 +1,9 @@
package htsjdk.beta.plugin;
-//Note: This is a just a tagging interface used to tag SAMFileHeader, VCFHeader, and SAMSequenceDictionary.
+// Note: This is a just a tagging interface used to tag SAMFileHeader, VCFHeader, and SAMSequenceDictionary.
// It will be more useful once version upgrading is implemented.
/**
* Tagging interface used as a type-bound for codec/encoder/decoder header type params.
*/
-public interface HtsHeader {
-}
+public interface HtsHeader {}
diff --git a/src/main/java/htsjdk/beta/plugin/HtsRecord.java b/src/main/java/htsjdk/beta/plugin/HtsRecord.java
index fe5cc0c31c..5b2d7ae094 100644
--- a/src/main/java/htsjdk/beta/plugin/HtsRecord.java
+++ b/src/main/java/htsjdk/beta/plugin/HtsRecord.java
@@ -1,11 +1,10 @@
package htsjdk.beta.plugin;
-//Note: This is a tagging interface currently used as a type-bound for codec/encoder/decoder
+// Note: This is a tagging interface currently used as a type-bound for codec/encoder/decoder
// record type params, and used to tag SAMRecord, BAMRecord, VariantContext, and ReferenceSequence.
// It will be more useful once version upgrading is implemented.
/**
* Tagging interface used as a type-bound for codec/encoder/decoder record type params.
*/
-public interface HtsRecord {
-}
+public interface HtsRecord {}
diff --git a/src/main/java/htsjdk/beta/plugin/HtsVersion.java b/src/main/java/htsjdk/beta/plugin/HtsVersion.java
index e93e325bb9..31e200ee94 100644
--- a/src/main/java/htsjdk/beta/plugin/HtsVersion.java
+++ b/src/main/java/htsjdk/beta/plugin/HtsVersion.java
@@ -40,7 +40,8 @@ public HtsVersion(final String versionString) {
ValidationUtils.nonNull(versionString);
final String[] parts = versionString.split("\\.");
if (parts.length != 3) {
- throw new IllegalArgumentException(String.format("Unable parse version string as major.minor.patch: '%s'", versionString));
+ throw new IllegalArgumentException(
+ String.format("Unable parse version string as major.minor.patch: '%s'", versionString));
}
try {
majorVersion = Integer.parseInt(parts[0]);
@@ -108,7 +109,7 @@ public int compareTo(HtsVersion o) {
ValidationUtils.nonNull(o);
if (this.majorVersion == o.majorVersion) {
if (this.minorVersion == o.minorVersion) {
- if (this.patchVersion == o.patchVersion){
+ if (this.patchVersion == o.patchVersion) {
return 0;
}
return this.patchVersion - o.patchVersion;
diff --git a/src/main/java/htsjdk/beta/plugin/IOUtils.java b/src/main/java/htsjdk/beta/plugin/IOUtils.java
index d2512cac93..e6b052b6c8 100644
--- a/src/main/java/htsjdk/beta/plugin/IOUtils.java
+++ b/src/main/java/htsjdk/beta/plugin/IOUtils.java
@@ -4,7 +4,6 @@
import htsjdk.io.HtsPath;
import htsjdk.io.IOPath;
import htsjdk.samtools.util.BlockCompressedOutputStream;
-
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
@@ -42,7 +41,7 @@ public static IOPath createTempPath(final String prefix, final String suffix) {
* @param toConvert Path to convert to GATKPath
* @return a Path, or null if the input was null.
*/
- public static HtsPath toHtsPath(Path toConvert){
+ public static HtsPath toHtsPath(Path toConvert) {
return null == toConvert ? null : new HtsPath(toConvert.toUri().toString());
}
@@ -55,17 +54,15 @@ public static HtsPath toHtsPath(Path toConvert){
public static String getStringFromPath(final IOPath ioPath) {
try {
final StringWriter stringWriter = new StringWriter();
- //TODO: the UTF-8 encoding of these should be codified somewhere else...
- Files.lines(ioPath.toPath(), StandardCharsets.UTF_8).forEach(
- line -> {
- stringWriter.write(line);
- stringWriter.append("\n");
- });
+ // TODO: the UTF-8 encoding of these should be codified somewhere else...
+ Files.lines(ioPath.toPath(), StandardCharsets.UTF_8).forEach(line -> {
+ stringWriter.write(line);
+ stringWriter.append("\n");
+ });
return stringWriter.toString();
} catch (final IOException e) {
throw new HtsjdkIOException(
- String.format("Failed to load reads bundle json from: %s", ioPath.getRawInputString()),
- e);
+ String.format("Failed to load reads bundle json from: %s", ioPath.getRawInputString()), e);
}
}
@@ -77,21 +74,21 @@ public static String getStringFromPath(final IOPath ioPath) {
* @param gzipOutput if true, gzip output
*/
public static void writeStringToPath(final IOPath ioPath, final String contents, final boolean gzipOutput) {
- if (gzipOutput) {
- try (final BufferedOutputStream bos = new BufferedOutputStream(ioPath.getOutputStream());
- final BlockCompressedOutputStream bcos = new BlockCompressedOutputStream(bos, ioPath.toPath())) {
- bcos.write(contents.getBytes());
- } catch (final IOException e) {
- throw new HtsjdkIOException(
- String.format("Failed to load reads bundle json from: %s", ioPath.getRawInputString()), e);
- }
- } else {
- try (final BufferedOutputStream bos = new BufferedOutputStream(ioPath.getOutputStream())) {
- bos.write(contents.getBytes());
- } catch (final IOException e) {
- throw new HtsjdkIOException(
- String.format("Failed to load reads bundle json from: %s", ioPath.getRawInputString()), e);
- }
- }
+ if (gzipOutput) {
+ try (final BufferedOutputStream bos = new BufferedOutputStream(ioPath.getOutputStream());
+ final BlockCompressedOutputStream bcos = new BlockCompressedOutputStream(bos, ioPath.toPath())) {
+ bcos.write(contents.getBytes());
+ } catch (final IOException e) {
+ throw new HtsjdkIOException(
+ String.format("Failed to load reads bundle json from: %s", ioPath.getRawInputString()), e);
+ }
+ } else {
+ try (final BufferedOutputStream bos = new BufferedOutputStream(ioPath.getOutputStream())) {
+ bos.write(contents.getBytes());
+ } catch (final IOException e) {
+ throw new HtsjdkIOException(
+ String.format("Failed to load reads bundle json from: %s", ioPath.getRawInputString()), e);
+ }
+ }
}
}
diff --git a/src/main/java/htsjdk/beta/plugin/hapref/HapRefDecoderOptions.java b/src/main/java/htsjdk/beta/plugin/hapref/HapRefDecoderOptions.java
index 363264f067..0b2294654f 100644
--- a/src/main/java/htsjdk/beta/plugin/hapref/HapRefDecoderOptions.java
+++ b/src/main/java/htsjdk/beta/plugin/hapref/HapRefDecoderOptions.java
@@ -5,5 +5,4 @@
/**
* Class for haploid reference decoder options.
*/
-public class HapRefDecoderOptions implements HtsDecoderOptions {
-}
+public class HapRefDecoderOptions implements HtsDecoderOptions {}
diff --git a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceCodec.java b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceCodec.java
index 25b49a3ac0..7bac69149b 100644
--- a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceCodec.java
+++ b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceCodec.java
@@ -6,11 +6,11 @@
/**
* Base class for all {@link HtsContentType#HAPLOID_REFERENCE} codecs.
*/
-public interface HaploidReferenceCodec extends HtsCodec<
- HaploidReferenceDecoderOptions,
- HaploidReferenceEncoderOptions> {
+public interface HaploidReferenceCodec
+ extends HtsCodec {
@Override
- default HtsContentType getContentType() { return HtsContentType.HAPLOID_REFERENCE; }
-
+ default HtsContentType getContentType() {
+ return HtsContentType.HAPLOID_REFERENCE;
+ }
}
diff --git a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceDecoder.java b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceDecoder.java
index 0836ca8c06..9fcf79c411 100644
--- a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceDecoder.java
+++ b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceDecoder.java
@@ -8,4 +8,4 @@
/**
* Base class for all {@link HtsContentType#HAPLOID_REFERENCE} decoders.
*/
-public interface HaploidReferenceDecoder extends HtsDecoder { }
+public interface HaploidReferenceDecoder extends HtsDecoder {}
diff --git a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceDecoderOptions.java b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceDecoderOptions.java
index 6c402f22a2..c2c5170047 100644
--- a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceDecoderOptions.java
+++ b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceDecoderOptions.java
@@ -5,5 +5,4 @@
/**
* Class for haploid reference decoder options.
*/
-public class HaploidReferenceDecoderOptions implements HtsDecoderOptions {
-}
+public class HaploidReferenceDecoderOptions implements HtsDecoderOptions {}
diff --git a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceEncoder.java b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceEncoder.java
index e7eab395cf..fda62cd457 100644
--- a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceEncoder.java
+++ b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceEncoder.java
@@ -8,4 +8,4 @@
/**
* Base class for all {@link HtsContentType#HAPLOID_REFERENCE} encoders.
*/
-public interface HaploidReferenceEncoder extends HtsEncoder { }
+public interface HaploidReferenceEncoder extends HtsEncoder {}
diff --git a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceEncoderOptions.java b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceEncoderOptions.java
index cb2ea05f91..bc2a9115e0 100644
--- a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceEncoderOptions.java
+++ b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceEncoderOptions.java
@@ -5,5 +5,4 @@
/**
* Class for haploid reference encoder options.
*/
-public class HaploidReferenceEncoderOptions implements HtsEncoderOptions {
-}
+public class HaploidReferenceEncoderOptions implements HtsEncoderOptions {}
diff --git a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceFormats.java b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceFormats.java
index 607189b914..aa25ba996a 100644
--- a/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceFormats.java
+++ b/src/main/java/htsjdk/beta/plugin/hapref/HaploidReferenceFormats.java
@@ -9,5 +9,4 @@ public class HaploidReferenceFormats {
* Fasta format
*/
public static final String FASTA = "FASTA";
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/interval/HtsIntervalUtils.java b/src/main/java/htsjdk/beta/plugin/interval/HtsIntervalUtils.java
index 06555055d3..570ae422bb 100644
--- a/src/main/java/htsjdk/beta/plugin/interval/HtsIntervalUtils.java
+++ b/src/main/java/htsjdk/beta/plugin/interval/HtsIntervalUtils.java
@@ -1,16 +1,14 @@
package htsjdk.beta.plugin.interval;
+import htsjdk.annotations.InternalAPI;
import htsjdk.samtools.QueryInterval;
import htsjdk.samtools.SAMSequenceDictionary;
import htsjdk.samtools.util.Locatable;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
-
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
-
/**
* Methods for interconverting between HtsQueryInterval and existing htsjdk types such as Locatable/QueryInterval
*/
@@ -57,9 +55,7 @@ public int getEnd() {
@Override
public String toString() {
- return String.format("%s:%s-%s",
- interval.getQueryName(),
- interval.getStart(), interval.getEnd());
+ return String.format("%s:%s-%s", interval.getQueryName(), interval.getStart(), interval.getEnd());
}
};
}
@@ -73,10 +69,7 @@ public String toString() {
@InternalAPI
public static List toLocatableList(final List intervals) {
ValidationUtils.nonNull(intervals, "interval list");
- return intervals
- .stream()
- .map(si -> toLocatable(si))
- .collect(Collectors.toList());
+ return intervals.stream().map(si -> toLocatable(si)).collect(Collectors.toList());
}
/**
@@ -88,14 +81,13 @@ public static List toLocatableList(final List intervals)
*/
@InternalAPI
public static QueryInterval[] toQueryIntervalArray(
- final List intervals,
- final SAMSequenceDictionary dictionary) {
+ final List intervals, final SAMSequenceDictionary dictionary) {
ValidationUtils.nonNull(intervals, "interval list");
ValidationUtils.nonNull(dictionary, "SAMSequenceDictionary");
- return intervals
- .stream()
+ return intervals.stream()
.map(si -> toQueryInterval(si, dictionary))
- .collect(Collectors.toList()).toArray(new QueryInterval[intervals.size()]);
+ .collect(Collectors.toList())
+ .toArray(new QueryInterval[intervals.size()]);
}
/**
@@ -106,8 +98,7 @@ public static QueryInterval[] toQueryIntervalArray(
*/
@InternalAPI
public static List fromQueryIntervalArray(
- final QueryInterval[] queryIntervals,
- final SAMSequenceDictionary dictionary) {
+ final QueryInterval[] queryIntervals, final SAMSequenceDictionary dictionary) {
return Arrays.stream(queryIntervals)
.map(si -> new HtsQueryInterval(si, dictionary))
.collect(Collectors.toList());
@@ -126,7 +117,8 @@ public static int toIntegerSafe(final long coord) {
try {
return Math.toIntExact(coord);
} catch (ArithmeticException e) {
- throw new IllegalArgumentException(String.format("long to int conversion of %ld results in integer overflow", coord), e);
+ throw new IllegalArgumentException(
+ String.format("long to int conversion of %ld results in integer overflow", coord), e);
}
}
}
diff --git a/src/main/java/htsjdk/beta/plugin/interval/HtsQuery.java b/src/main/java/htsjdk/beta/plugin/interval/HtsQuery.java
index b541c19786..c5e5b79df5 100644
--- a/src/main/java/htsjdk/beta/plugin/interval/HtsQuery.java
+++ b/src/main/java/htsjdk/beta/plugin/interval/HtsQuery.java
@@ -3,7 +3,6 @@
import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
import htsjdk.samtools.util.CloseableIterator;
import htsjdk.utils.ValidationUtils;
-
import java.util.Collections;
import java.util.List;
@@ -22,7 +21,7 @@ public interface HtsQuery extends Iterable {
@Override
CloseableIterator iterator();
- //*******************************************
+ // *******************************************
// Start temporary common query interface default implementations.
/**
@@ -63,10 +62,7 @@ default CloseableIterator query(final String queryString) {
* @return an iterator over all records from the underlying resource that match the query arguments
*/
default CloseableIterator query(
- final String queryName,
- final long start,
- final long end,
- final HtsQueryRule queryRule) {
+ final String queryName, final long start, final long end, final HtsQueryRule queryRule) {
return query(new HtsQueryInterval(queryName, start, end), queryRule);
}
@@ -160,7 +156,7 @@ default CloseableIterator queryContained(final List interva
return query(intervals, HtsQueryRule.CONTAINED);
}
- //TODO: match reads that have this start; we *could* just use an HtsInterval with span==1 ? do we need this ?
+ // TODO: match reads that have this start; we *could* just use an HtsInterval with span==1 ? do we need this ?
/**
* Get an iterator over all records from the underlying resource that overlap the start position
*
@@ -172,5 +168,4 @@ default CloseableIterator queryStart(final String queryName, final long
ValidationUtils.validateArg(isQueryable(), "Decoder is not queryable");
throw new HtsjdkUnsupportedOperationException("queryStart not implemented for this decoder");
}
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/interval/HtsQueryInterval.java b/src/main/java/htsjdk/beta/plugin/interval/HtsQueryInterval.java
index 0cfc202b66..88e2ea030f 100644
--- a/src/main/java/htsjdk/beta/plugin/interval/HtsQueryInterval.java
+++ b/src/main/java/htsjdk/beta/plugin/interval/HtsQueryInterval.java
@@ -4,7 +4,7 @@
import htsjdk.samtools.SAMSequenceDictionary;
import htsjdk.utils.ValidationUtils;
-//TODO: wild cards 0, +, end of reference/contig
+// TODO: wild cards 0, +, end of reference/contig
/**
* An concrete query interval implementation of {@link HtsInterval} used for random access queries on
@@ -22,8 +22,8 @@ public class HtsQueryInterval implements HtsInterval {
* @param start the integer start position
* @param end the end position
*/
- public HtsQueryInterval(final String queryName, final long start, final long end){
- //validatePositions(contig, start, end);
+ public HtsQueryInterval(final String queryName, final long start, final long end) {
+ // validatePositions(contig, start, end);
this.queryName = queryName;
this.start = start;
this.end = end;
@@ -37,22 +37,32 @@ public HtsQueryInterval(final String queryName, final long start, final long end
*/
public HtsQueryInterval(final QueryInterval queryInterval, final SAMSequenceDictionary dictionary) {
ValidationUtils.nonNull(dictionary, "a valid sequence dictionary is required");
- ValidationUtils.nonNull(dictionary.getSequence(queryInterval.referenceIndex),
- String.format("query index %d is not present in the provided dictionary", queryInterval.referenceIndex));
- ValidationUtils.nonNull(dictionary.getSequence(queryInterval.referenceIndex).getContig(),
- String.format("contig name for index %d is not present in the provided dictionary", queryInterval.referenceIndex));
+ ValidationUtils.nonNull(
+ dictionary.getSequence(queryInterval.referenceIndex),
+ String.format(
+ "query index %d is not present in the provided dictionary", queryInterval.referenceIndex));
+ ValidationUtils.nonNull(
+ dictionary.getSequence(queryInterval.referenceIndex).getContig(),
+ String.format(
+ "contig name for index %d is not present in the provided dictionary",
+ queryInterval.referenceIndex));
this.queryName = dictionary.getSequence(queryInterval.referenceIndex).getContig();
this.start = queryInterval.start;
this.end = queryInterval.end;
}
@Override
- public String getQueryName() { return queryName; }
+ public String getQueryName() {
+ return queryName;
+ }
@Override
- public long getStart() { return start; }
+ public long getStart() {
+ return start;
+ }
@Override
- public long getEnd() { return end; }
-
+ public long getEnd() {
+ return end;
+ }
}
diff --git a/src/main/java/htsjdk/beta/plugin/reads/ReadsBundle.java b/src/main/java/htsjdk/beta/plugin/reads/ReadsBundle.java
index 3d2f244f14..7e18940f2d 100644
--- a/src/main/java/htsjdk/beta/plugin/reads/ReadsBundle.java
+++ b/src/main/java/htsjdk/beta/plugin/reads/ReadsBundle.java
@@ -1,20 +1,19 @@
package htsjdk.beta.plugin.reads;
import htsjdk.beta.io.IOPathUtils;
-import htsjdk.beta.io.bundle.BundleJSON;
-import htsjdk.io.HtsPath;
-import htsjdk.io.IOPath;
-import htsjdk.beta.io.bundle.BundleResourceType;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleBuilder;
-import htsjdk.beta.io.bundle.IOPathResource;
+import htsjdk.beta.io.bundle.BundleJSON;
import htsjdk.beta.io.bundle.BundleResource;
+import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.io.bundle.IOPathResource;
+import htsjdk.io.HtsPath;
+import htsjdk.io.IOPath;
import htsjdk.samtools.SamFiles;
import htsjdk.samtools.util.FileExtensions;
import htsjdk.samtools.util.Log;
import htsjdk.samtools.util.Tuple;
import htsjdk.utils.ValidationUtils;
-
import java.io.Serializable;
import java.nio.file.Path;
import java.util.Arrays;
@@ -77,11 +76,11 @@ protected ReadsBundle(final Collection resources) {
super(BundleResourceType.CT_ALIGNED_READS, resources);
}
- /**
- * return the {@link BundleResourceType#CT_ALIGNED_READS} {@link BundleResource} for this {@link ReadsBundle}
- *
- * @return the {@link BundleResourceType#CT_ALIGNED_READS} {@link BundleResource} for this {@link ReadsBundle}
- */
+ /**
+ * return the {@link BundleResourceType#CT_ALIGNED_READS} {@link BundleResource} for this {@link ReadsBundle}
+ *
+ * @return the {@link BundleResourceType#CT_ALIGNED_READS} {@link BundleResource} for this {@link ReadsBundle}
+ */
public BundleResource getReads() {
return getOrThrow(BundleResourceType.CT_ALIGNED_READS);
}
@@ -127,9 +126,9 @@ public static ReadsBundle getReadsBundleFromString(final String jsonStri
* @return a newly created {@link ReadsBundle}
*/
public static ReadsBundle getReadsBundleFromString(
- final String jsonString,
- final Function ioPathConstructor) {
- return new ReadsBundle<>(BundleJSON.toBundle(jsonString, ioPathConstructor).getResources());
+ final String jsonString, final Function ioPathConstructor) {
+ return new ReadsBundle<>(
+ BundleJSON.toBundle(jsonString, ioPathConstructor).getResources());
}
/**
@@ -157,14 +156,14 @@ public static ReadsBundle resolveIndex(final IOPath reads) {
* @return a {@link ReadsBundle} containing reads and companion index, if it can be found
*/
public static ReadsBundle resolveIndex(
- final T reads,
- final Function ioPathConstructor) {
+ final T reads, final Function ioPathConstructor) {
if (reads.hasFileSystemProvider()) {
final Path index = SamFiles.findIndex(reads.toPath());
if (index == null) {
return new ReadsBundle<>(reads);
} else {
- return new ReadsBundle(reads, ioPathConstructor.apply(index.toUri().toString()));
+ return new ReadsBundle(
+ reads, ioPathConstructor.apply(index.toUri().toString()));
}
}
return new ReadsBundle<>(reads);
@@ -177,9 +176,7 @@ private static IOPathResource toInputResource(final String pr
if (providedContentType != null && !typePair.get().a.equals(providedContentType)) {
LOG.warn(String.format(
"Provided content type \"%s\" for \"%s\" doesn't match derived content type \"%s\"",
- providedContentType,
- ioPath.getRawInputString(),
- typePair.get().a));
+ providedContentType, ioPath.getRawInputString(), typePair.get().a));
}
}
return new IOPathResource(ioPath, providedContentType);
@@ -204,9 +201,8 @@ private static Optional> getInferredCon
} else if (ext.equals((FileExtensions.SAM))) {
return Optional.of(new Tuple<>(BundleResourceType.CT_ALIGNED_READS, BundleResourceType.FMT_READS_SAM));
}
- //TODO: finish this, else SRA, htsget,...
+ // TODO: finish this, else SRA, htsget,...
}
return Optional.empty();
}
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/reads/ReadsCodec.java b/src/main/java/htsjdk/beta/plugin/reads/ReadsCodec.java
index 2958983e64..3c2b05ba1e 100644
--- a/src/main/java/htsjdk/beta/plugin/reads/ReadsCodec.java
+++ b/src/main/java/htsjdk/beta/plugin/reads/ReadsCodec.java
@@ -9,6 +9,7 @@
public interface ReadsCodec extends HtsCodec {
@Override
- default HtsContentType getContentType() { return HtsContentType.ALIGNED_READS; }
-
+ default HtsContentType getContentType() {
+ return HtsContentType.ALIGNED_READS;
+ }
}
diff --git a/src/main/java/htsjdk/beta/plugin/reads/ReadsDecoder.java b/src/main/java/htsjdk/beta/plugin/reads/ReadsDecoder.java
index 681a1b47b9..013f6e47a5 100644
--- a/src/main/java/htsjdk/beta/plugin/reads/ReadsDecoder.java
+++ b/src/main/java/htsjdk/beta/plugin/reads/ReadsDecoder.java
@@ -1,12 +1,11 @@
package htsjdk.beta.plugin.reads;
+import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.plugin.HtsContentType;
import htsjdk.beta.plugin.HtsDecoder;
-import htsjdk.beta.io.bundle.Bundle;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.util.CloseableIterator;
-
import java.util.Optional;
/**
@@ -31,4 +30,3 @@ public interface ReadsDecoder extends HtsDecoder, Read
@Override
Optional queryMate(SAMRecord rec);
}
-
diff --git a/src/main/java/htsjdk/beta/plugin/reads/ReadsDecoderOptions.java b/src/main/java/htsjdk/beta/plugin/reads/ReadsDecoderOptions.java
index f1ae8a6536..585d567996 100644
--- a/src/main/java/htsjdk/beta/plugin/reads/ReadsDecoderOptions.java
+++ b/src/main/java/htsjdk/beta/plugin/reads/ReadsDecoderOptions.java
@@ -1,12 +1,11 @@
package htsjdk.beta.plugin.reads;
+import htsjdk.annotations.InternalAPI;
import htsjdk.beta.codecs.reads.bam.BAMDecoderOptions;
import htsjdk.beta.codecs.reads.cram.CRAMDecoderOptions;
import htsjdk.beta.plugin.HtsDecoderOptions;
import htsjdk.samtools.ValidationStringency;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
-
import java.nio.channels.SeekableByteChannel;
import java.util.Optional;
import java.util.function.Function;
@@ -15,15 +14,15 @@
* Reads decoder options (shared/common).
*/
public class ReadsDecoderOptions implements HtsDecoderOptions {
- private ValidationStringency validationStringency = ValidationStringency.STRICT;
- private boolean eagerlyDecode = false; // honored by BAM and HtsGet
- private boolean fileBasedIndexCached = false; // honored by BAM and CRAM
- private boolean memoryMapIndexes = true; // honored by BAM and CRAM
- //TODO: replace these with a prefetch size args, and use a local channel wrapper implementation
+ private ValidationStringency validationStringency = ValidationStringency.STRICT;
+ private boolean eagerlyDecode = false; // honored by BAM and HtsGet
+ private boolean fileBasedIndexCached = false; // honored by BAM and CRAM
+ private boolean memoryMapIndexes = true; // honored by BAM and CRAM
+ // TODO: replace these with a prefetch size args, and use a local channel wrapper implementation
private Function readsChannelTransformer;
private Function indexChannelTransformer;
- private BAMDecoderOptions bamDecoderOptions = new BAMDecoderOptions();
- private CRAMDecoderOptions cramDecoderOptions = new CRAMDecoderOptions();
+ private BAMDecoderOptions bamDecoderOptions = new BAMDecoderOptions();
+ private CRAMDecoderOptions cramDecoderOptions = new CRAMDecoderOptions();
/**
* Get the {@link ValidationStringency} used for these options. Defaults to {@link ValidationStringency#STRICT}.
@@ -112,7 +111,9 @@ public ReadsDecoderOptions setMemoryMapIndexes(final boolean memoryMapIndexes) {
*
* @return the {@link BAMDecoderOptions} for these options
*/
- public BAMDecoderOptions getBAMDecoderOptions() { return bamDecoderOptions; }
+ public BAMDecoderOptions getBAMDecoderOptions() {
+ return bamDecoderOptions;
+ }
/**
* Set the {@link BAMDecoderOptions} used for these options.
@@ -131,7 +132,9 @@ public ReadsDecoderOptions setBAMDecoderOptions(final BAMDecoderOptions bamDecod
*
* @return the {@link CRAMDecoderOptions} for these options
*/
- public CRAMDecoderOptions getCRAMDecoderOptions() { return cramDecoderOptions; }
+ public CRAMDecoderOptions getCRAMDecoderOptions() {
+ return cramDecoderOptions;
+ }
/**
* Set the {@link CRAMDecoderOptions} for these ReadsDecoderOptions.
@@ -196,5 +199,4 @@ public ReadsDecoderOptions setIndexChannelTransformer(
this.indexChannelTransformer = indexChannelTransformer;
return this;
}
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/reads/ReadsEncoder.java b/src/main/java/htsjdk/beta/plugin/reads/ReadsEncoder.java
index 7c16fc2527..042a19bec6 100644
--- a/src/main/java/htsjdk/beta/plugin/reads/ReadsEncoder.java
+++ b/src/main/java/htsjdk/beta/plugin/reads/ReadsEncoder.java
@@ -8,4 +8,4 @@
/**
* Base interface for {@link HtsContentType#ALIGNED_READS} encoders.
*/
-public interface ReadsEncoder extends HtsEncoder { }
+public interface ReadsEncoder extends HtsEncoder {}
diff --git a/src/main/java/htsjdk/beta/plugin/reads/ReadsEncoderOptions.java b/src/main/java/htsjdk/beta/plugin/reads/ReadsEncoderOptions.java
index 711522f8c4..7e4114317c 100644
--- a/src/main/java/htsjdk/beta/plugin/reads/ReadsEncoderOptions.java
+++ b/src/main/java/htsjdk/beta/plugin/reads/ReadsEncoderOptions.java
@@ -40,7 +40,9 @@ public ReadsEncoderOptions setPreSorted(boolean preSorted) {
*
* @return the {@link BAMEncoderOptions} for these ReadsEncoderOptions
*/
- public BAMEncoderOptions getBAMEncoderOptions() { return bamEncoderOptions; }
+ public BAMEncoderOptions getBAMEncoderOptions() {
+ return bamEncoderOptions;
+ }
/**
* Set the {@link BAMEncoderOptions} for these ReadsEncoderOptions. Defaults values are default
@@ -76,5 +78,4 @@ public ReadsEncoderOptions setCRAMEncoderOptions(final CRAMEncoderOptions cramEn
this.cramEncoderOptions = cramEncoderOptions;
return this;
}
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/reads/ReadsFormats.java b/src/main/java/htsjdk/beta/plugin/reads/ReadsFormats.java
index d406da3734..f6a3791182 100644
--- a/src/main/java/htsjdk/beta/plugin/reads/ReadsFormats.java
+++ b/src/main/java/htsjdk/beta/plugin/reads/ReadsFormats.java
@@ -24,5 +24,4 @@ public class ReadsFormats {
* GA4GH htsget BAM format.
*/
public static final String HTSGET_BAM = "HTSGET_BAM";
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/reads/ReadsQuery.java b/src/main/java/htsjdk/beta/plugin/reads/ReadsQuery.java
index 0ef6821b82..707579e310 100644
--- a/src/main/java/htsjdk/beta/plugin/reads/ReadsQuery.java
+++ b/src/main/java/htsjdk/beta/plugin/reads/ReadsQuery.java
@@ -2,7 +2,6 @@
import htsjdk.beta.plugin.HtsRecord;
import htsjdk.samtools.util.CloseableIterator;
-
import java.util.Optional;
/**
diff --git a/src/main/java/htsjdk/beta/plugin/registry/HaploidReferenceResolver.java b/src/main/java/htsjdk/beta/plugin/registry/HaploidReferenceResolver.java
index 676a5ffe3c..6b59d45f64 100644
--- a/src/main/java/htsjdk/beta/plugin/registry/HaploidReferenceResolver.java
+++ b/src/main/java/htsjdk/beta/plugin/registry/HaploidReferenceResolver.java
@@ -15,7 +15,6 @@
import htsjdk.samtools.util.GZIIndex;
import htsjdk.samtools.util.IOUtil;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -70,8 +69,7 @@ public HaploidReferenceDecoder getHaploidReferenceDecoder(final IOPath inputPath
* that the registry contains an incorrectly written codec.
*/
public HaploidReferenceDecoder getHaploidReferenceDecoder(
- final IOPath inputPath,
- final HaploidReferenceDecoderOptions HaploidReferenceDecoderOptions) {
+ final IOPath inputPath, final HaploidReferenceDecoderOptions HaploidReferenceDecoderOptions) {
ValidationUtils.nonNull(inputPath, "Input path");
ValidationUtils.nonNull(HaploidReferenceDecoderOptions, "Decoder options");
@@ -109,12 +107,12 @@ public HaploidReferenceDecoder getHaploidReferenceDecoder(final Bundle inputBund
*/
@SuppressWarnings("unchecked")
public HaploidReferenceDecoder getHaploidReferenceDecoder(
- final Bundle inputBundle,
- final HaploidReferenceDecoderOptions HaploidReferenceDecoderOptions) {
+ final Bundle inputBundle, final HaploidReferenceDecoderOptions HaploidReferenceDecoderOptions) {
ValidationUtils.nonNull(inputBundle, "Input bundle");
ValidationUtils.nonNull(HaploidReferenceDecoderOptions, "Decoder options");
- return (HaploidReferenceDecoder) resolveForDecoding(inputBundle).getDecoder(inputBundle, HaploidReferenceDecoderOptions);
+ return (HaploidReferenceDecoder)
+ resolveForDecoding(inputBundle).getDecoder(inputBundle, HaploidReferenceDecoderOptions);
}
/**
@@ -126,38 +124,33 @@ public HaploidReferenceDecoder getHaploidReferenceDecoder(
* @return a reference Bundle
* @param
*/
- public static Bundle referenceBundleFromFastaPath(final IOPath fastaPath, final Function ioPathConstructor) {
+ public static Bundle referenceBundleFromFastaPath(
+ final IOPath fastaPath, final Function ioPathConstructor) {
final BundleBuilder referenceBundleBuilder = new BundleBuilder();
referenceBundleBuilder.addPrimary(new IOPathResource(fastaPath, BundleResourceType.CT_HAPLOID_REFERENCE));
final Path dictPath = ReferenceSequenceFileFactory.getDefaultDictionaryForReferenceSequence(fastaPath.toPath());
if (Files.exists(dictPath)) {
- referenceBundleBuilder.addSecondary(
- new IOPathResource(
- ioPathConstructor.apply(dictPath.toUri().toString()),
- BundleResourceType.CT_REFERENCE_DICTIONARY));
+ referenceBundleBuilder.addSecondary(new IOPathResource(
+ ioPathConstructor.apply(dictPath.toUri().toString()), BundleResourceType.CT_REFERENCE_DICTIONARY));
}
final Path idxPath = ReferenceSequenceFileFactory.getFastaIndexFileName(fastaPath.toPath());
if (Files.exists(idxPath)) {
- referenceBundleBuilder.addSecondary(
- new IOPathResource(
- ioPathConstructor.apply(idxPath.toUri().toString()),
- BundleResourceType.CT_REFERENCE_INDEX));
+ referenceBundleBuilder.addSecondary(new IOPathResource(
+ ioPathConstructor.apply(idxPath.toUri().toString()), BundleResourceType.CT_REFERENCE_INDEX));
}
try {
if (IOUtil.isBlockCompressed(fastaPath.toPath(), true)) {
final Path gziPath = GZIIndex.resolveIndexNameForBgzipFile(fastaPath.toPath());
- referenceBundleBuilder.addSecondary(
- new IOPathResource(
- ioPathConstructor.apply(gziPath.toUri().toString()),
- BundleResourceType.CT_REFERENCE_INDEX_GZI));
+ referenceBundleBuilder.addSecondary(new IOPathResource(
+ ioPathConstructor.apply(gziPath.toUri().toString()),
+ BundleResourceType.CT_REFERENCE_INDEX_GZI));
}
} catch (IOException e) {
throw new HtsjdkException("Error while checking for block compression", e);
}
return referenceBundleBuilder.build();
}
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/registry/HtsCodecRegistry.java b/src/main/java/htsjdk/beta/plugin/registry/HtsCodecRegistry.java
index 9ee13a3c68..ad226c9f17 100644
--- a/src/main/java/htsjdk/beta/plugin/registry/HtsCodecRegistry.java
+++ b/src/main/java/htsjdk/beta/plugin/registry/HtsCodecRegistry.java
@@ -1,11 +1,12 @@
package htsjdk.beta.plugin.registry;
+import htsjdk.beta.exception.HtsjdkPluginException;
+import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
import htsjdk.beta.plugin.HtsCodec;
import htsjdk.beta.plugin.hapref.HaploidReferenceCodec;
import htsjdk.beta.plugin.reads.ReadsCodec;
import htsjdk.beta.plugin.variants.VariantsCodec;
-import htsjdk.beta.exception.HtsjdkPluginException;
-import htsjdk.beta.exception.HtsjdkUnsupportedOperationException;
+
/**
* A registry for tracking {@link HtsCodec} instances.
*
@@ -26,7 +27,7 @@ public class HtsCodecRegistry {
* Create a registry. Protected to prevent use outside of the registry package. To create
* a private registry from outside the registry package, use {@link #createPrivateRegistry}.
*/
- protected HtsCodecRegistry() { }
+ protected HtsCodecRegistry() {}
/**
* Add a codec to the registry. If a codec that supports the same (format, version) (determined
@@ -66,15 +67,21 @@ protected HtsCodecRegistry() { }
*
* @return a mutable registry instance for private use
*/
- public synchronized static HtsCodecRegistry createPrivateRegistry() {
+ public static synchronized HtsCodecRegistry createPrivateRegistry() {
final HtsCodecRegistry privateRegistry = new HtsCodecRegistry();
// propagate the codecs from the sourceRegistry to the new registry
- HtsDefaultRegistry.htsDefaultCodecRegistry.getHaploidReferenceResolver().getCodecs()
+ HtsDefaultRegistry.htsDefaultCodecRegistry
+ .getHaploidReferenceResolver()
+ .getCodecs()
+ .forEach(c -> privateRegistry.registerCodec(c));
+ HtsDefaultRegistry.htsDefaultCodecRegistry
+ .getReadsResolver()
+ .getCodecs()
.forEach(c -> privateRegistry.registerCodec(c));
- HtsDefaultRegistry.htsDefaultCodecRegistry.getReadsResolver().getCodecs().
- forEach(c -> privateRegistry.registerCodec(c));
- HtsDefaultRegistry.htsDefaultCodecRegistry.getVariantsResolver().getCodecs()
+ HtsDefaultRegistry.htsDefaultCodecRegistry
+ .getVariantsResolver()
+ .getCodecs()
.forEach(c -> privateRegistry.registerCodec(c));
return privateRegistry;
}
@@ -84,21 +91,25 @@ public synchronized static HtsCodecRegistry createPrivateRegistry() {
*
* @return the {@link HaploidReferenceResolver} for this registry
*/
- public synchronized HaploidReferenceResolver getHaploidReferenceResolver() { return htsHaploidReferenceResolver; }
+ public synchronized HaploidReferenceResolver getHaploidReferenceResolver() {
+ return htsHaploidReferenceResolver;
+ }
/**
* Get the {@link ReadsResolver} for this registry.
*
* @return the {@link ReadsResolver} for this registry
*/
- public synchronized ReadsResolver getReadsResolver() { return htsReadsResolver; }
+ public synchronized ReadsResolver getReadsResolver() {
+ return htsReadsResolver;
+ }
/**
* Get the {@link VariantsResolver} for this registry.
*
* @return the {@link VariantsResolver} for this registry
*/
- public synchronized VariantsResolver getVariantsResolver() { return htsVariantsResolver; }
-
+ public synchronized VariantsResolver getVariantsResolver() {
+ return htsVariantsResolver;
+ }
}
-
diff --git a/src/main/java/htsjdk/beta/plugin/registry/HtsCodecResolver.java b/src/main/java/htsjdk/beta/plugin/registry/HtsCodecResolver.java
index dbfc7d7ed2..cd83db6b4e 100644
--- a/src/main/java/htsjdk/beta/plugin/registry/HtsCodecResolver.java
+++ b/src/main/java/htsjdk/beta/plugin/registry/HtsCodecResolver.java
@@ -1,18 +1,17 @@
package htsjdk.beta.plugin.registry;
+import htsjdk.annotations.InternalAPI;
+import htsjdk.beta.exception.HtsjdkException;
import htsjdk.beta.exception.HtsjdkIOException;
-import htsjdk.beta.plugin.HtsCodec;
-import htsjdk.beta.plugin.HtsVersion;
+import htsjdk.beta.exception.HtsjdkPluginException;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResource;
import htsjdk.beta.io.bundle.SignatureStream;
-import htsjdk.beta.exception.HtsjdkException;
-import htsjdk.beta.exception.HtsjdkPluginException;
+import htsjdk.beta.plugin.HtsCodec;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.io.IOPath;
import htsjdk.samtools.util.Log;
-import htsjdk.annotations.InternalAPI;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
@@ -37,8 +36,8 @@
public class HtsCodecResolver> {
private static final Log LOG = Log.getInstance(HtsCodecResolver.class);
- final static String NO_SUPPORTING_CODEC_ERROR = "No registered codec accepts the provided resource";
- final static String MULTIPLE_SUPPORTING_CODECS_ERROR = "Multiple codecs accept the provided resource";
+ static final String NO_SUPPORTING_CODEC_ERROR = "No registered codec accepts the provided resource";
+ static final String MULTIPLE_SUPPORTING_CODECS_ERROR = "Multiple codecs accept the provided resource";
private final String requiredContentType;
private final Map> codecs = new HashMap<>();
@@ -75,9 +74,9 @@ public C registerCodec(final C codec) {
// update the version map for this codec
final C oldCodec = versionMap.put(codec.getVersion(), codec);
if (oldCodec != null) {
- LOG.warn(String.format("A previously registered HTS codec (%s) was replaced with the (%s) codec ",
- oldCodec.getDisplayName(),
- codec.getDisplayName()));
+ LOG.warn(String.format(
+ "A previously registered HTS codec (%s) was replaced with the (%s) codec ",
+ oldCodec.getDisplayName(), codec.getDisplayName()));
}
return oldCodec;
}
@@ -149,15 +148,14 @@ public C resolveForDecoding(final Bundle bundle) {
final Optional optFormatString = bundleResource.getFileFormat();
final List candidateCodecs = resolveForFormat(optFormatString);
- final List resolvedCodecs = bundleResource.getIOPath().isPresent() ?
- resolveForDecodingIOPath(bundleResource, candidateCodecs) :
- resolveForDecodingStream(bundleResource, candidateCodecs);
+ final List resolvedCodecs = bundleResource.getIOPath().isPresent()
+ ? resolveForDecodingIOPath(bundleResource, candidateCodecs)
+ : resolveForDecodingStream(bundleResource, candidateCodecs);
return getOneOrThrow(
resolvedCodecs,
- () -> String.format("%s/%s",
- optFormatString.isPresent () ? optFormatString.get() : "(NONE)",
- bundleResource));
+ () -> String.format(
+ "%s/%s", optFormatString.isPresent() ? optFormatString.get() : "(NONE)", bundleResource));
}
/**
@@ -180,7 +178,9 @@ public C resolveForDecoding(final Bundle bundle) {
* @throws HtsjdkPluginException if more than one codec claims to handle the resource. this usually indicates
* that the registry contains an incorrectly written codec.
*/
- public C resolveForEncoding(final Bundle bundle) { return resolveForEncoding(bundle, HtsVersion.NEWEST_VERSION); }
+ public C resolveForEncoding(final Bundle bundle) {
+ return resolveForEncoding(bundle, HtsVersion.NEWEST_VERSION);
+ }
/**
* Inspect a bundle and find a codec that can encode to the primary resource using the format version
@@ -208,16 +208,15 @@ public C resolveForEncoding(final Bundle bundle, final HtsVersion htsVersion) {
final List candidateCodecs = resolveForFormat(optFormatString);
final Optional ioPath = bundleResource.getIOPath();
- final List filteredCodecs = bundleResource.getIOPath().isPresent() ?
- resolveForEncodingIOPath(ioPath.get(), candidateCodecs) :
- candidateCodecs; // there isn't anything else to probe when the output is to a stream
+ final List filteredCodecs = bundleResource.getIOPath().isPresent()
+ ? resolveForEncodingIOPath(ioPath.get(), candidateCodecs)
+ : candidateCodecs; // there isn't anything else to probe when the output is to a stream
final List resolvedCodecs = filterByVersion(filteredCodecs, htsVersion);
return getOneOrThrow(
resolvedCodecs,
- () -> String.format("%s/%s",
- optFormatString.isPresent () ? optFormatString.get() : "(NONE)",
- bundleResource));
+ () -> String.format(
+ "%s/%s", optFormatString.isPresent() ? optFormatString.get() : "(NONE)", bundleResource));
}
/**
@@ -245,9 +244,9 @@ public List resolveForFormat(final String format) {
* @throws HtsjdkException if no registered codecs can handle the resource
*/
public C resolveFormatAndVersion(final String format, final HtsVersion formatVersion) {
- final List matchingCodecs = resolveForFormat(format)
- .stream()
- .filter(codec -> codec.getFileFormat().equals(format) && codec.getVersion().equals(formatVersion))
+ final List matchingCodecs = resolveForFormat(format).stream()
+ .filter(codec -> codec.getFileFormat().equals(format)
+ && codec.getVersion().equals(formatVersion))
.collect(Collectors.toList());
return getOneOrThrow(matchingCodecs, () -> String.format("%s/%s", format, formatVersion));
}
@@ -259,11 +258,8 @@ public C resolveFormatAndVersion(final String format, final HtsVersion formatVer
*/
public List getCodecs() {
// flatten out the codecs into a single list
- final List codecList = codecs
- .values()
- .stream()
- .flatMap(map -> map.values().stream())
- .collect(Collectors.toList());
+ final List codecList =
+ codecs.values().stream().flatMap(map -> map.values().stream()).collect(Collectors.toList());
return codecList;
}
@@ -296,35 +292,28 @@ private List resolveForDecodingStream(final BundleResource bundleResource, fi
final byte[] signatureBuffer = getSignatureProbeBuffer(bundleResource, candidateCodecs);
return candidateCodecs.stream()
.filter(codec -> codec.canDecodeSignature(
- new SignatureStream(signatureBuffer.length, signatureBuffer),
- bundleResource.getDisplayName()))
+ new SignatureStream(signatureBuffer.length, signatureBuffer), bundleResource.getDisplayName()))
.collect(Collectors.toList());
}
- private final byte[] getSignatureProbeBuffer(
- final BundleResource bundleResource,
- final List candidateCodecs) {
+ private final byte[] getSignatureProbeBuffer(final BundleResource bundleResource, final List candidateCodecs) {
final int maxSignatureProbeLength = getMaxSignatureProbeLength(candidateCodecs);
- try (final SignatureStream probingStream =
- bundleResource.getIOPath().isPresent() ?
- getIOPathSignatureProbingStream(bundleResource, maxSignatureProbeLength) :
- bundleResource.getSignatureStream(maxSignatureProbeLength)) {
+ try (final SignatureStream probingStream = bundleResource.getIOPath().isPresent()
+ ? getIOPathSignatureProbingStream(bundleResource, maxSignatureProbeLength)
+ : bundleResource.getSignatureStream(maxSignatureProbeLength)) {
// we need to recreate a stream over the underlying signature for each codec,
// since some implementations may use their own mark/reset pairs
final byte[] signatureBytes = new byte[probingStream.getSignaturePrefixLength()];
final int readSize = probingStream.read(signatureBytes);
if (readSize != maxSignatureProbeLength) {
- throw new HtsjdkPluginException(
- String.format("Failure to read %d bytes from signature stream for %s (only read %d)",
- maxSignatureProbeLength,
- bundleResource,
- readSize));
+ throw new HtsjdkPluginException(String.format(
+ "Failure to read %d bytes from signature stream for %s (only read %d)",
+ maxSignatureProbeLength, bundleResource, readSize));
}
return signatureBytes;
} catch (IOException e) {
throw new HtsjdkIOException(
- String.format("error closing signature stream for %s", bundleResource.getDisplayName()),
- e);
+ String.format("error closing signature stream for %s", bundleResource.getDisplayName()), e);
}
}
@@ -339,21 +328,19 @@ private List resolveForEncodingIOPath(final IOPath ioPath, final List cand
final List filteredCodecs = uriHandlers.isEmpty() ? candidateCodecs : uriHandlers;
// reduce our candidates based on uri and IOPath
- return filteredCodecs.stream()
- .filter(c -> c.canDecodeURI(ioPath))
- .collect(Collectors.toList());
+ return filteredCodecs.stream().filter(c -> c.canDecodeURI(ioPath)).collect(Collectors.toList());
}
private int getMaxSignatureProbeLength(final List candidateCodecs) {
// find the longest signature probe length of any candidate
return candidateCodecs.stream()
.map(codec -> codec.getSignatureProbeLength())
- .max(Integer::compare).orElse(0);
+ .max(Integer::compare)
+ .orElse(0);
}
private SignatureStream getIOPathSignatureProbingStream(
- final BundleResource bundleResource,
- final int streamPrefixSize) {
+ final BundleResource bundleResource, final int streamPrefixSize) {
ValidationUtils.validateArg(bundleResource.getIOPath().isPresent(), "an IOPath resource is required");
final IOPath inputPath = bundleResource.getIOPath().get();
if (!inputPath.hasFileSystemProvider()) {
@@ -364,11 +351,10 @@ private SignatureStream getIOPathSignatureProbingStream(
// "claimURI" implementations, or else it would be a known protocol such as "gs://" for
// which the user expected a file system to be present. It likely represents user error
// (a user entered "hdf://" instead of "hdfs://"), and it will fail anyway, so throw.
- throw new IllegalArgumentException(
- String.format("The resource (%s) specifies a custom protocol (%s) " +
- "which no registered codec claims, and for which no NIO file system provider is available",
- bundleResource,
- inputPath.getURI().getScheme()));
+ throw new IllegalArgumentException(String.format(
+ "The resource (%s) specifies a custom protocol (%s) "
+ + "which no registered codec claims, and for which no NIO file system provider is available",
+ bundleResource, inputPath.getURI().getScheme()));
}
return bundleResource.getSignatureStream(streamPrefixSize);
}
@@ -387,10 +373,12 @@ protected List filterByVersion(final List candidateCodecs, final HtsVersio
// version (since there still can be more than one)
final HtsVersion newestVersion = candidateCodecs.stream()
.map(c -> c.getVersion())
- .reduce(candidateCodecs.get(0).getVersion(),
+ .reduce(
+ candidateCodecs.get(0).getVersion(),
(HtsVersion a, HtsVersion b) -> a.compareTo(b) > 0 ? a : b);
- return candidateCodecs.stream().filter(
- c -> c.getVersion().equals(newestVersion)).collect(Collectors.toList());
+ return candidateCodecs.stream()
+ .filter(c -> c.getVersion().equals(newestVersion))
+ .collect(Collectors.toList());
} else {
return candidateCodecs.stream()
.filter(c -> c.getVersion().equals(htsVersion))
@@ -402,17 +390,13 @@ protected List filterByVersion(final List candidateCodecs, final HtsVersio
// or otherwise all registered codecs for this codec format.
private List resolveForFormat(final Optional optFormatString) {
final List candidateCodecs =
- optFormatString.isPresent() ?
- resolveForFormat(optFormatString.get()) :
- getCodecs();
+ optFormatString.isPresent() ? resolveForFormat(optFormatString.get()) : getCodecs();
if (optFormatString.isPresent() && candidateCodecs.isEmpty()) {
// warn if the resource format string is present, but doesn't map to any codec registered
// with this resolver (/content type).
LOG.warn(String.format(
"The specified format string (%s) does not correspond to any registered codec for content type (%s)",
- optFormatString.get(),
- requiredContentType));
-
+ optFormatString.get(), requiredContentType));
}
return candidateCodecs;
}
@@ -426,14 +410,13 @@ private List getURIOwners(final List candidateCodecs, final IOPath ioPath)
if (isCustomURI) {
// ensure that all codecs that claim to own this URI honor the contract that says if canDecodeURI
// returns true, ownsURI must also return true for the same IOPath
- uriHandlers.stream().forEach(
- codec -> {
- if (!codec.canDecodeURI(ioPath)) {
- throw new HtsjdkPluginException(
- String.format("The %s codec returned true for ownsURI but false for canDecodeURI for path: %s",
- codec,
- ioPath.getURI()));
- }});
+ uriHandlers.stream().forEach(codec -> {
+ if (!codec.canDecodeURI(ioPath)) {
+ throw new HtsjdkPluginException(String.format(
+ "The %s codec returned true for ownsURI but false for canDecodeURI for path: %s",
+ codec, ioPath.getURI()));
+ }
+ });
}
return uriHandlers;
}
@@ -446,21 +429,18 @@ private final BundleResource getPrimaryResource(final Bundle bundle, final boole
if (!requiredContentType.equals(bundlePrimaryContentType)) {
throw new IllegalArgumentException(String.format(
"The primary content type (%s) for the resource does not match the requested content type (%s).",
- bundlePrimaryContentType,
- requiredContentType));
+ bundlePrimaryContentType, requiredContentType));
}
// Make sure the resource type is appropriate for encoding or decoding, as requested by the caller
if (forEncoding && !bundleResource.hasInputType()) {
- throw new IllegalArgumentException(
- String.format("The %s resource found (%s) cannot be used as an input resource",
- requiredContentType,
- bundleResource));
+ throw new IllegalArgumentException(String.format(
+ "The %s resource found (%s) cannot be used as an input resource",
+ requiredContentType, bundleResource));
} else if (!forEncoding && !bundleResource.hasOutputType()) { // for decoding
- throw new IllegalArgumentException(
- String.format("The %s resource found (%s) cannot be used as an output resource",
- requiredContentType,
- bundleResource));
+ throw new IllegalArgumentException(String.format(
+ "The %s resource found (%s) cannot be used as an output resource",
+ requiredContentType, bundleResource));
}
return bundleResource;
@@ -468,13 +448,9 @@ private final BundleResource getPrimaryResource(final Bundle bundle, final boole
@InternalAPI
static > C getOneOrThrow(
- final List resolvedCodecs,
- final Supplier contextMessage) {
+ final List resolvedCodecs, final Supplier contextMessage) {
if (resolvedCodecs.size() == 0) {
- throw new HtsjdkException(String.format(
- "%s %s",
- NO_SUPPORTING_CODEC_ERROR,
- contextMessage.get()));
+ throw new HtsjdkException(String.format("%s %s", NO_SUPPORTING_CODEC_ERROR, contextMessage.get()));
} else if (resolvedCodecs.size() > 1) {
final String multipleCodecsMessage = String.format(
"%s (%s)\n%s\nThis indicates an internal error in one or more of the codecs:",
@@ -486,5 +462,4 @@ private final BundleResource getPrimaryResource(final Bundle bundle, final boole
return resolvedCodecs.get(0);
}
}
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/registry/HtsDefaultRegistry.java b/src/main/java/htsjdk/beta/plugin/registry/HtsDefaultRegistry.java
index 6a14758668..a241221399 100644
--- a/src/main/java/htsjdk/beta/plugin/registry/HtsDefaultRegistry.java
+++ b/src/main/java/htsjdk/beta/plugin/registry/HtsDefaultRegistry.java
@@ -17,7 +17,9 @@ public class HtsDefaultRegistry {
/**
* statically populate the default registry with any codecs on the classpath
*/
- static {ServiceLoader.load(HtsCodec.class).forEach(htsDefaultCodecRegistry::registerCodec);}
+ static {
+ ServiceLoader.load(HtsCodec.class).forEach(htsDefaultCodecRegistry::registerCodec);
+ }
/**
* Grt the {@link HaploidReferenceResolver} resolver for this registry.
@@ -25,7 +27,8 @@ public class HtsDefaultRegistry {
* @return the {@link HaploidReferenceResolver} resolver for this registry
*/
public static synchronized HaploidReferenceResolver getHaploidReferenceResolver() {
- return htsDefaultCodecRegistry.getHaploidReferenceResolver(); }
+ return htsDefaultCodecRegistry.getHaploidReferenceResolver();
+ }
/**
* Gt the {@link ReadsResolver} resolver for this registry.
@@ -33,7 +36,8 @@ public static synchronized HaploidReferenceResolver getHaploidReferenceResolver(
* @return the {@link ReadsResolver} resolver for this registry
*/
public static synchronized ReadsResolver getReadsResolver() {
- return htsDefaultCodecRegistry.getReadsResolver(); }
+ return htsDefaultCodecRegistry.getReadsResolver();
+ }
/**
* Get the {@link VariantsResolver} resolver for this registry.
@@ -41,6 +45,6 @@ public static synchronized ReadsResolver getReadsResolver() {
* @return the {@link VariantsResolver} resolver for this registry
*/
public static synchronized VariantsResolver getVariantsResolver() {
- return htsDefaultCodecRegistry.getVariantsResolver(); }
-
+ return htsDefaultCodecRegistry.getVariantsResolver();
+ }
}
diff --git a/src/main/java/htsjdk/beta/plugin/registry/ReadsResolver.java b/src/main/java/htsjdk/beta/plugin/registry/ReadsResolver.java
index b89ffc4a10..90fb0796c2 100644
--- a/src/main/java/htsjdk/beta/plugin/registry/ReadsResolver.java
+++ b/src/main/java/htsjdk/beta/plugin/registry/ReadsResolver.java
@@ -2,9 +2,9 @@
import htsjdk.beta.exception.HtsjdkException;
import htsjdk.beta.exception.HtsjdkPluginException;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleResourceType;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.reads.ReadsBundle;
import htsjdk.beta.plugin.reads.ReadsCodec;
import htsjdk.beta.plugin.reads.ReadsDecoder;
@@ -25,7 +25,7 @@
* {@link ReadsCodec}s, such as {@link ReadsDecoder}, {@link ReadsEncoder},
* {@link htsjdk.beta.plugin.reads.ReadsDecoderOptions}.
*/
-public class ReadsResolver extends HtsCodecResolver{
+public class ReadsResolver extends HtsCodecResolver {
/**
* Create a ReadsResolver.
@@ -64,9 +64,7 @@ public ReadsDecoder getReadsDecoder(final IOPath inputPath) {
* @throws HtsjdkPluginException if more than one codec claims to handle the resource. this usually indicates
* that the registry contains an incorrectly written codec.
*/
- public ReadsDecoder getReadsDecoder(
- final IOPath inputPath,
- final ReadsDecoderOptions readsDecoderOptions) {
+ public ReadsDecoder getReadsDecoder(final IOPath inputPath, final ReadsDecoderOptions readsDecoderOptions) {
ValidationUtils.nonNull(inputPath, "Input path");
ValidationUtils.nonNull(readsDecoderOptions, "Decoder options");
@@ -102,9 +100,7 @@ public ReadsDecoder getReadsDecoder(final Bundle inputBundle) {
* that the registry contains an incorrectly written codec.
*/
@SuppressWarnings("unchecked")
- public ReadsDecoder getReadsDecoder(
- final Bundle inputBundle,
- final ReadsDecoderOptions readsDecoderOptions) {
+ public ReadsDecoder getReadsDecoder(final Bundle inputBundle, final ReadsDecoderOptions readsDecoderOptions) {
ValidationUtils.nonNull(inputBundle, "Input bundle");
ValidationUtils.nonNull(readsDecoderOptions, "Decoder options");
@@ -143,9 +139,7 @@ public ReadsEncoder getReadsEncoder(final IOPath outputPath) {
* @throws HtsjdkPluginException if more than one codec claims to handle the resource. this usually indicates
* that the registry contains an incorrectly written codec.
*/
- public ReadsEncoder getReadsEncoder(
- final IOPath outputPath,
- final ReadsEncoderOptions readsEncoderOptions) {
+ public ReadsEncoder getReadsEncoder(final IOPath outputPath, final ReadsEncoderOptions readsEncoderOptions) {
ValidationUtils.nonNull(outputPath, "Output path");
ValidationUtils.nonNull(readsEncoderOptions, "Encoder options");
@@ -168,9 +162,7 @@ public ReadsEncoder getReadsEncoder(
* that the registry contains an incorrectly written codec.
*/
@SuppressWarnings("unchecked")
- public ReadsEncoder getReadsEncoder(
- final Bundle outputBundle,
- final ReadsEncoderOptions readsEncoderOptions) {
+ public ReadsEncoder getReadsEncoder(final Bundle outputBundle, final ReadsEncoderOptions readsEncoderOptions) {
ValidationUtils.nonNull(outputBundle, "outputBundle");
ValidationUtils.nonNull(readsEncoderOptions, "Encoder options");
@@ -200,8 +192,7 @@ public ReadsEncoder getReadsEncoder(
ValidationUtils.nonNull(readsFormat, "Reads format");
ValidationUtils.nonNull(formatVersion, "File format version");
- return (ReadsEncoder) resolveFormatAndVersion(readsFormat, formatVersion)
- .getEncoder(outputBundle, readsEncoderOptions);
+ return (ReadsEncoder)
+ resolveFormatAndVersion(readsFormat, formatVersion).getEncoder(outputBundle, readsEncoderOptions);
}
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/registry/VariantsResolver.java b/src/main/java/htsjdk/beta/plugin/registry/VariantsResolver.java
index dd8841377e..e755fa219c 100644
--- a/src/main/java/htsjdk/beta/plugin/registry/VariantsResolver.java
+++ b/src/main/java/htsjdk/beta/plugin/registry/VariantsResolver.java
@@ -3,11 +3,11 @@
import htsjdk.beta.codecs.variants.vcf.vcfv4_2.VCFCodecV4_2;
import htsjdk.beta.exception.HtsjdkException;
import htsjdk.beta.exception.HtsjdkPluginException;
-import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.io.bundle.Bundle;
import htsjdk.beta.io.bundle.BundleBuilder;
import htsjdk.beta.io.bundle.BundleResourceType;
import htsjdk.beta.io.bundle.IOPathResource;
+import htsjdk.beta.plugin.HtsVersion;
import htsjdk.beta.plugin.variants.VariantsCodec;
import htsjdk.beta.plugin.variants.VariantsDecoder;
import htsjdk.beta.plugin.variants.VariantsDecoderOptions;
@@ -62,8 +62,7 @@ public VariantsDecoder getVariantsDecoder(final IOPath inputPath) {
* that the registry contains an incorrectly written codec.
*/
public VariantsDecoder getVariantsDecoder(
- final IOPath inputPath,
- final VariantsDecoderOptions variantsDecoderOptions) {
+ final IOPath inputPath, final VariantsDecoderOptions variantsDecoderOptions) {
ValidationUtils.nonNull(inputPath, "Input path");
ValidationUtils.nonNull(variantsDecoderOptions, "Decoder options");
@@ -102,8 +101,7 @@ public VariantsDecoder getVariantsDecoder(final Bundle inputBundle) {
*/
@SuppressWarnings("unchecked")
public VariantsDecoder getVariantsDecoder(
- final Bundle inputBundle,
- final VariantsDecoderOptions variantsDecoderOptions) {
+ final Bundle inputBundle, final VariantsDecoderOptions variantsDecoderOptions) {
ValidationUtils.nonNull(inputBundle, "Input bundle");
ValidationUtils.nonNull(variantsDecoderOptions, "Decoder options");
@@ -137,8 +135,7 @@ public VariantsEncoder getVariantsEncoder(final IOPath outputPath) {
* that the registry contains an incorrectly written codec.
*/
public VariantsEncoder getVariantsEncoder(
- final IOPath outputPath,
- final VariantsEncoderOptions variantsEncoderOptions) {
+ final IOPath outputPath, final VariantsEncoderOptions variantsEncoderOptions) {
ValidationUtils.nonNull(outputPath, "Output path");
ValidationUtils.nonNull(variantsEncoderOptions, "Encoder options");
@@ -159,12 +156,11 @@ public VariantsEncoder getVariantsEncoder(
* that the registry contains an incorrectly written codec.
*/
public VariantsEncoder getVariantsEncoder(
- final Bundle outputBundle,
- final VariantsEncoderOptions variantsEncoderOptions) {
+ final Bundle outputBundle, final VariantsEncoderOptions variantsEncoderOptions) {
ValidationUtils.nonNull(outputBundle, "Output bundle");
ValidationUtils.nonNull(variantsEncoderOptions, "Encoder options");
- //NOTE: we can't allow the resolver to choose the newest registered codec when writing a
+ // NOTE: we can't allow the resolver to choose the newest registered codec when writing a
// VCF, since the newest codec is v4.3, which has no encoder, so for now explicitly select v4.2
final VariantsCodec variantsCodec = resolveForEncoding(outputBundle, VCFCodecV4_2.VCF_V42_VERSION);
return (VariantsEncoder) variantsCodec.getEncoder(outputBundle, variantsEncoderOptions);
@@ -194,8 +190,7 @@ public VariantsEncoder getVariantsEncoder(
ValidationUtils.nonNull(variantsFormat, "Format");
ValidationUtils.nonNull(formatVersion, "Format version");
- return (VariantsEncoder) resolveFormatAndVersion(variantsFormat, formatVersion)
- .getEncoder(outputBundle, variantsEncoderOptions);
+ return (VariantsEncoder)
+ resolveFormatAndVersion(variantsFormat, formatVersion).getEncoder(outputBundle, variantsEncoderOptions);
}
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/variants/VariantsBundle.java b/src/main/java/htsjdk/beta/plugin/variants/VariantsBundle.java
index 2a8dae15e4..128d0d2840 100644
--- a/src/main/java/htsjdk/beta/plugin/variants/VariantsBundle.java
+++ b/src/main/java/htsjdk/beta/plugin/variants/VariantsBundle.java
@@ -8,7 +8,6 @@
import htsjdk.samtools.util.Log;
import htsjdk.samtools.util.Tuple;
import htsjdk.utils.ValidationUtils;
-
import java.io.Serial;
import java.io.Serializable;
import java.nio.file.Files;
@@ -30,6 +29,7 @@
public class VariantsBundle extends Bundle implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
+
private static final Log LOG = Log.getInstance(VariantsBundle.class);
/**
@@ -108,8 +108,8 @@ public static VariantsBundle getVariantsBundleFromPath(final IOPath jsonPath) {
* @param ioPathConstructor a function that takes a string and returns an IOPath-derived class of type {@code T}
* @return a {@link VariantsBundle} created from jsonPath
*/
- public static VariantsBundle getVariantsBundleFromPath(final IOPath jsonPath,
- final Function ioPathConstructor) {
+ public static VariantsBundle getVariantsBundleFromPath(
+ final IOPath jsonPath, final Function ioPathConstructor) {
return getVariantsBundleFromString(IOPathUtils.getStringFromPath(jsonPath), ioPathConstructor);
}
@@ -133,9 +133,9 @@ public static VariantsBundle getVariantsBundleFromString(final String jsonString
* @return a newly created {@link htsjdk.beta.plugin.variants.VariantsBundle}
*/
public static VariantsBundle getVariantsBundleFromString(
- final String jsonString,
- final Function ioPathConstructor) {
- return new VariantsBundle(BundleJSON.toBundle(jsonString, ioPathConstructor).getResources());
+ final String jsonString, final Function ioPathConstructor) {
+ return new VariantsBundle(
+ BundleJSON.toBundle(jsonString, ioPathConstructor).getResources());
}
/**
@@ -166,8 +166,7 @@ public static Optional resolveIndex(final IOPath variants) {
* if it can be found
*/
public static Optional resolveIndex(
- final T variantsHtsPath,
- final Function ioPathConstructor) {
+ final T variantsHtsPath, final Function ioPathConstructor) {
final Set indexExtensions = Set.of(FileExtensions.TRIBBLE_INDEX, FileExtensions.TABIX_INDEX);
for (final String extension : indexExtensions) {
final T putativeIndexPath = IOPathUtils.appendExtension(variantsHtsPath, extension, ioPathConstructor);
@@ -185,9 +184,7 @@ private static IOPathResource toInputResource(final String pr
if (providedContentType != null && !typePair.get().a.equals(providedContentType)) {
LOG.warn(String.format(
"Provided content type \"%s\" for \"%s\" doesn't match derived content type \"%s\"",
- providedContentType,
- ioPath.getRawInputString(),
- typePair.get().a));
+ providedContentType, ioPath.getRawInputString(), typePair.get().a));
}
}
return new IOPathResource(ioPath, providedContentType);
@@ -206,9 +203,11 @@ private static Optional> getInferredCon
if (extension.isPresent()) {
final String ext = extension.get();
if (ext.equals(FileExtensions.VCF)) {
- return Optional.of(new Tuple<>(BundleResourceType.CT_VARIANT_CONTEXTS, BundleResourceType.FMT_VARIANTS_VCF));
+ return Optional.of(
+ new Tuple<>(BundleResourceType.CT_VARIANT_CONTEXTS, BundleResourceType.FMT_VARIANTS_VCF));
} else if (ext.equals(FileExtensions.COMPRESSED_VCF) || ext.equals(FileExtensions.COMPRESSED_VCF_BGZ)) {
- return Optional.of(new Tuple<>(BundleResourceType.CT_VARIANT_CONTEXTS, BundleResourceType.FMT_VARIANTS_VCF));
+ return Optional.of(
+ new Tuple<>(BundleResourceType.CT_VARIANT_CONTEXTS, BundleResourceType.FMT_VARIANTS_VCF));
}
}
return Optional.empty();
diff --git a/src/main/java/htsjdk/beta/plugin/variants/VariantsCodec.java b/src/main/java/htsjdk/beta/plugin/variants/VariantsCodec.java
index 97cc39306b..76591b3f5c 100644
--- a/src/main/java/htsjdk/beta/plugin/variants/VariantsCodec.java
+++ b/src/main/java/htsjdk/beta/plugin/variants/VariantsCodec.java
@@ -9,6 +9,7 @@
public interface VariantsCodec extends HtsCodec {
@Override
- default HtsContentType getContentType() { return HtsContentType.VARIANT_CONTEXTS; }
-
+ default HtsContentType getContentType() {
+ return HtsContentType.VARIANT_CONTEXTS;
+ }
}
diff --git a/src/main/java/htsjdk/beta/plugin/variants/VariantsDecoder.java b/src/main/java/htsjdk/beta/plugin/variants/VariantsDecoder.java
index 1d19461c1c..420388fcdb 100644
--- a/src/main/java/htsjdk/beta/plugin/variants/VariantsDecoder.java
+++ b/src/main/java/htsjdk/beta/plugin/variants/VariantsDecoder.java
@@ -8,4 +8,4 @@
/**
* Base class for all {@link HtsContentType#VARIANT_CONTEXTS} decoders.
*/
-public interface VariantsDecoder extends HtsDecoder { }
+public interface VariantsDecoder extends HtsDecoder {}
diff --git a/src/main/java/htsjdk/beta/plugin/variants/VariantsDecoderOptions.java b/src/main/java/htsjdk/beta/plugin/variants/VariantsDecoderOptions.java
index 46a2abad5a..9a112c2dff 100644
--- a/src/main/java/htsjdk/beta/plugin/variants/VariantsDecoderOptions.java
+++ b/src/main/java/htsjdk/beta/plugin/variants/VariantsDecoderOptions.java
@@ -1,14 +1,13 @@
package htsjdk.beta.plugin.variants;
-import htsjdk.beta.plugin.HtsDecoderOptions;
import htsjdk.annotations.InternalAPI;
-
+import htsjdk.beta.plugin.HtsDecoderOptions;
import java.nio.channels.SeekableByteChannel;
import java.util.Optional;
import java.util.function.Function;
public class VariantsDecoderOptions implements HtsDecoderOptions {
- //TODO: replace these with a prefetch size args, and use a local channel wrapper implementation
+ // TODO: replace these with a prefetch size args, and use a local channel wrapper implementation
private Function variantsChannelTransformer;
private Function indexChannelTransformer;
@@ -63,5 +62,4 @@ public VariantsDecoderOptions setIndexChannelTransformer(
this.indexChannelTransformer = indexChannelTransformer;
return this;
}
-
}
diff --git a/src/main/java/htsjdk/beta/plugin/variants/VariantsEncoder.java b/src/main/java/htsjdk/beta/plugin/variants/VariantsEncoder.java
index 9840047e69..932f3deea2 100644
--- a/src/main/java/htsjdk/beta/plugin/variants/VariantsEncoder.java
+++ b/src/main/java/htsjdk/beta/plugin/variants/VariantsEncoder.java
@@ -8,4 +8,4 @@
/**
* Base class for all {@link HtsContentType#VARIANT_CONTEXTS} encoders.
*/
-public interface VariantsEncoder extends HtsEncoder { }
+public interface VariantsEncoder extends HtsEncoder {}
diff --git a/src/main/java/htsjdk/beta/plugin/variants/VariantsEncoderOptions.java b/src/main/java/htsjdk/beta/plugin/variants/VariantsEncoderOptions.java
index 94182dc4d3..0b09fd3335 100644
--- a/src/main/java/htsjdk/beta/plugin/variants/VariantsEncoderOptions.java
+++ b/src/main/java/htsjdk/beta/plugin/variants/VariantsEncoderOptions.java
@@ -6,12 +6,11 @@
import htsjdk.samtools.Defaults;
public class VariantsEncoderOptions implements HtsEncoderOptions {
- private boolean writeSitesOnly = false;
- private boolean writeFullFormatField = false;
- private boolean allowFieldsMissingFromHeader = false;
- private boolean isAsyncIO = false;
- private int bufferSize = Defaults.NON_ZERO_BUFFER_SIZE; // 128k
-
+ private boolean writeSitesOnly = false;
+ private boolean writeFullFormatField = false;
+ private boolean allowFieldsMissingFromHeader = false;
+ private boolean isAsyncIO = false;
+ private int bufferSize = Defaults.NON_ZERO_BUFFER_SIZE; // 128k
/**
* Get the buffer size used when writing to an {@link IOPathResource}. Defaults
@@ -115,5 +114,4 @@ public VariantsEncoderOptions setWriteFullFormatField(boolean writeFullFormatFie
this.writeFullFormatField = writeFullFormatField;
return this;
}
-
}
diff --git a/src/main/java/htsjdk/io/AsyncWriterPool.java b/src/main/java/htsjdk/io/AsyncWriterPool.java
index f95bcbc7db..dab043ce39 100644
--- a/src/main/java/htsjdk/io/AsyncWriterPool.java
+++ b/src/main/java/htsjdk/io/AsyncWriterPool.java
@@ -1,7 +1,6 @@
package htsjdk.io;
import htsjdk.samtools.util.RuntimeIOException;
-
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
@@ -21,7 +20,6 @@ public class AsyncWriterPool implements Closeable {
private final ExecutorService executor;
private final List> writers = new ArrayList<>();
-
// The amount of time to wait on the queue in the event of catastrophic failure in the writer threads.
private int timeoutSeconds = 5;
@@ -65,7 +63,10 @@ public AsyncWriterPool() {
public void close() throws IOException {
if (this.poolClosed) return;
this.poolClosed = true;
- CompletableFuture.allOf(this.writers.stream().map(PooledWriter::nonBlockingClose).toArray(CompletableFuture[]::new)).join();
+ CompletableFuture.allOf(this.writers.stream()
+ .map(PooledWriter::nonBlockingClose)
+ .toArray(CompletableFuture[]::new))
+ .join();
this.executor.shutdown();
}
@@ -104,7 +105,6 @@ public Writer pool(final Writer writer, final BlockingQueue queue,
return pooledWriter;
}
-
/**
* Any class that implements {@link Writer} can be exchanged for a {@code PooledWriter}. The PooledWriter provides
* the same API as {@link Writer}, but will manage buffering of writes and sending to the {@link AsyncWriterPool} it
@@ -122,7 +122,8 @@ private class PooledWriter implements Writer {
private boolean isClosed = false;
- // Holds the Future of the last task submitted to the AsyncWriterPools until it is checked, then it is null again.
+ // Holds the Future of the last task submitted to the AsyncWriterPools until it is checked, then it is null
+ // again.
private Future currentTask;
/**
@@ -137,7 +138,8 @@ private PooledWriter(final Writer writer, final BlockingQueue queue, final
if (writeThreshold <= 0)
throw new IllegalArgumentException("writeThreshold must be >= 1: " + writeThreshold);
if (writeThreshold > queue.remainingCapacity())
- throw new IllegalArgumentException("writeThreshold (" + writeThreshold + ") can't be larger then queue capacity (" + queue.remainingCapacity() + ").");
+ throw new IllegalArgumentException("writeThreshold (" + writeThreshold
+ + ") can't be larger then queue capacity (" + queue.remainingCapacity() + ").");
this.writer = writer;
this.queue = queue;
@@ -208,7 +210,10 @@ public void write(final A item) {
* normal operations the timeout should not come into play and items will add immediately.
*/
try {
- while (!this.isClosed && !this.queue.offer(item, AsyncWriterPool.this.getTimeoutSeconds(), TimeUnit.SECONDS)) { /* Just wait. */ }
+ while (!this.isClosed
+ && !this.queue.offer(item, AsyncWriterPool.this.getTimeoutSeconds(), TimeUnit.SECONDS)) {
+ /* Just wait. */
+ }
} catch (InterruptedException e) {
throw new RuntimeException("Exception while placing item in queue", e);
}
@@ -251,14 +256,16 @@ private void drain() {
*/
private CompletableFuture nonBlockingClose() {
- return CompletableFuture.supplyAsync(() -> {
- try {
- this.close();
- return null;
- } catch (Exception e) {
- throw new RuntimeException("Caught exception while closing PooledWriter.", e);
- }
- }, AsyncWriterPool.this.executor);
+ return CompletableFuture.supplyAsync(
+ () -> {
+ try {
+ this.close();
+ return null;
+ } catch (Exception e) {
+ throw new RuntimeException("Caught exception while closing PooledWriter.", e);
+ }
+ },
+ AsyncWriterPool.this.executor);
}
/**
diff --git a/src/main/java/htsjdk/io/HtsPath.java b/src/main/java/htsjdk/io/HtsPath.java
index 035b1ff418..f3c2df78b8 100644
--- a/src/main/java/htsjdk/io/HtsPath.java
+++ b/src/main/java/htsjdk/io/HtsPath.java
@@ -1,7 +1,6 @@
package htsjdk.io;
import htsjdk.utils.ValidationUtils;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -71,10 +70,10 @@ public class HtsPath implements IOPath, Serializable {
private static final long serialVersionUID = 1L;
private static final String HIERARCHICAL_SCHEME_SEPARATOR = "://";
- private final String rawInputString; // raw input string provided by th user; may or may not have a scheme
- private final URI uri; // working URI; always has a scheme ("file" if not otherwise specified)
+ private final String rawInputString; // raw input string provided by th user; may or may not have a scheme
+ private final URI uri; // working URI; always has a scheme ("file" if not otherwise specified)
private transient String pathFailureReason; // cache the reason for "toPath" conversion failure
- private transient Path cachedPath; // cache the Path associated with this URI if its "Path-able"
+ private transient Path cachedPath; // cache the Path associated with this URI if its "Path-able"
/**
* Create an HtsPath from a raw input path string.
@@ -117,12 +116,14 @@ public String getURIString() {
* Return the raw input string provided to the constructor.
*/
@Override
- public String getRawInputString() { return rawInputString; }
+ public String getRawInputString() {
+ return rawInputString;
+ }
@Override
public boolean hasFileSystemProvider() {
// try to find a provider; assume that our URI always has a scheme
- for (FileSystemProvider provider: FileSystemProvider.installedProviders()) {
+ for (FileSystemProvider provider : FileSystemProvider.installedProviders()) {
if (provider.getScheme().equalsIgnoreCase(uri.getScheme())) {
return true;
}
@@ -134,10 +135,10 @@ public boolean hasFileSystemProvider() {
public boolean isPath() {
try {
return getCachedPath() != null || toPath() != null;
- } catch (ProviderNotFoundException |
- FileSystemNotFoundException |
- IllegalArgumentException |
- AssertionError e) {
+ } catch (ProviderNotFoundException
+ | FileSystemNotFoundException
+ | IllegalArgumentException
+ | AssertionError e) {
// jimfs throws an AssertionError that wraps a URISyntaxException when trying to create path where
// the scheme-specific part is missing or incorrect
pathFailureReason = e.getMessage();
@@ -192,7 +193,10 @@ public InputStream getInputStream() {
return Files.newInputStream(resourcePath);
} catch (IOException e) {
throw new RuntimeException(
- String.format("Could not create open input stream for %s (as URI %s)", getRawInputString(), getURIString()), e);
+ String.format(
+ "Could not create open input stream for %s (as URI %s)",
+ getRawInputString(), getURIString()),
+ e);
}
}
@@ -206,12 +210,17 @@ public OutputStream getOutputStream() {
try {
return Files.newOutputStream(resourcePath);
} catch (IOException e) {
- throw new RuntimeException(String.format("Could not open output stream for %s (as URI %s)", getRawInputString(), getURIString()), e);
+ throw new RuntimeException(
+ String.format(
+ "Could not open output stream for %s (as URI %s)", getRawInputString(), getURIString()),
+ e);
}
}
// get the cached path associated with this URI if its already been created
- protected Path getCachedPath() { return cachedPath; }
+ protected Path getCachedPath() {
+ return cachedPath;
+ }
protected void setCachedPath(Path path) {
this.cachedPath = path;
@@ -251,8 +260,8 @@ private URI getURIForString(final String pathString) {
tempURI = getCachedPath().toUri();
}
} catch (URISyntaxException uriException) {
- //check that the uri wasn't a badly encoded absolute uri of some sort
- //if you don't do this it will be treated as a badly formed file:// url
+ // check that the uri wasn't a badly encoded absolute uri of some sort
+ // if you don't do this it will be treated as a badly formed file:// url
assertNoProblematicScheme(pathString, uriException);
// the input string isn't a valid URI; assume its a local (non-URI) file reference, and
@@ -265,9 +274,7 @@ private URI getURIForString(final String pathString) {
// the user intended to provide a local file reference or a URI, so preserve both
final String errorMessage = String.format(
"%s can't be interpreted as a local file (%s) or as a URI (%s).",
- pathString,
- pathException.getMessage(),
- uriException.getMessage());
+ pathString, pathException.getMessage(), uriException.getMessage());
throw new IllegalArgumentException(errorMessage, pathException);
}
}
@@ -292,28 +299,30 @@ private URI getURIForString(final String pathString) {
* @param pathString the path being examined
* @param cause the original failure reason
*/
- static void assertNoProblematicScheme(String pathString, URISyntaxException cause){
- if(pathString.equals(HIERARCHICAL_SCHEME_SEPARATOR)){
+ static void assertNoProblematicScheme(String pathString, URISyntaxException cause) {
+ if (pathString.equals(HIERARCHICAL_SCHEME_SEPARATOR)) {
throw new IllegalArgumentException(HIERARCHICAL_SCHEME_SEPARATOR + " is not a valid path.", cause);
}
final String[] split = pathString.split(HIERARCHICAL_SCHEME_SEPARATOR, -1);
final String scheme = split[0];
- if(split.length == 2 && pathString.endsWith(HIERARCHICAL_SCHEME_SEPARATOR)) {
- throw new IllegalArgumentException("A path consisting of only a scheme is not allowed: " + pathString, cause);
+ if (split.length == 2 && pathString.endsWith(HIERARCHICAL_SCHEME_SEPARATOR)) {
+ throw new IllegalArgumentException(
+ "A path consisting of only a scheme is not allowed: " + pathString, cause);
}
- if(split.length > 1){
- if(scheme == null || scheme.isEmpty()){
- throw new IllegalArgumentException("Malformed path " + pathString + " includes an empty scheme.", cause);
+ if (split.length > 1) {
+ if (scheme == null || scheme.isEmpty()) {
+ throw new IllegalArgumentException(
+ "Malformed path " + pathString + " includes an empty scheme.", cause);
}
- if(!scheme.equals("file")){
- throw new IllegalArgumentException("Malformed path " + pathString + " includes a scheme: " + scheme + ":// but was an invalid URI." +
- "\nCheck that it is fully encoded.", cause);
+ if (!scheme.equals("file")) {
+ throw new IllegalArgumentException(
+ "Malformed path " + pathString + " includes a scheme: " + scheme + ":// but was an invalid URI."
+ + "\nCheck that it is fully encoded.",
+ cause);
}
}
-
}
-
}
diff --git a/src/main/java/htsjdk/io/IOPath.java b/src/main/java/htsjdk/io/IOPath.java
index 7f22df3c4a..bd2d3d1873 100644
--- a/src/main/java/htsjdk/io/IOPath.java
+++ b/src/main/java/htsjdk/io/IOPath.java
@@ -2,7 +2,6 @@
import htsjdk.samtools.util.FileExtensions;
import htsjdk.utils.ValidationUtils;
-
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
@@ -91,7 +90,8 @@ default String getScheme() {
default Optional getExtension() {
final String hierarchicalPath = getURI().getPath();
if (hierarchicalPath != null) {
- final int indexOfLastComponent = hierarchicalPath.lastIndexOf(FileSystems.getDefault().getSeparator());
+ final int indexOfLastComponent =
+ hierarchicalPath.lastIndexOf(FileSystems.getDefault().getSeparator());
if (indexOfLastComponent != -1 && indexOfLastComponent < hierarchicalPath.length() - 1) {
final String lastComponent = hierarchicalPath.substring(indexOfLastComponent + 1);
if (lastComponent.length() > 0) {
@@ -127,9 +127,7 @@ default boolean hasExtension(final String extension) {
// We don't want to use {@code #getExtension} here, since it won't work correctly if we're comparing an
// extension that uses multiple . chars, such as .fasta.gz.
final String hierarchicalPath = getURI().getPath();
- return hierarchicalPath == null ?
- false :
- hierarchicalPath.toLowerCase().endsWith(extension.toLowerCase());
+ return hierarchicalPath == null ? false : hierarchicalPath.toLowerCase().endsWith(extension.toLowerCase());
}
/**
@@ -140,7 +138,8 @@ default boolean hasExtension(final String extension) {
*/
default Optional getBaseName() {
final String hierarchicalPath = getURI().getPath();
- final int indexOfLastComponent = hierarchicalPath.lastIndexOf(FileSystems.getDefault().getSeparator());
+ final int indexOfLastComponent =
+ hierarchicalPath.lastIndexOf(FileSystems.getDefault().getSeparator());
if (indexOfLastComponent != -1 && indexOfLastComponent < hierarchicalPath.length() - 1) {
final String lastComponent = hierarchicalPath.substring(indexOfLastComponent + 1);
if (lastComponent.length() > 0) {
diff --git a/src/main/java/htsjdk/samtools/AbstractBAMFileIndex.java b/src/main/java/htsjdk/samtools/AbstractBAMFileIndex.java
index 9df206ecfd..7989ca3184 100644
--- a/src/main/java/htsjdk/samtools/AbstractBAMFileIndex.java
+++ b/src/main/java/htsjdk/samtools/AbstractBAMFileIndex.java
@@ -25,7 +25,6 @@
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.samtools.util.RuntimeIOException;
-
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
@@ -60,11 +59,16 @@ protected AbstractBAMFileIndex(final File file, final SAMSequenceDictionary dict
this(new MemoryMappedFileBuffer(file), file.getName(), dictionary);
}
- protected AbstractBAMFileIndex(final File file, final SAMSequenceDictionary dictionary, final boolean useMemoryMapping) {
- this((useMemoryMapping ? new MemoryMappedFileBuffer(file) : new RandomAccessFileBuffer(file)), file.getName(), dictionary);
+ protected AbstractBAMFileIndex(
+ final File file, final SAMSequenceDictionary dictionary, final boolean useMemoryMapping) {
+ this(
+ (useMemoryMapping ? new MemoryMappedFileBuffer(file) : new RandomAccessFileBuffer(file)),
+ file.getName(),
+ dictionary);
}
- protected AbstractBAMFileIndex(final IndexFileBuffer indexFileBuffer, final String source, final SAMSequenceDictionary dictionary) {
+ protected AbstractBAMFileIndex(
+ final IndexFileBuffer indexFileBuffer, final String source, final SAMSequenceDictionary dictionary) {
mIndexBuffer = indexFileBuffer;
mBamDictionary = dictionary;
verifyIndexMagicNumber(source);
@@ -87,9 +91,10 @@ public static int getNumIndexLevels() {
return GenomicIndexUtil.LEVEL_STARTS.length;
}
- private static void assertLevelIsValid (final int levelNumber) {
+ private static void assertLevelIsValid(final int levelNumber) {
if (levelNumber >= getNumIndexLevels()) {
- throw new SAMException("Level number (" + levelNumber + ") is greater than or equal to maximum (" + getNumIndexLevels() + ").");
+ throw new SAMException("Level number (" + levelNumber + ") is greater than or equal to maximum ("
+ + getNumIndexLevels() + ").");
}
}
@@ -112,7 +117,7 @@ public static int getFirstBinInLevel(final int levelNumber) {
public int getLevelSize(final int levelNumber) {
assertLevelIsValid(levelNumber);
- if (levelNumber == getNumIndexLevels()-1) {
+ if (levelNumber == getNumIndexLevels() - 1) {
return GenomicIndexUtil.MAX_BINS - GenomicIndexUtil.LEVEL_STARTS[levelNumber] - 1;
} else {
return GenomicIndexUtil.LEVEL_STARTS[levelNumber + 1] - GenomicIndexUtil.LEVEL_STARTS[levelNumber];
@@ -125,13 +130,12 @@ public int getLevelSize(final int levelNumber) {
* @return the level associated with the given bin number.
*/
public int getLevelForBin(final Bin bin) {
- if(bin.getBinNumber() >= GenomicIndexUtil.MAX_BINS)
+ if (bin.getBinNumber() >= GenomicIndexUtil.MAX_BINS)
throw new SAMException("Tried to get level for invalid bin.");
- for(int i = getNumIndexLevels()-1; i >= 0; i--) {
- if(bin.getBinNumber() >= GenomicIndexUtil.LEVEL_STARTS[i])
- return i;
+ for (int i = getNumIndexLevels() - 1; i >= 0; i--) {
+ if (bin.getBinNumber() >= GenomicIndexUtil.LEVEL_STARTS[i]) return i;
}
- throw new SAMException("Unable to find correct bin for bin "+bin);
+ throw new SAMException("Unable to find correct bin for bin " + bin);
}
/**
@@ -142,8 +146,11 @@ public int getLevelForBin(final Bin bin) {
public int getFirstLocusInBin(final Bin bin) {
final int level = getLevelForBin(bin);
final int levelStart = GenomicIndexUtil.LEVEL_STARTS[level];
- final int levelSize = ((level==getNumIndexLevels()-1) ? GenomicIndexUtil.MAX_BINS-1 : GenomicIndexUtil.LEVEL_STARTS[level+1]) - levelStart;
- return (bin.getBinNumber() - levelStart)*(GenomicIndexUtil.BIN_GENOMIC_SPAN /levelSize)+1;
+ final int levelSize = ((level == getNumIndexLevels() - 1)
+ ? GenomicIndexUtil.MAX_BINS - 1
+ : GenomicIndexUtil.LEVEL_STARTS[level + 1])
+ - levelStart;
+ return (bin.getBinNumber() - levelStart) * (GenomicIndexUtil.BIN_GENOMIC_SPAN / levelSize) + 1;
}
/**
@@ -154,8 +161,11 @@ public int getFirstLocusInBin(final Bin bin) {
public int getLastLocusInBin(final Bin bin) {
final int level = getLevelForBin(bin);
final int levelStart = GenomicIndexUtil.LEVEL_STARTS[level];
- final int levelSize = ((level==getNumIndexLevels()-1) ? GenomicIndexUtil.MAX_BINS-1 : GenomicIndexUtil.LEVEL_STARTS[level+1]) - levelStart;
- return (bin.getBinNumber()-levelStart+1)*(GenomicIndexUtil.BIN_GENOMIC_SPAN /levelSize);
+ final int levelSize = ((level == getNumIndexLevels() - 1)
+ ? GenomicIndexUtil.MAX_BINS - 1
+ : GenomicIndexUtil.LEVEL_STARTS[level + 1])
+ - levelStart;
+ return (bin.getBinNumber() - levelStart + 1) * (GenomicIndexUtil.BIN_GENOMIC_SPAN / levelSize);
}
public int getNumberOfReferences() {
@@ -271,7 +281,7 @@ protected BAMIndexContent query(final int referenceSequence, final int startPos,
final int binCount = readInteger();
boolean metaDataSeen = false;
- final Bin[] bins = new Bin[getMaxBinNumberForReference(referenceSequence) +1];
+ final Bin[] bins = new Bin[getMaxBinNumberForReference(referenceSequence) + 1];
for (int binNumber = 0; binNumber < binCount; binNumber++) {
final int indexBin = readInteger();
final int nChunks = readInteger();
@@ -279,7 +289,7 @@ protected BAMIndexContent query(final int referenceSequence, final int startPos,
// System.out.println("# bin[" + i + "] = " + indexBin + ", nChunks = " + nChunks);
Chunk lastChunk = null;
if (regionBins.get(indexBin)) {
- chunks = new ArrayList(nChunks);
+ chunks = new ArrayList(nChunks);
readChunks(nChunks, chunks);
} else if (indexBin == GenomicIndexUtil.MAX_BINS) {
// meta data - build the bin so that the count of bins is correct;
@@ -300,20 +310,25 @@ protected BAMIndexContent query(final int referenceSequence, final int startPos,
final int nLinearBins = readInteger();
final int regionLinearBinStart = LinearIndex.convertToLinearIndexOffset(startPos);
- final int regionLinearBinStop = endPos > 0 ? LinearIndex.convertToLinearIndexOffset(endPos) : nLinearBins-1;
- final int actualStop = Math.min(regionLinearBinStop, nLinearBins -1);
+ final int regionLinearBinStop = endPos > 0 ? LinearIndex.convertToLinearIndexOffset(endPos) : nLinearBins - 1;
+ final int actualStop = Math.min(regionLinearBinStop, nLinearBins - 1);
long[] linearIndexEntries = new long[0];
if (regionLinearBinStart < nLinearBins) {
- linearIndexEntries = new long[actualStop-regionLinearBinStart+1];
+ linearIndexEntries = new long[actualStop - regionLinearBinStart + 1];
skipBytes(8 * regionLinearBinStart);
- for(int linearBin = regionLinearBinStart; linearBin <= actualStop; linearBin++)
- linearIndexEntries[linearBin-regionLinearBinStart] = readLong();
+ for (int linearBin = regionLinearBinStart; linearBin <= actualStop; linearBin++)
+ linearIndexEntries[linearBin - regionLinearBinStart] = readLong();
}
- final LinearIndex linearIndex = new LinearIndex(referenceSequence,regionLinearBinStart,linearIndexEntries);
+ final LinearIndex linearIndex = new LinearIndex(referenceSequence, regionLinearBinStart, linearIndexEntries);
- return new BAMIndexContent(referenceSequence, bins, binCount - (metaDataSeen? 1 : 0), new BAMIndexMetaData(metaDataChunks), linearIndex);
+ return new BAMIndexContent(
+ referenceSequence,
+ bins,
+ binCount - (metaDataSeen ? 1 : 0),
+ new BAMIndexMetaData(metaDataChunks),
+ linearIndex);
}
/**
@@ -338,7 +353,7 @@ static int getMaxBinNumberForSequenceLength(final int sequenceLength) {
// return 4680 + (sequenceLength >> 14); // note 4680 = getFirstBinInLevel(getNumIndexLevels() - 1)
}
- abstract protected BAMIndexContent getQueryResults(int reference);
+ protected abstract BAMIndexContent getQueryResults(int reference);
/**
* Gets the possible number of bins for a given reference sequence.
@@ -375,8 +390,7 @@ protected void verifyIndexMagicNumber(final String sourceName) {
final byte[] buffer = new byte[4];
readBytes(buffer);
if (!Arrays.equals(buffer, BAMFileConstants.BAI_INDEX_MAGIC)) {
- throw new RuntimeIOException("Invalid file header in BAM index " + sourceName +
- ": " + new String(buffer));
+ throw new RuntimeIOException("Invalid file header in BAM index " + sourceName + ": " + new String(buffer));
}
}
@@ -399,11 +413,11 @@ protected void readChunks(int nChunks, List chunks) {
}
protected void skipToSequence(final int sequenceIndex) {
- //Use sequence position cache if available
- if(sequenceIndexes[sequenceIndex] != -1){
- seek(sequenceIndexes[sequenceIndex]);
- return;
- }
+ // Use sequence position cache if available
+ if (sequenceIndexes[sequenceIndex] != -1) {
+ seek(sequenceIndexes[sequenceIndex]);
+ return;
+ }
// Use previous sequence position if in cache, which optimizes for common access pattern
// of iterating through sequences in order.
@@ -415,7 +429,7 @@ protected void skipToSequence(final int sequenceIndex) {
} else {
startSequenceIndex = 0;
}
-
+
for (int i = startSequenceIndex; i < sequenceIndex; i++) {
// System.out.println("# Sequence TID: " + i);
final int nBins = readInteger();
@@ -430,8 +444,8 @@ protected void skipToSequence(final int sequenceIndex) {
// System.out.println("# nLinearBins: " + nLinearBins);
skipBytes(8 * nLinearBins);
}
-
- //Update sequence position cache
+
+ // Update sequence position cache
sequenceIndexes[sequenceIndex] = position();
}
@@ -454,16 +468,16 @@ protected final void skipBytes(final int count) {
protected final void seek(final long position) {
mIndexBuffer.seek(position);
}
-
- protected final long position(){
- return mIndexBuffer.position();
+
+ protected final long position() {
+ return mIndexBuffer.position();
}
protected final SAMSequenceDictionary getBamDictionary() {
return mBamDictionary;
}
- protected final void setSequenceIndexes (int nReferences) {
+ protected final void setSequenceIndexes(int nReferences) {
sequenceIndexes = new long[nReferences + 1];
Arrays.fill(sequenceIndexes, -1);
}
diff --git a/src/main/java/htsjdk/samtools/AbstractSAMHeaderRecord.java b/src/main/java/htsjdk/samtools/AbstractSAMHeaderRecord.java
index a3e2ce5966..210d2e0415 100644
--- a/src/main/java/htsjdk/samtools/AbstractSAMHeaderRecord.java
+++ b/src/main/java/htsjdk/samtools/AbstractSAMHeaderRecord.java
@@ -23,7 +23,6 @@
*/
package htsjdk.samtools;
-
import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -33,11 +32,10 @@
* Base class for the various concrete records in a SAM header, providing uniform
* access to the attributes.
*/
-
public abstract class AbstractSAMHeaderRecord implements Serializable {
public static final long serialVersionUID = 1L;
- private final Map mAttributes = new LinkedHashMap();
+ private final Map mAttributes = new LinkedHashMap();
public String getAttribute(final String key) {
return mAttributes.get(key);
@@ -53,7 +51,7 @@ public String getAttribute(final String key) {
*/
@Deprecated
public void setAttribute(final String key, final Object value) {
- setAttribute(key, value == null? null: value.toString());
+ setAttribute(key, value == null ? null : value.toString());
}
/**
@@ -83,11 +81,10 @@ public void setAttribute(final String key, final String value) {
/**
* Returns the Set of attributes.
*/
- public Set> getAttributes() {
+ public Set> getAttributes() {
return mAttributes.entrySet();
}
-
/**
* Returns the ID tag (or equivalent) for this header record. The
* default implementation throws a SAMException to indicate "not implemented".
@@ -118,7 +115,8 @@ protected int attributesHashCode() {
abstract Set getStandardTags();
/** Simple to String that outputs the concrete class name and the set of attributes stored. */
- @Override public String toString() {
+ @Override
+ public String toString() {
return getClass().getSimpleName() + this.mAttributes.toString();
}
@@ -126,5 +124,5 @@ protected int attributesHashCode() {
* Returns the record in the SAM line-based text format. Fields are
* separated by '\t' characters. The String is NOT terminated by '\n'.
*/
- abstract public String getSAMString();
+ public abstract String getSAMString();
}
diff --git a/src/main/java/htsjdk/samtools/AlignmentBlock.java b/src/main/java/htsjdk/samtools/AlignmentBlock.java
index 1320dfdf66..bf41783ff3 100644
--- a/src/main/java/htsjdk/samtools/AlignmentBlock.java
+++ b/src/main/java/htsjdk/samtools/AlignmentBlock.java
@@ -48,11 +48,17 @@ public class AlignmentBlock implements Serializable {
}
/** The first, 1-based, base in the read that is aligned to the reference reference. */
- public int getReadStart() { return readStart; }
+ public int getReadStart() {
+ return readStart;
+ }
/** The first, 1-based, position in the reference to which the read is aligned. */
- public int getReferenceStart() { return referenceStart; }
+ public int getReferenceStart() {
+ return referenceStart;
+ }
/** The number of contiguous bases aligned to the reference. */
- public int getLength() { return length; }
+ public int getLength() {
+ return length;
+ }
}
diff --git a/src/main/java/htsjdk/samtools/AsyncSAMFileWriter.java b/src/main/java/htsjdk/samtools/AsyncSAMFileWriter.java
index ea85458ec3..3d8e0f561c 100644
--- a/src/main/java/htsjdk/samtools/AsyncSAMFileWriter.java
+++ b/src/main/java/htsjdk/samtools/AsyncSAMFileWriter.java
@@ -33,16 +33,25 @@ public AsyncSAMFileWriter(final SAMFileWriter out, final int queueSize) {
this.underlyingWriter = out;
}
- @Override protected void synchronouslyWrite(final SAMRecord item) { this.underlyingWriter.addAlignment(item); }
+ @Override
+ protected void synchronouslyWrite(final SAMRecord item) {
+ this.underlyingWriter.addAlignment(item);
+ }
- @Override protected void synchronouslyClose() { this.underlyingWriter.close(); }
+ @Override
+ protected void synchronouslyClose() {
+ this.underlyingWriter.close();
+ }
- @Override protected final String getThreadNamePrefix() { return "SAMFileWriterThread-"; }
+ @Override
+ protected final String getThreadNamePrefix() {
+ return "SAMFileWriterThread-";
+ }
- @Override
- public void setProgressLogger(final ProgressLoggerInterface progress) {
- this.underlyingWriter.setProgressLogger(progress);
- }
+ @Override
+ public void setProgressLogger(final ProgressLoggerInterface progress) {
+ this.underlyingWriter.setProgressLogger(progress);
+ }
@Override
public void setSortOrderChecking(boolean check) {
diff --git a/src/main/java/htsjdk/samtools/BAMFileConstants.java b/src/main/java/htsjdk/samtools/BAMFileConstants.java
index 638c56cc56..8192bf5612 100644
--- a/src/main/java/htsjdk/samtools/BAMFileConstants.java
+++ b/src/main/java/htsjdk/samtools/BAMFileConstants.java
@@ -36,7 +36,6 @@ class BAMFileConstants {
* BAM file magic number. This is what is present in the gunzipped version of the file,
* which never exists on disk.
*/
-
static final byte[] BAM_MAGIC = "BAM\1".getBytes();
/**
* BAM index file magic numbers.
@@ -44,6 +43,7 @@ class BAMFileConstants {
*/
@Deprecated
static final byte[] BAM_INDEX_MAGIC = "BAI\1".getBytes();
+
static final byte[] BAI_INDEX_MAGIC = "BAI\1".getBytes();
static final byte[] CSI_INDEX_MAGIC = "CSI\1".getBytes();
@@ -51,6 +51,7 @@ class BAMFileConstants {
* CSI index related constants
*/
static final int CSI_MAGIC_OFFSET = 0;
+
static final int CSI_MINSHIFT_OFFSET = 4;
static final int CSI_AUXDATA_OFFSET = 12;
static final int CSI_CHUNK_SIZE = 16;
diff --git a/src/main/java/htsjdk/samtools/BAMFileReader.java b/src/main/java/htsjdk/samtools/BAMFileReader.java
index 3693eeba8c..9667174d32 100644
--- a/src/main/java/htsjdk/samtools/BAMFileReader.java
+++ b/src/main/java/htsjdk/samtools/BAMFileReader.java
@@ -23,11 +23,9 @@
*/
package htsjdk.samtools;
-
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.samtools.util.*;
import htsjdk.samtools.util.zip.InflaterFactory;
-
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
@@ -94,15 +92,22 @@ public class BAMFileReader extends SamReader.ReaderImplementation {
* @param samRecordFactory SAM record factory
* @throws IOException
*/
- BAMFileReader(final InputStream stream,
- final File indexFile,
- final boolean eagerDecode,
- final boolean useAsynchronousIO,
- final ValidationStringency validationStringency,
- final SAMRecordFactory samRecordFactory)
+ BAMFileReader(
+ final InputStream stream,
+ final File indexFile,
+ final boolean eagerDecode,
+ final boolean useAsynchronousIO,
+ final ValidationStringency validationStringency,
+ final SAMRecordFactory samRecordFactory)
throws IOException {
- this(stream, indexFile, eagerDecode, useAsynchronousIO, validationStringency, samRecordFactory,
- BlockGunzipper.getDefaultInflaterFactory());
+ this(
+ stream,
+ indexFile,
+ eagerDecode,
+ useAsynchronousIO,
+ validationStringency,
+ samRecordFactory,
+ BlockGunzipper.getDefaultInflaterFactory());
}
/**
@@ -116,17 +121,20 @@ public class BAMFileReader extends SamReader.ReaderImplementation {
* @param inflaterFactory InflaterFactory used by BlockCompressedInputStream
* @throws IOException
*/
- BAMFileReader(final InputStream stream,
- final File indexFile,
- final boolean eagerDecode,
- final boolean useAsynchronousIO,
- final ValidationStringency validationStringency,
- final SAMRecordFactory samRecordFactory,
- final InflaterFactory inflaterFactory)
+ BAMFileReader(
+ final InputStream stream,
+ final File indexFile,
+ final boolean eagerDecode,
+ final boolean useAsynchronousIO,
+ final ValidationStringency validationStringency,
+ final SAMRecordFactory samRecordFactory,
+ final InflaterFactory inflaterFactory)
throws IOException {
mIndexFile = indexFile;
mIsSeekable = false;
- mCompressedInputStream = useAsynchronousIO ? new AsyncBlockCompressedInputStream(stream, inflaterFactory) : new BlockCompressedInputStream(stream, inflaterFactory);
+ mCompressedInputStream = useAsynchronousIO
+ ? new AsyncBlockCompressedInputStream(stream, inflaterFactory)
+ : new BlockCompressedInputStream(stream, inflaterFactory);
mStream = new BinaryCodec(new DataInputStream(mCompressedInputStream));
this.eagerDecode = eagerDecode;
this.mValidationStringency = validationStringency;
@@ -144,14 +152,22 @@ public class BAMFileReader extends SamReader.ReaderImplementation {
* @param samRecordFactory SAM record factory
* @throws IOException
*/
- BAMFileReader(final File file,
- final File indexFile,
- final boolean eagerDecode,
- final boolean useAsynchronousIO,
- final ValidationStringency validationStringency,
- final SAMRecordFactory samRecordFactory)
- throws IOException {
- this(file, indexFile, eagerDecode, useAsynchronousIO, validationStringency, samRecordFactory, BlockGunzipper.getDefaultInflaterFactory());
+ BAMFileReader(
+ final File file,
+ final File indexFile,
+ final boolean eagerDecode,
+ final boolean useAsynchronousIO,
+ final ValidationStringency validationStringency,
+ final SAMRecordFactory samRecordFactory)
+ throws IOException {
+ this(
+ file,
+ indexFile,
+ eagerDecode,
+ useAsynchronousIO,
+ validationStringency,
+ samRecordFactory,
+ BlockGunzipper.getDefaultInflaterFactory());
}
/**
@@ -165,20 +181,29 @@ public class BAMFileReader extends SamReader.ReaderImplementation {
* @param inflaterFactory InflaterFactory used by BlockCompressedInputStream
* @throws IOException
*/
- BAMFileReader(final File file,
- final File indexFile,
- final boolean eagerDecode,
- final boolean useAsynchronousIO,
- final ValidationStringency validationStringency,
- final SAMRecordFactory samRecordFactory,
- final InflaterFactory inflaterFactory)
- throws IOException {
- this(useAsynchronousIO ? new AsyncBlockCompressedInputStream(file, inflaterFactory) : new BlockCompressedInputStream(file, inflaterFactory),
- indexFile!=null ? indexFile : SamFiles.findIndex(file), eagerDecode, useAsynchronousIO, file.getAbsolutePath(), validationStringency, samRecordFactory);
+ BAMFileReader(
+ final File file,
+ final File indexFile,
+ final boolean eagerDecode,
+ final boolean useAsynchronousIO,
+ final ValidationStringency validationStringency,
+ final SAMRecordFactory samRecordFactory,
+ final InflaterFactory inflaterFactory)
+ throws IOException {
+ this(
+ useAsynchronousIO
+ ? new AsyncBlockCompressedInputStream(file, inflaterFactory)
+ : new BlockCompressedInputStream(file, inflaterFactory),
+ indexFile != null ? indexFile : SamFiles.findIndex(file),
+ eagerDecode,
+ useAsynchronousIO,
+ file.getAbsolutePath(),
+ validationStringency,
+ samRecordFactory);
if (mIndexFile != null && mIndexFile.lastModified() < file.lastModified() - 5000) {
- System.err.println("WARNING: BAM index file " + mIndexFile.getAbsolutePath() +
- " is older than BAM " + file.getAbsolutePath());
+ System.err.println("WARNING: BAM index file " + mIndexFile.getAbsolutePath() + " is older than BAM "
+ + file.getAbsolutePath());
}
// Provide better error message when there is an error reading.
@@ -195,14 +220,22 @@ public class BAMFileReader extends SamReader.ReaderImplementation {
* @param samRecordFactory SAM record factory
* @throws IOException
*/
- BAMFileReader(final SeekableStream strm,
- final File indexFile,
- final boolean eagerDecode,
- final boolean useAsynchronousIO,
- final ValidationStringency validationStringency,
- final SAMRecordFactory samRecordFactory)
- throws IOException {
- this(strm, indexFile, eagerDecode, useAsynchronousIO, validationStringency, samRecordFactory, BlockGunzipper.getDefaultInflaterFactory());
+ BAMFileReader(
+ final SeekableStream strm,
+ final File indexFile,
+ final boolean eagerDecode,
+ final boolean useAsynchronousIO,
+ final ValidationStringency validationStringency,
+ final SAMRecordFactory samRecordFactory)
+ throws IOException {
+ this(
+ strm,
+ indexFile,
+ eagerDecode,
+ useAsynchronousIO,
+ validationStringency,
+ samRecordFactory,
+ BlockGunzipper.getDefaultInflaterFactory());
}
/**
@@ -216,16 +249,25 @@ public class BAMFileReader extends SamReader.ReaderImplementation {
* @param inflaterFactory InflaterFactory used by BlockCompressedInputStream
* @throws IOException
*/
- BAMFileReader(final SeekableStream strm,
- final File indexFile,
- final boolean eagerDecode,
- final boolean useAsynchronousIO,
- final ValidationStringency validationStringency,
- final SAMRecordFactory samRecordFactory,
- final InflaterFactory inflaterFactory)
- throws IOException {
- this(useAsynchronousIO ? new AsyncBlockCompressedInputStream(strm, inflaterFactory) : new BlockCompressedInputStream(strm, inflaterFactory),
- indexFile, eagerDecode, useAsynchronousIO, strm.getSource(), validationStringency, samRecordFactory);
+ BAMFileReader(
+ final SeekableStream strm,
+ final File indexFile,
+ final boolean eagerDecode,
+ final boolean useAsynchronousIO,
+ final ValidationStringency validationStringency,
+ final SAMRecordFactory samRecordFactory,
+ final InflaterFactory inflaterFactory)
+ throws IOException {
+ this(
+ useAsynchronousIO
+ ? new AsyncBlockCompressedInputStream(strm, inflaterFactory)
+ : new BlockCompressedInputStream(strm, inflaterFactory),
+ indexFile,
+ eagerDecode,
+ useAsynchronousIO,
+ strm.getSource(),
+ validationStringency,
+ samRecordFactory);
}
/**
@@ -238,14 +280,22 @@ public class BAMFileReader extends SamReader.ReaderImplementation {
* @param samRecordFactory SAM record factory
* @throws IOException
*/
- BAMFileReader(final SeekableStream strm,
- final SeekableStream indexStream,
- final boolean eagerDecode,
- final boolean useAsynchronousIO,
- final ValidationStringency validationStringency,
- final SAMRecordFactory samRecordFactory)
- throws IOException {
- this(strm, indexStream, eagerDecode, useAsynchronousIO, validationStringency, samRecordFactory, BlockGunzipper.getDefaultInflaterFactory());
+ BAMFileReader(
+ final SeekableStream strm,
+ final SeekableStream indexStream,
+ final boolean eagerDecode,
+ final boolean useAsynchronousIO,
+ final ValidationStringency validationStringency,
+ final SAMRecordFactory samRecordFactory)
+ throws IOException {
+ this(
+ strm,
+ indexStream,
+ eagerDecode,
+ useAsynchronousIO,
+ validationStringency,
+ samRecordFactory,
+ BlockGunzipper.getDefaultInflaterFactory());
}
/**
@@ -259,16 +309,25 @@ public class BAMFileReader extends SamReader.ReaderImplementation {
* @param inflaterFactory InflaterFactory used by BlockCompressedInputStream
* @throws IOException
*/
- BAMFileReader(final SeekableStream strm,
- final SeekableStream indexStream,
- final boolean eagerDecode,
- final boolean useAsynchronousIO,
- final ValidationStringency validationStringency,
- final SAMRecordFactory samRecordFactory,
- final InflaterFactory inflaterFactory)
- throws IOException {
- this(useAsynchronousIO ? new AsyncBlockCompressedInputStream(strm, inflaterFactory) : new BlockCompressedInputStream(strm, inflaterFactory),
- indexStream, eagerDecode, useAsynchronousIO, strm.getSource(), validationStringency, samRecordFactory);
+ BAMFileReader(
+ final SeekableStream strm,
+ final SeekableStream indexStream,
+ final boolean eagerDecode,
+ final boolean useAsynchronousIO,
+ final ValidationStringency validationStringency,
+ final SAMRecordFactory samRecordFactory,
+ final InflaterFactory inflaterFactory)
+ throws IOException {
+ this(
+ useAsynchronousIO
+ ? new AsyncBlockCompressedInputStream(strm, inflaterFactory)
+ : new BlockCompressedInputStream(strm, inflaterFactory),
+ indexStream,
+ eagerDecode,
+ useAsynchronousIO,
+ strm.getSource(),
+ validationStringency,
+ samRecordFactory);
}
/**
@@ -282,14 +341,15 @@ public class BAMFileReader extends SamReader.ReaderImplementation {
* @param samRecordFactory SAM record factory
* @throws IOException
*/
- private BAMFileReader(final BlockCompressedInputStream compressedInputStream,
- final File indexFile,
- final boolean eagerDecode,
- final boolean useAsynchronousIO,
- final String source,
- final ValidationStringency validationStringency,
- final SAMRecordFactory samRecordFactory)
- throws IOException {
+ private BAMFileReader(
+ final BlockCompressedInputStream compressedInputStream,
+ final File indexFile,
+ final boolean eagerDecode,
+ final boolean useAsynchronousIO,
+ final String source,
+ final ValidationStringency validationStringency,
+ final SAMRecordFactory samRecordFactory)
+ throws IOException {
mIndexFile = indexFile;
mIsSeekable = true;
mCompressedInputStream = compressedInputStream;
@@ -312,14 +372,15 @@ private BAMFileReader(final BlockCompressedInputStream compressedInputStream,
* @param samRecordFactory SAM record factory
* @throws IOException
*/
- private BAMFileReader(final BlockCompressedInputStream compressedInputStream,
- final SeekableStream indexStream,
- final boolean eagerDecode,
- final boolean useAsynchronousIO,
- final String source,
- final ValidationStringency validationStringency,
- final SAMRecordFactory samRecordFactory)
- throws IOException {
+ private BAMFileReader(
+ final BlockCompressedInputStream compressedInputStream,
+ final SeekableStream indexStream,
+ final boolean eagerDecode,
+ final boolean useAsynchronousIO,
+ final String source,
+ final ValidationStringency validationStringency,
+ final SAMRecordFactory samRecordFactory)
+ throws IOException {
mIndexStream = indexStream;
mIsSeekable = true;
mCompressedInputStream = compressedInputStream;
@@ -333,7 +394,8 @@ private BAMFileReader(final BlockCompressedInputStream compressedInputStream,
/** Reads through the header and sequence records to find the virtual file offset of the first record in the BAM file. */
static long findVirtualOffsetOfFirstRecord(final File bam) throws IOException {
- final BAMFileReader reader = new BAMFileReader(bam, null, false, false, ValidationStringency.SILENT, new DefaultSAMRecordFactory());
+ final BAMFileReader reader =
+ new BAMFileReader(bam, null, false, false, ValidationStringency.SILENT, new DefaultSAMRecordFactory());
final long offset = reader.mFirstRecordPointer;
reader.close();
return offset;
@@ -344,7 +406,13 @@ static long findVirtualOffsetOfFirstRecord(final File bam) throws IOException {
* The caller is responsible for closing the stream.
*/
static long findVirtualOffsetOfFirstRecord(final SeekableStream seekableStream) throws IOException {
- final BAMFileReader reader = new BAMFileReader(seekableStream, (SeekableStream) null, false, false, ValidationStringency.SILENT, new DefaultSAMRecordFactory());
+ final BAMFileReader reader = new BAMFileReader(
+ seekableStream,
+ (SeekableStream) null,
+ false,
+ false,
+ ValidationStringency.SILENT,
+ new DefaultSAMRecordFactory());
return reader.mFirstRecordPointer;
}
@@ -363,7 +431,7 @@ void enableFileSource(final SamReader reader, final boolean enabled) {
*/
@Override
protected void enableIndexCaching(final boolean enabled) {
- if(mIndex != null)
+ if (mIndex != null)
throw new SAMException("Unable to turn on index caching; index file has already been loaded.");
this.mEnableIndexCaching = enabled;
}
@@ -381,11 +449,15 @@ protected void enableIndexMemoryMapping(final boolean enabled) {
this.mEnableIndexMemoryMapping = enabled;
}
- @Override void enableCrcChecking(final boolean enabled) {
+ @Override
+ void enableCrcChecking(final boolean enabled) {
this.mCompressedInputStream.setCheckCrcs(enabled);
}
- @Override void setSAMRecordFactory(final SAMRecordFactory samRecordFactory) { this.samRecordFactory = samRecordFactory; }
+ @Override
+ void setSAMRecordFactory(final SAMRecordFactory samRecordFactory) {
+ this.samRecordFactory = samRecordFactory;
+ }
@Override
public SamReader.Type type() {
@@ -409,26 +481,27 @@ public boolean hasIndex() {
*/
@Override
public BAMIndex getIndex() {
- if(!hasIndex()) {
+ if (!hasIndex()) {
throw new SAMException("No index is available for this BAM file.");
}
- if(mIndex == null) {
+ if (mIndex == null) {
final SamIndexes samIndexType = getIndexType();
final SAMSequenceDictionary sequenceDictionary = getFileHeader().getSequenceDictionary();
- if(mIndexFile != null) {
+ if (mIndexFile != null) {
if (samIndexType.equals(SamIndexes.BAI)) {
- mIndex = mEnableIndexCaching ? new CachingBAMFileIndex(mIndexFile, sequenceDictionary, mEnableIndexMemoryMapping)
+ mIndex = mEnableIndexCaching
+ ? new CachingBAMFileIndex(mIndexFile, sequenceDictionary, mEnableIndexMemoryMapping)
: new DiskBasedBAMFileIndex(mIndexFile, sequenceDictionary, mEnableIndexMemoryMapping);
} else if (samIndexType.equals(SamIndexes.CSI)) {
mIndex = new CSIIndex(mIndexFile, mEnableIndexMemoryMapping, sequenceDictionary);
} else {
throw new SAMFormatException("Unsupported BAM index file format: " + mIndexFile.getName());
}
- } else if(mIndexStream != null) {
+ } else if (mIndexStream != null) {
if (samIndexType.equals(SamIndexes.BAI)) {
mIndex = new CachingBAMFileIndex(mIndexStream, sequenceDictionary);
} else if (samIndexType.equals(SamIndexes.CSI)) {
- mIndex = new CSIIndex(mIndexStream, sequenceDictionary);
+ mIndex = new CSIIndex(mIndexStream, sequenceDictionary);
} else {
throw new SAMFormatException("Unsupported BAM index file format: " + mIndexStream.getSource());
}
@@ -455,13 +528,16 @@ public SamIndexes getIndexType() {
if (samIndexesType == SamIndexes.BAI || samIndexesType == SamIndexes.CSI) {
return samIndexesType;
}
- throw new SAMFormatException(String.format("Unknown BAM index file type: %s in %s", samIndexesType, mIndexStream.getSource()));
+ throw new SAMFormatException(
+ String.format("Unknown BAM index file type: %s in %s", samIndexesType, mIndexStream.getSource()));
}
return null;
}
- public void setEagerDecode(final boolean desired) { this.eagerDecode = desired; }
+ public void setEagerDecode(final boolean desired) {
+ this.eagerDecode = desired;
+ }
@Override
public void close() {
@@ -541,7 +617,7 @@ public CloseableIterator getIterator(final SAMFileSpan chunks) {
}
// Create an iterator over the given chunk boundaries.
- mCurrentIterator = new BAMFileIndexIterator(((BAMFileSpan)chunks).toCoordinateArray());
+ mCurrentIterator = new BAMFileIndexIterator(((BAMFileSpan) chunks).toCoordinateArray());
return mCurrentIterator;
}
@@ -553,7 +629,7 @@ public CloseableIterator getIterator(final SAMFileSpan chunks) {
*/
@Override
public SAMFileSpan getFilePointerSpanningReads() {
- return new BAMFileSpan(new Chunk(mFirstRecordPointer,Long.MAX_VALUE));
+ return new BAMFileSpan(new Chunk(mFirstRecordPointer, Long.MAX_VALUE));
}
/**
@@ -704,8 +780,9 @@ public CloseableIterator queryUnmapped() {
* @param validationStringency Determines how stringent to be when validating the sam
* @param source Note that this is used only for reporting errors.
*/
- protected static SAMFileHeader readHeader(final BinaryCodec stream, final ValidationStringency validationStringency, final String source)
- throws IOException {
+ protected static SAMFileHeader readHeader(
+ final BinaryCodec stream, final ValidationStringency validationStringency, final String source)
+ throws IOException {
final byte[] buffer = new byte[4];
stream.readBytes(buffer);
@@ -717,27 +794,27 @@ protected static SAMFileHeader readHeader(final BinaryCodec stream, final Valida
final String textHeader = stream.readString(headerTextLength);
final SAMTextHeaderCodec headerCodec = new SAMTextHeaderCodec();
headerCodec.setValidationStringency(validationStringency);
- final SAMFileHeader samFileHeader = headerCodec.decode(BufferedLineReader.fromString(textHeader),
- source);
+ final SAMFileHeader samFileHeader = headerCodec.decode(BufferedLineReader.fromString(textHeader), source);
final int sequenceCount = stream.readInt();
if (!samFileHeader.getSequenceDictionary().isEmpty()) {
// It is allowed to have binary sequences but no text sequences, so only validate if both are present
if (sequenceCount != samFileHeader.getSequenceDictionary().size()) {
- throw new SAMFormatException("Number of sequences in text header (" +
- samFileHeader.getSequenceDictionary().size() +
- ") != number of sequences in binary header (" + sequenceCount + ") for file " + source);
+ throw new SAMFormatException("Number of sequences in text header ("
+ + samFileHeader.getSequenceDictionary().size()
+ + ") != number of sequences in binary header ("
+ + sequenceCount + ") for file " + source);
}
for (int i = 0; i < sequenceCount; i++) {
final SAMSequenceRecord binarySequenceRecord = readSequenceRecord(stream, source);
final SAMSequenceRecord sequenceRecord = samFileHeader.getSequence(i);
if (!sequenceRecord.getSequenceName().equals(binarySequenceRecord.getSequenceName())) {
- throw new SAMFormatException("For sequence " + i + ", text and binary have different names in file " +
- source);
+ throw new SAMFormatException(
+ "For sequence " + i + ", text and binary have different names in file " + source);
}
if (sequenceRecord.getSequenceLength() != binarySequenceRecord.getSequenceLength()) {
- throw new SAMFormatException("For sequence " + i + ", text and binary have different lengths in file " +
- source);
+ throw new SAMFormatException(
+ "For sequence " + i + ", text and binary have different lengths in file " + source);
}
}
} else {
@@ -794,7 +871,6 @@ protected void assertOpen() {
public void remove() {
throw new UnsupportedOperationException("Not supported: remove");
}
-
}
private class EmptyBamIterator extends AbstractBamIterator {
@@ -810,8 +886,8 @@ public SAMRecord next() {
}
/**
-
- /**
+ *
+ * /**
* Iterator for non-indexed sequential iteration through all SAMRecords in file.
* Starting point of iteration is wherever current file position is when the iterator is constructed.
*/
@@ -829,8 +905,8 @@ private class BAMFileIterator extends AbstractBamIterator {
*/
BAMFileIterator(final boolean advance) {
this.bamRecordCodec = new BAMRecordCodec(getFileHeader(), samRecordFactory);
- this.bamRecordCodec.setInputStream(BAMFileReader.this.mStream.getInputStream(),
- BAMFileReader.this.mStream.getInputFileName());
+ this.bamRecordCodec.setInputStream(
+ BAMFileReader.this.mStream.getInputStream(), BAMFileReader.this.mStream.getInputFileName());
if (advance) {
advance();
@@ -861,9 +937,10 @@ void advance() {
mNextRecord.setValidationStringency(mValidationStringency);
if (mValidationStringency != ValidationStringency.SILENT) {
- final List validationErrors = mNextRecord.isValid(mValidationStringency == ValidationStringency.STRICT);
- SAMUtils.processValidationErrors(validationErrors,
- this.samRecordIndex, BAMFileReader.this.getValidationStringency());
+ final List validationErrors =
+ mNextRecord.isValid(mValidationStringency == ValidationStringency.STRICT);
+ SAMUtils.processValidationErrors(
+ validationErrors, this.samRecordIndex, BAMFileReader.this.getValidationStringency());
}
}
if (eagerDecode && mNextRecord != null) {
@@ -882,8 +959,9 @@ SAMRecord getNextRecord() throws IOException {
final SAMRecord next = bamRecordCodec.decode();
final long stopCoordinate = mCompressedInputStream.getFilePointer();
- if(mReader != null && next != null)
- next.setFileSource(new SAMFileSource(mReader,new BAMFileSpan(new Chunk(startCoordinate,stopCoordinate))));
+ if (mReader != null && next != null)
+ next.setFileSource(
+ new SAMFileSource(mReader, new BAMFileSpan(new Chunk(startCoordinate, stopCoordinate))));
return next;
}
@@ -901,8 +979,7 @@ protected SAMRecord peek() {
* @param referenceIndex Desired reference sequence.
* @param start 1-based alignment start.
*/
- private CloseableIterator createStartingAtIndexIterator(final int referenceIndex,
- final int start) {
+ private CloseableIterator createStartingAtIndexIterator(final int referenceIndex, final int start) {
// Hit the index to determine the chunk boundaries for the required data.
final BAMIndex fileIndex = getIndex();
@@ -914,7 +991,7 @@ private CloseableIterator createStartingAtIndexIterator(final int ref
// Add some preprocessing filters for edge-case reads that don't fit into this
// query type.
- return new BAMQueryFilteringIterator(iterator,new BAMStartingAtIteratorFilter(referenceIndex,start));
+ return new BAMQueryFilteringIterator(iterator, new BAMStartingAtIteratorFilter(referenceIndex, start));
}
/**
@@ -927,7 +1004,8 @@ public static BAMFileSpan getFileSpan(QueryInterval[] intervals, BAMIndex fileIn
final BAMFileSpan[] inputSpans = new BAMFileSpan[intervals.length];
for (int i = 0; i < intervals.length; ++i) {
final QueryInterval interval = intervals[i];
- final BAMFileSpan span = fileIndex.getSpanOverlapping(interval.referenceIndex, interval.start, interval.end);
+ final BAMFileSpan span =
+ fileIndex.getSpanOverlapping(interval.referenceIndex, interval.start, interval.end);
inputSpans[i] = span;
}
final BAMFileSpan span;
@@ -939,8 +1017,7 @@ public static BAMFileSpan getFileSpan(QueryInterval[] intervals, BAMIndex fileIn
return span;
}
- private CloseableIterator createIndexIterator(final QueryInterval[] intervals,
- final boolean contained) {
+ private CloseableIterator createIndexIterator(final QueryInterval[] intervals, final boolean contained) {
QueryInterval.assertIntervalsOptimized(intervals);
@@ -951,7 +1028,8 @@ private CloseableIterator createIndexIterator(final QueryInterval[] i
// Add some preprocessing filters for edge-case reads that don't fit into this
// query type.
- return new BAMQueryFilteringIterator(iterator, new BAMQueryMultipleIntervalsIteratorFilter(intervals, contained));
+ return new BAMQueryFilteringIterator(
+ iterator, new BAMQueryMultipleIntervalsIteratorFilter(intervals, contained));
}
/**
@@ -962,9 +1040,8 @@ private CloseableIterator createIndexIterator(final QueryInterval[] i
* @param filePointers file pointer pairs corresponding to chunk boundaries for the
* intervals
*/
- public CloseableIterator createIndexIterator(final QueryInterval[] intervals,
- final boolean contained,
- final long[] filePointers) {
+ public CloseableIterator createIndexIterator(
+ final QueryInterval[] intervals, final boolean contained, final long[] filePointers) {
QueryInterval.assertIntervalsOptimized(intervals);
@@ -973,7 +1050,8 @@ public CloseableIterator createIndexIterator(final QueryInterval[] in
// Add some preprocessing filters for edge-case reads that don't fit into this
// query type.
- return new BAMQueryFilteringIterator(iterator, new BAMQueryMultipleIntervalsIteratorFilter(intervals, contained));
+ return new BAMQueryFilteringIterator(
+ iterator, new BAMQueryMultipleIntervalsIteratorFilter(intervals, contained));
}
/**
@@ -998,18 +1076,16 @@ private class BAMFileIndexIterator extends BAMFileIterator {
* @param filePointers the block / offset combination, stored in chunk format.
*/
BAMFileIndexIterator(final long[] filePointers) {
- super(false); // delay advance() until after construction
+ super(false); // delay advance() until after construction
mFilePointers = filePointers;
advance();
}
@Override
- SAMRecord getNextRecord()
- throws IOException {
+ SAMRecord getNextRecord() throws IOException {
// Advance to next file block if necessary
while (mCompressedInputStream.getFilePointer() >= mFilePointerLimit) {
- if (mFilePointers == null ||
- mFilePointerIndex >= mFilePointers.length) {
+ if (mFilePointers == null || mFilePointerIndex >= mFilePointers.length) {
return null;
}
final long startOffset = mFilePointers[mFilePointerIndex++];
@@ -1034,10 +1110,11 @@ public class BAMQueryFilteringIterator extends AbstractBamIterator {
* The next record to be returned. Will be null if no such record exists.
*/
protected SAMRecord mNextRecord;
+
private final BAMIteratorFilter iteratorFilter;
- public BAMQueryFilteringIterator(final CloseableIterator iterator,
- final BAMIteratorFilter iteratorFilter) {
+ public BAMQueryFilteringIterator(
+ final CloseableIterator iterator, final BAMIteratorFilter iteratorFilter) {
this.wrappedIterator = iterator;
this.iteratorFilter = iteratorFilter;
mNextRecord = advance();
@@ -1058,8 +1135,7 @@ public boolean hasNext() {
*/
@Override
public SAMRecord next() {
- if(!hasNext())
- throw new NoSuchElementException("BAMQueryFilteringIterator: no next element available");
+ if (!hasNext()) throw new NoSuchElementException("BAMQueryFilteringIterator: no next element available");
final SAMRecord currentRead = mNextRecord;
mNextRecord = advance();
return currentRead;
@@ -1068,21 +1144,24 @@ public SAMRecord next() {
SAMRecord advance() {
while (true) {
// Pull next record from stream
- if(!wrappedIterator.hasNext())
- return null;
+ if (!wrappedIterator.hasNext()) return null;
final SAMRecord record = wrappedIterator.next();
switch (iteratorFilter.compareToFilter(record)) {
- case MATCHES_FILTER: return record;
- case STOP_ITERATION: return null;
- case CONTINUE_ITERATION: break; // keep looping
- default: throw new SAMException("Unexpected return from compareToFilter");
+ case MATCHES_FILTER:
+ return record;
+ case STOP_ITERATION:
+ return null;
+ case CONTINUE_ITERATION:
+ break; // keep looping
+ default:
+ throw new SAMException("Unexpected return from compareToFilter");
}
}
}
}
- private class BAMFileIndexUnmappedIterator extends BAMFileIterator {
+ private class BAMFileIndexUnmappedIterator extends BAMFileIterator {
private BAMFileIndexUnmappedIterator() {
while (this.hasNext() && peek().getReferenceIndex() != SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX) {
advance();
diff --git a/src/main/java/htsjdk/samtools/BAMFileSpan.java b/src/main/java/htsjdk/samtools/BAMFileSpan.java
index d99760d2a8..4fe90198e7 100644
--- a/src/main/java/htsjdk/samtools/BAMFileSpan.java
+++ b/src/main/java/htsjdk/samtools/BAMFileSpan.java
@@ -24,7 +24,6 @@
package htsjdk.samtools;
import htsjdk.samtools.util.StringUtil;
-
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
@@ -90,8 +89,7 @@ public boolean isEmpty() {
@Override
public BAMFileSpan clone() {
final BAMFileSpan clone = new BAMFileSpan();
- for(final Chunk chunk: chunks)
- clone.chunks.add(chunk.clone());
+ for (final Chunk chunk : chunks) clone.chunks.add(chunk.clone());
return clone;
}
@@ -104,30 +102,26 @@ public BAMFileSpan clone() {
*/
@Override
public SAMFileSpan removeContentsBefore(final SAMFileSpan fileSpan) {
- if(fileSpan == null)
- return clone();
+ if (fileSpan == null) return clone();
- if(!(fileSpan instanceof BAMFileSpan))
- throw new SAMException("Unable to compare ");
+ if (!(fileSpan instanceof BAMFileSpan)) throw new SAMException("Unable to compare ");
- final BAMFileSpan bamFileSpan = (BAMFileSpan)fileSpan;
+ final BAMFileSpan bamFileSpan = (BAMFileSpan) fileSpan;
- if(bamFileSpan.isEmpty())
- return clone();
+ if (bamFileSpan.isEmpty()) return clone();
validateSorted();
final BAMFileSpan trimmedChunkList = new BAMFileSpan();
final long chunkStart = bamFileSpan.chunks.get(0).getChunkStart();
- for(final Chunk chunkToTrim: chunks) {
- if(chunkToTrim.getChunkEnd() > chunkStart) {
- if(chunkToTrim.getChunkStart() >= chunkStart) {
+ for (final Chunk chunkToTrim : chunks) {
+ if (chunkToTrim.getChunkEnd() > chunkStart) {
+ if (chunkToTrim.getChunkStart() >= chunkStart) {
// This chunk from the list is completely beyond the start of the filtering chunk.
trimmedChunkList.add(chunkToTrim.clone());
- }
- else {
+ } else {
// This chunk from the list partially overlaps the filtering chunk and must be trimmed.
- trimmedChunkList.add(new Chunk(chunkStart,chunkToTrim.getChunkEnd()));
+ trimmedChunkList.add(new Chunk(chunkStart, chunkToTrim.getChunkEnd()));
}
}
}
@@ -143,30 +137,27 @@ public SAMFileSpan removeContentsBefore(final SAMFileSpan fileSpan) {
* given chunk.
*/
public SAMFileSpan removeContentsAfter(final SAMFileSpan fileSpan) {
- if(fileSpan == null)
- return clone();
+ if (fileSpan == null) return clone();
- if(!(fileSpan instanceof BAMFileSpan))
- throw new SAMException("Unable to compare ");
+ if (!(fileSpan instanceof BAMFileSpan)) throw new SAMException("Unable to compare ");
- final BAMFileSpan bamFileSpan = (BAMFileSpan)fileSpan;
+ final BAMFileSpan bamFileSpan = (BAMFileSpan) fileSpan;
- if(bamFileSpan.isEmpty())
- return clone();
+ if (bamFileSpan.isEmpty()) return clone();
validateSorted();
final BAMFileSpan trimmedChunkList = new BAMFileSpan();
- final long chunkEnd = bamFileSpan.chunks.get(bamFileSpan.chunks.size() - 1).getChunkEnd();
- for(final Chunk chunkToTrim: chunks) {
- if(chunkToTrim.getChunkStart() < chunkEnd) {
- if(chunkToTrim.getChunkEnd() <= chunkEnd) {
+ final long chunkEnd =
+ bamFileSpan.chunks.get(bamFileSpan.chunks.size() - 1).getChunkEnd();
+ for (final Chunk chunkToTrim : chunks) {
+ if (chunkToTrim.getChunkStart() < chunkEnd) {
+ if (chunkToTrim.getChunkEnd() <= chunkEnd) {
// This chunk from the list is completely before the end of the filtering chunk.
trimmedChunkList.add(chunkToTrim.clone());
- }
- else {
+ } else {
// This chunk from the list partially overlaps the filtering chunk and must be trimmed.
- trimmedChunkList.add(new Chunk(chunkToTrim.getChunkStart(),chunkEnd));
+ trimmedChunkList.add(new Chunk(chunkToTrim.getChunkStart(), chunkEnd));
}
}
}
@@ -179,10 +170,10 @@ public SAMFileSpan removeContentsAfter(final SAMFileSpan fileSpan) {
*/
@Override
public SAMFileSpan getContentsFollowing() {
- if(chunks.isEmpty())
+ if (chunks.isEmpty())
throw new SAMException("Unable to get the file pointer following this one: no data present.");
validateSorted();
- return new BAMFileSpan(new Chunk(chunks.get(chunks.size()-1).getChunkEnd(),Long.MAX_VALUE));
+ return new BAMFileSpan(new Chunk(chunks.get(chunks.size() - 1).getChunkEnd(), Long.MAX_VALUE));
}
/**
@@ -228,7 +219,7 @@ public long[] toCoordinateArray() {
*/
public long getFirstOffset() {
final long result = 0;
- if (chunks == null){
+ if (chunks == null) {
return result;
}
for (final Chunk chunk : chunks) {
@@ -250,7 +241,7 @@ public List getChunks() {
* @return The single chunk stored in this span
*/
protected Chunk getSingleChunk() {
- if (chunks.size() != 1){
+ if (chunks.size() != 1) {
throw new SAMException("Expecting a single chunk for span. Found " + chunks.size());
}
return chunks.get(0);
@@ -265,12 +256,12 @@ protected Chunk getSingleChunk() {
* @return A list of chunks.
*/
protected static SAMFileSpan toChunkList(final long[] coordinateArray) {
- if(coordinateArray.length % 2 != 0)
+ if (coordinateArray.length % 2 != 0)
throw new SAMException("Data supplied does not appear to be in coordinate array format.");
final BAMFileSpan chunkList = new BAMFileSpan();
- for(int i = 0; i < coordinateArray.length; i += 2)
- chunkList.add(new Chunk(coordinateArray[i],coordinateArray[i+1]));
+ for (int i = 0; i < coordinateArray.length; i += 2)
+ chunkList.add(new Chunk(coordinateArray[i], coordinateArray[i + 1]));
chunkList.validateSorted();
@@ -281,9 +272,10 @@ protected static SAMFileSpan toChunkList(final long[] coordinateArray) {
* Validates the list of chunks to ensure that they appear in sorted order.
*/
private void validateSorted() {
- for(int i = 1; i < chunks.size(); i++) {
- if(chunks.get(i).getChunkStart() < chunks.get(i-1).getChunkEnd())
- throw new SAMException(String.format("Chunk list is unsorted; chunk %s is before chunk %s",chunks.get(i-1),chunks.get(i)));
+ for (int i = 1; i < chunks.size(); i++) {
+ if (chunks.get(i).getChunkStart() < chunks.get(i - 1).getChunkEnd())
+ throw new SAMException(String.format(
+ "Chunk list is unsorted; chunk %s is before chunk %s", chunks.get(i - 1), chunks.get(i)));
}
}
@@ -303,7 +295,7 @@ public String toString() {
public static BAMFileSpan merge(final BAMFileSpan[] spans) {
final ArrayList inputChunks = new ArrayList();
for (final BAMFileSpan span : spans) {
- if(span != null){
+ if (span != null) {
inputChunks.addAll(span.chunks);
}
}
diff --git a/src/main/java/htsjdk/samtools/BAMFileWriter.java b/src/main/java/htsjdk/samtools/BAMFileWriter.java
index ae6f6a0c26..b2e3381493 100644
--- a/src/main/java/htsjdk/samtools/BAMFileWriter.java
+++ b/src/main/java/htsjdk/samtools/BAMFileWriter.java
@@ -29,7 +29,6 @@
import htsjdk.samtools.util.IOUtil;
import htsjdk.samtools.util.RuntimeIOException;
import htsjdk.samtools.util.zip.DeflaterFactory;
-
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
@@ -72,19 +71,25 @@ protected BAMFileWriter(final OutputStream os, final File file, final int compre
outputBinaryCodec.setOutputFileName(getPathString(file));
}
- protected BAMFileWriter(final OutputStream os, final File file, final int compressionLevel, final DeflaterFactory deflaterFactory) {
+ protected BAMFileWriter(
+ final OutputStream os, final File file, final int compressionLevel, final DeflaterFactory deflaterFactory) {
blockCompressedOutputStream = new BlockCompressedOutputStream(os, file, compressionLevel, deflaterFactory);
outputBinaryCodec = new BinaryCodec(blockCompressedOutputStream);
outputBinaryCodec.setOutputFileName(getPathString(file));
}
- protected BAMFileWriter(final OutputStream os, final String absoluteFilename, final int compressionLevel, final DeflaterFactory deflaterFactory) {
- blockCompressedOutputStream = new BlockCompressedOutputStream(os, (Path)null, compressionLevel, deflaterFactory);
- outputBinaryCodec = new BinaryCodec(blockCompressedOutputStream);
- outputBinaryCodec.setOutputFileName(absoluteFilename);
+ protected BAMFileWriter(
+ final OutputStream os,
+ final String absoluteFilename,
+ final int compressionLevel,
+ final DeflaterFactory deflaterFactory) {
+ blockCompressedOutputStream =
+ new BlockCompressedOutputStream(os, (Path) null, compressionLevel, deflaterFactory);
+ outputBinaryCodec = new BinaryCodec(blockCompressedOutputStream);
+ outputBinaryCodec.setOutputFileName(absoluteFilename);
}
- private void prepareToWriteAlignments() {
+ private void prepareToWriteAlignments() {
if (bamRecordCodec == null) {
bamRecordCodec = new BAMRecordCodec(getFileHeader());
bamRecordCodec.setOutputStream(outputBinaryCodec.getOutputStream(), getFilename());
@@ -92,17 +97,17 @@ private void prepareToWriteAlignments() {
}
/** @return absolute path, or null if arg is null. */
- private String getPathString(final File path){
+ private String getPathString(final File path) {
return (path != null) ? path.getAbsolutePath() : null;
}
- // Allow enabling the bam index construction
- // only enabled by factory method before anything is written
- void enableBamIndexConstruction () {
- if (!getSortOrder().equals(SAMFileHeader.SortOrder.coordinate)){
- throw new SAMException("Not creating BAM index since not sorted by coordinates: " + getSortOrder());
+ // Allow enabling the bam index construction
+ // only enabled by factory method before anything is written
+ void enableBamIndexConstruction() {
+ if (!getSortOrder().equals(SAMFileHeader.SortOrder.coordinate)) {
+ throw new SAMException("Not creating BAM index since not sorted by coordinates: " + getSortOrder());
}
- if(getFilename() == null){
+ if (getFilename() == null) {
throw new SAMException("Not creating BAM index since we don't have an output file name");
}
bamIndexer = createBamIndex(getFilename());
@@ -110,12 +115,13 @@ void enableBamIndexConstruction () {
private BAMIndexer createBamIndex(final String pathURI) {
try {
- final String indexFileBase = pathURI.endsWith(FileExtensions.BAM) ?
- pathURI.substring(0, pathURI.lastIndexOf('.')) : pathURI;
+ final String indexFileBase =
+ pathURI.endsWith(FileExtensions.BAM) ? pathURI.substring(0, pathURI.lastIndexOf('.')) : pathURI;
final Path indexPath = IOUtil.getPath(indexFileBase + FileExtensions.BAI_INDEX);
if (Files.exists(indexPath)) {
if (!Files.isWritable(indexPath)) {
- throw new SAMException("Not creating BAM index since unable to write index file " + indexPath.toUri());
+ throw new SAMException(
+ "Not creating BAM index since unable to write index file " + indexPath.toUri());
}
}
return new BAMIndexer(indexPath, getFileHeader());
@@ -153,13 +159,13 @@ protected void writeHeader(final String textHeader) {
@Override
protected void finish() {
outputBinaryCodec.close();
- try {
- if (bamIndexer != null) {
- bamIndexer.finish();
- }
- } catch (Exception e) {
- throw new SAMException("Exception writing BAM index file", e);
+ try {
+ if (bamIndexer != null) {
+ bamIndexer.finish();
}
+ } catch (Exception e) {
+ throw new SAMException("Exception writing BAM index file", e);
+ }
}
/** @return absolute path in URI format, or null if this writer does not correspond to a file.
@@ -173,7 +179,8 @@ protected String getFilename() {
* Writes a header to a BAM file. samFileHeader and headerText are redundant - one can be used to regenerate the other but in
* some instances we already have both so this allows us to save some cycles
*/
- protected static void writeHeader(final BinaryCodec outputBinaryCodec, final SAMFileHeader samFileHeader, final String headerText) {
+ protected static void writeHeader(
+ final BinaryCodec outputBinaryCodec, final SAMFileHeader samFileHeader, final String headerText) {
outputBinaryCodec.writeBytes(BAMFileConstants.BAM_MAGIC);
// calculate and write the length of the SAM file header text and the header text
@@ -181,7 +188,8 @@ protected static void writeHeader(final BinaryCodec outputBinaryCodec, final SAM
// write the sequences binarily. This is redundant with the text header
outputBinaryCodec.writeInt(samFileHeader.getSequenceDictionary().size());
- for (final SAMSequenceRecord sequenceRecord: samFileHeader.getSequenceDictionary().getSequences()) {
+ for (final SAMSequenceRecord sequenceRecord :
+ samFileHeader.getSequenceDictionary().getSequences()) {
outputBinaryCodec.writeString(sequenceRecord.getSequenceName(), true, true);
outputBinaryCodec.writeInt(sequenceRecord.getSequenceLength());
}
@@ -203,7 +211,8 @@ protected static void writeHeader(final BinaryCodec outputBinaryCodec, final SAM
* @param samFileHeader the header to write
*/
public static void writeHeader(final OutputStream outputStream, final SAMFileHeader samFileHeader) {
- final BlockCompressedOutputStream blockCompressedOutputStream = new BlockCompressedOutputStream(outputStream, (Path)null);
+ final BlockCompressedOutputStream blockCompressedOutputStream =
+ new BlockCompressedOutputStream(outputStream, (Path) null);
final BinaryCodec outputBinaryCodec = new BinaryCodec(blockCompressedOutputStream);
writeHeader(outputBinaryCodec, samFileHeader);
try {
diff --git a/src/main/java/htsjdk/samtools/BAMIndex.java b/src/main/java/htsjdk/samtools/BAMIndex.java
index ffc93993ce..d55797241e 100644
--- a/src/main/java/htsjdk/samtools/BAMIndex.java
+++ b/src/main/java/htsjdk/samtools/BAMIndex.java
@@ -23,9 +23,8 @@
*/
package htsjdk.samtools;
-import java.io.Closeable;
-
import htsjdk.samtools.util.FileExtensions;
+import java.io.Closeable;
/**
* A basic interface for querying BAM indices.
@@ -55,7 +54,7 @@ public interface BAMIndex extends Closeable {
* Gets the compressed chunks which should be searched for the contents of records contained by the span
* referenceIndex:startPos-endPos, inclusive. See the BAM spec for more information on how a chunk is
* represented.
- *
+ *
* @param referenceIndex The contig.
* @param startPos Genomic start of query.
* @param endPos Genomic end of query.
diff --git a/src/main/java/htsjdk/samtools/BAMIndexContent.java b/src/main/java/htsjdk/samtools/BAMIndexContent.java
index be9d856aa0..d4dd047f78 100644
--- a/src/main/java/htsjdk/samtools/BAMIndexContent.java
+++ b/src/main/java/htsjdk/samtools/BAMIndexContent.java
@@ -1,69 +1,75 @@
-/*
- * The MIT License
- *
- * Copyright (c) 2010 The Broad Institute
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-package htsjdk.samtools;
-
-/**
- * Represents the contents of a bam index file for one reference.
- * A BAM index (.bai) file contains information for all references in the bam file.
- * This class describes the data present in the index file for one of these references;
- * including the bins, chunks, and linear index.
- */
-class BAMIndexContent extends BinningIndexContent {
- /**
- * Chunks containing metaData for the reference, e.g. number of aligned and unaligned records
- */
- private final BAMIndexMetaData mMetaData;
-
-
-
- /**
- * @param referenceSequence Content corresponds to this reference.
- * @param binList Array of bins represented by this content, possibly sparse
- * @param metaData Extra information about the reference in this index
- * @param linearIndex Additional index used to optimize queries
- */
- BAMIndexContent(final int referenceSequence, final BinList binList, final BAMIndexMetaData metaData, final LinearIndex linearIndex) {
- super(referenceSequence, binList, linearIndex);
- this.mMetaData = metaData;
- }
-
- /**
- * @param referenceSequence Content corresponds to this reference.
- * @param bins Array of bins represented by this content, possibly sparse
- * @param numberOfBins Number of non-null bins
- * @param metaData Extra information about the reference in this index
- * @param linearIndex Additional index used to optimize queries
- */
- BAMIndexContent(final int referenceSequence, final Bin[] bins, final int numberOfBins, final BAMIndexMetaData metaData, final LinearIndex linearIndex) {
- this(referenceSequence, new BinList(bins, numberOfBins), metaData, linearIndex);
- }
-
- /**
- * @return the meta data chunks for this content
- */
- public BAMIndexMetaData getMetaData() {
- return mMetaData;
- }
-
-}
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2010 The Broad Institute
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package htsjdk.samtools;
+
+/**
+ * Represents the contents of a bam index file for one reference.
+ * A BAM index (.bai) file contains information for all references in the bam file.
+ * This class describes the data present in the index file for one of these references;
+ * including the bins, chunks, and linear index.
+ */
+class BAMIndexContent extends BinningIndexContent {
+ /**
+ * Chunks containing metaData for the reference, e.g. number of aligned and unaligned records
+ */
+ private final BAMIndexMetaData mMetaData;
+
+ /**
+ * @param referenceSequence Content corresponds to this reference.
+ * @param binList Array of bins represented by this content, possibly sparse
+ * @param metaData Extra information about the reference in this index
+ * @param linearIndex Additional index used to optimize queries
+ */
+ BAMIndexContent(
+ final int referenceSequence,
+ final BinList binList,
+ final BAMIndexMetaData metaData,
+ final LinearIndex linearIndex) {
+ super(referenceSequence, binList, linearIndex);
+ this.mMetaData = metaData;
+ }
+
+ /**
+ * @param referenceSequence Content corresponds to this reference.
+ * @param bins Array of bins represented by this content, possibly sparse
+ * @param numberOfBins Number of non-null bins
+ * @param metaData Extra information about the reference in this index
+ * @param linearIndex Additional index used to optimize queries
+ */
+ BAMIndexContent(
+ final int referenceSequence,
+ final Bin[] bins,
+ final int numberOfBins,
+ final BAMIndexMetaData metaData,
+ final LinearIndex linearIndex) {
+ this(referenceSequence, new BinList(bins, numberOfBins), metaData, linearIndex);
+ }
+
+ /**
+ * @return the meta data chunks for this content
+ */
+ public BAMIndexMetaData getMetaData() {
+ return mMetaData;
+ }
+}
diff --git a/src/main/java/htsjdk/samtools/BAMIndexMerger.java b/src/main/java/htsjdk/samtools/BAMIndexMerger.java
index 2d0890e750..0ba360cd74 100644
--- a/src/main/java/htsjdk/samtools/BAMIndexMerger.java
+++ b/src/main/java/htsjdk/samtools/BAMIndexMerger.java
@@ -25,7 +25,6 @@
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.samtools.util.BlockCompressedFilePointerUtil;
-
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
@@ -78,8 +77,9 @@ public void processIndex(final AbstractBAMFileIndex index, final long partLength
sequenceDictionary = index.getBamDictionary();
}
if (index.getNumberOfReferences() != numReferences) {
- throw new IllegalArgumentException(
- String.format("Cannot merge BAI files with different number of references, %s and %s.", numReferences, index.getNumberOfReferences()));
+ throw new IllegalArgumentException(String.format(
+ "Cannot merge BAI files with different number of references, %s and %s.",
+ numReferences, index.getNumberOfReferences()));
}
index.getBamDictionary().assertSameDictionary(sequenceDictionary);
// just store the indexes rather than computing the BAMIndexContent for each ref,
@@ -99,7 +99,8 @@ public void finish(final long dataFileLength) {
try (BinaryBAMIndexWriter writer = new BinaryBAMIndexWriter(numReferences, out)) {
for (int ref = 0; ref < numReferences; ref++) {
final int r = ref;
- List bamIndexContentList = indexes.stream().map(index -> index.getQueryResults(r)).collect(Collectors.toList());
+ List bamIndexContentList =
+ indexes.stream().map(index -> index.getQueryResults(r)).collect(Collectors.toList());
final BAMIndexContent bamIndexContent = mergeBAMIndexContent(ref, bamIndexContentList, offsets);
writer.writeReference(bamIndexContent);
}
@@ -111,8 +112,8 @@ public static AbstractBAMFileIndex openIndex(SeekableStream stream, SAMSequenceD
return new CachingBamFileIndexOptimizedForMerging(stream, dictionary);
}
- private static BAMIndexContent mergeBAMIndexContent(final int referenceSequence,
- final List bamIndexContentList, final long[] offsets) {
+ private static BAMIndexContent mergeBAMIndexContent(
+ final int referenceSequence, final List bamIndexContentList, final long[] offsets) {
final List binLists = new ArrayList<>();
final List metaDataList = new ArrayList<>();
final List linearIndexes = new ArrayList<>();
@@ -140,9 +141,14 @@ private static BAMIndexContent mergeBAMIndexContent(final int referenceSequence,
* @param offsets bin i will be shifted by offset i
* @return the merged bins
*/
- public static BinningIndexContent.BinList mergeBins(final List binLists, final long[] offsets) {
+ public static BinningIndexContent.BinList mergeBins(
+ final List binLists, final long[] offsets) {
final List mergedBins = new ArrayList<>();
- final int maxBinNumber = binLists.stream().filter(Objects::nonNull).mapToInt(bl -> bl.maxBinNumber).max().orElse(0);
+ final int maxBinNumber = binLists.stream()
+ .filter(Objects::nonNull)
+ .mapToInt(bl -> bl.maxBinNumber)
+ .max()
+ .orElse(0);
int commonNonNullBins = 0;
for (int i = 0; i <= maxBinNumber; i++) {
final List nonNullBins = new ArrayList<>();
@@ -161,8 +167,11 @@ public static BinningIndexContent.BinList mergeBins(final List bins) {
final List allChunks = new ArrayList<>();
for (Bin b : bins) {
if (b.getReferenceSequence() != referenceSequence) {
- throw new IllegalArgumentException(String.format("Bins have different reference sequences, %s and %s.", b.getReferenceSequence(), referenceSequence));
+ throw new IllegalArgumentException(String.format(
+ "Bins have different reference sequences, %s and %s.",
+ b.getReferenceSequence(), referenceSequence));
}
if (b.getBinNumber() != binNumber) {
- throw new IllegalArgumentException(String.format("Bins have different numbers, %s and %s.", b.getBinNumber(), binNumber));
+ throw new IllegalArgumentException(
+ String.format("Bins have different numbers, %s and %s.", b.getBinNumber(), binNumber));
}
allChunks.addAll(b.getChunkList());
}
@@ -241,7 +253,8 @@ private static BAMIndexMetaData mergeMetaData(final List metaD
* @param offsets linear index i will be shifted by offset i
* @return the merged linear index
*/
- public static LinearIndex mergeLinearIndexes(final int referenceSequence, final List linearIndexes, final long[] offsets) {
+ public static LinearIndex mergeLinearIndexes(
+ final int referenceSequence, final List linearIndexes, final long[] offsets) {
int maxIndex = -1;
for (LinearIndex li : linearIndexes) {
if (li == null) {
diff --git a/src/main/java/htsjdk/samtools/BAMIndexMetaData.java b/src/main/java/htsjdk/samtools/BAMIndexMetaData.java
index e2b1818bec..8e4ad4531a 100644
--- a/src/main/java/htsjdk/samtools/BAMIndexMetaData.java
+++ b/src/main/java/htsjdk/samtools/BAMIndexMetaData.java
@@ -1,287 +1,289 @@
-/*
- * The MIT License
- *
- * Copyright (c) 2010 The Broad Institute
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-package htsjdk.samtools;
-
-import htsjdk.samtools.cram.BAIEntry;
-import htsjdk.samtools.util.BlockCompressedFilePointerUtil;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-
-/**
- * Metadata about the bam index contained within the bam index.
- * One instance created per index file.
- */
-public class BAMIndexMetaData {
-
- // information for the entire index.
- // stored at the end of the index
- private long noCoordinateRecords = 0;
-
- // information for each reference.
- // stored in two chunks in bin # MAX_BINS
- private long firstOffset = -1;
- private long lastOffset = 0;
- private int alignedRecords = 0;
- private int unAlignedRecords = 0; // unmapped, but associated with this reference
-
-
- /**
- * Constructor used when writing an index
- * construct one instance for each index generated
- */
- BAMIndexMetaData() {
- noCoordinateRecords = 0;
- newReference();
- }
-
- /**
- * Constructor used when reading an index
- * construct one instance for each index generated
- */
- BAMIndexMetaData(List chunkList) {
- noCoordinateRecords = 0;
-
- if (chunkList == null || chunkList.isEmpty()) {
- // System.out.println("No metadata chunks");
- } else if (chunkList.size() != 2) {
- throw new SAMException("Unexpected number of metadata chunks " + (chunkList.size()));
- }
- // fill in the first/lastOffset un/alignedRecords from this
- boolean firstChunk = true;
- if (chunkList != null) {
- for (Chunk c : chunkList) {
- long start = c.getChunkStart();
- long end = c.getChunkEnd();
- if (firstChunk) {
- firstOffset = start;
- lastOffset = end;
- firstChunk = false;
- } else {
- firstChunk = true;
- alignedRecords = (int) start;
- unAlignedRecords = (int) end;
- }
- }
- }
- }
-
- private BAMIndexMetaData(final long firstOffset, final long lastOffset, final int alignedRecords, final int unAlignedRecords) {
- this.firstOffset = firstOffset;
- this.lastOffset = lastOffset;
- this.alignedRecords = alignedRecords;
- this.unAlignedRecords = unAlignedRecords;
- }
-
- /**
- * @return the count of aligned records associated with this reference
- */
- public int getAlignedRecordCount() {
- return alignedRecords;
- }
-
- /**
- * @return the count of unaligned records associated with this reference
- */
- public int getUnalignedRecordCount() {
- return unAlignedRecords;
- }
-
- /**
- * Call for each new reference sequence encountered
- */
- void newReference() {
- firstOffset = -1;
- lastOffset = 0;
- alignedRecords = 0;
- unAlignedRecords = 0;
- }
-
- /**
- * Extract relevant metaData from the record and its filePointer
- * Call only once per record in the file being indexed
- *
- * @param rec
- */
- void recordMetaData(final SAMRecord rec) {
-
- final int alignmentStart = rec.getAlignmentStart();
- if (alignmentStart == SAMRecord.NO_ALIGNMENT_START) {
- incrementNoCoordinateRecordCount();
- return;
- }
-
- if (rec.getFileSource() == null) {
- throw new SAMException("BAM cannot be indexed without setting a fileSource for record " + rec);
- }
- final Chunk newChunk = ((BAMFileSpan) rec.getFileSource().getFilePointer()).getSingleChunk();
- final long start = newChunk.getChunkStart();
- final long end = newChunk.getChunkEnd();
-
- if (rec.getReadUnmappedFlag()) {
- unAlignedRecords++;
- } else {
- alignedRecords++;
- }
- if (BlockCompressedFilePointerUtil.compare(start, firstOffset) < 1 || firstOffset == -1) {
- this.firstOffset = start;
- }
- if (BlockCompressedFilePointerUtil.compare(lastOffset, end) < 1) {
- this.lastOffset = end;
- }
- }
-
- // The resolution of a CRAM BAI index is more coarse than for BAM BAI. Each entry
- // is represented by a BAIEntry that represents a slice (or, in the case of
- // MULTI_REFERENCE slices, a subset of a slice), rather than SAMRecords.
- void recordMetaData(final BAIEntry baiEntry) {
- alignedRecords += baiEntry.getMappedReadsCount();
- noCoordinateRecords += baiEntry.getUnmappedUnplacedReadsCount();
- unAlignedRecords += baiEntry.getUnmappedReadsCount();
-
- final long start = baiEntry.getSliceByteOffsetFromCompressionHeaderStart();
-
- if (BlockCompressedFilePointerUtil.compare(start, firstOffset) < 1 || firstOffset == -1) {
- this.firstOffset = start;
- // not actually used, so set it to a dummy value (start)
- // see https://github.com/samtools/htsjdk/issues/401
- this.lastOffset = start;
- }
- }
-
- /**
- * Call whenever a reference with no coordinate information is encountered in the bam file
- */
- void incrementNoCoordinateRecordCount() {
- noCoordinateRecords++;
- }
-
- /**
- * Set local variable. Normally noCoordinateRecord count accessed from AbstractBAMFileIndex when reading
- */
- private void setNoCoordinateRecordCount(long count) {
- noCoordinateRecords = count;
- }
-
-
- /**
- * @return the count of records with no coordinate information in the bam file.
- * Not public, since only used by BAMIndexer when writing bam index.
- * Readers of bam index should use AbstractBAMFileIndex.getNoCoordinateRecordCount.
- */
- long getNoCoordinateRecordCount() {
- return noCoordinateRecords;
- }
-
- /**
- * @return the first virtual file offset used by this reference
- */
- long getFirstOffset() {
- return firstOffset;
- }
-
- /**
- * @return the last virtual file offset used by this reference
- */
- long getLastOffset() {
- return lastOffset;
- }
-
- /**
- * Return a new metadata object shifted by a given (non-virtual) offset.
- *
- * @param offset the offset in bytes
- * @return a new metadata object shifted by the given offset
- * @see BlockCompressedFilePointerUtil#shift(long, long)
- */
- BAMIndexMetaData shift(final long offset) {
- final long newFirstOffset = firstOffset == -1 ? firstOffset : BlockCompressedFilePointerUtil.shift(firstOffset, offset); // -1 is unset
- final long newLastOffset = lastOffset == 0 ? lastOffset : BlockCompressedFilePointerUtil.shift(lastOffset, offset); // 0 is unset
- return new BAMIndexMetaData(newFirstOffset, newLastOffset, alignedRecords, unAlignedRecords);
- }
-
- /**
- * Prints meta-data statistics from BAM index (.bai or .csi) file
- * Statistics include count of aligned and unaligned reads for each reference sequence
- * and a count of all records with no start coordinate
- */
- static public void printIndexStats(final File inputBamFile) {
- try {
- final BAMFileReader bam = new BAMFileReader(inputBamFile, null, false, false, ValidationStringency.SILENT, new DefaultSAMRecordFactory());
- if (!bam.hasIndex() || bam.getIndexType() == null) {
- throw new SAMException("No index for bam file " + inputBamFile);
- }
-
- BAMIndexMetaData[] data = getIndexStats(bam);
- if (data == null) {
- throw new SAMException("Exception in getting index statistics");
- }
-
- // read through all the bins of every reference.
- int nRefs = bam.getFileHeader().getSequenceDictionary().size();
- for (int i = 0; i < nRefs; i++) {
- final SAMSequenceRecord seq = bam.getFileHeader().getSequence(i);
- if (seq == null) continue;
- final String sequenceName = seq.getSequenceName();
- final int sequenceLength = seq.getSequenceLength();
- System.out.print(sequenceName + ' ' + "length=\t" + sequenceLength);
- if (data[i] == null) {
- System.out.println();
- continue;
- }
- System.out.println("\tAligned= " + data[i].getAlignedRecordCount() +
- "\tUnaligned= " + data[i].getUnalignedRecordCount());
- }
- System.out.println("NoCoordinateCount= " + data[0].getNoCoordinateRecordCount());
- } catch (IOException e) {
- throw new SAMException("Exception in getting index statistics", e);
- }
- }
-
- /**
- * Prints meta-data statistics from BAM index (.bai or .csi) file
- * Statistics include count of aligned and unaligned reads for each reference sequence
- * and a count of all records with no start coordinate
- */
- static public BAMIndexMetaData[] getIndexStats(final BAMFileReader bam) {
-
- AbstractBAMFileIndex index = (AbstractBAMFileIndex) bam.getIndex();
- // read through all the bins of every reference.
- int nRefs = index.getNumberOfReferences();
- BAMIndexMetaData[] result = new BAMIndexMetaData[nRefs == 0 ? 1 : nRefs];
- for (int i = 0; i < nRefs; i++) {
- result[i] = index.getMetaData(i);
- }
-
- if (result[0] == null) {
- result[0] = new BAMIndexMetaData();
- }
- final Long noCoordCount = index.getNoCoordinateCount();
- if (noCoordCount != null) // null in old index files without metadata
- result[0].setNoCoordinateRecordCount(noCoordCount);
-
- return result;
- }
-}
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2010 The Broad Institute
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package htsjdk.samtools;
+
+import htsjdk.samtools.cram.BAIEntry;
+import htsjdk.samtools.util.BlockCompressedFilePointerUtil;
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * Metadata about the bam index contained within the bam index.
+ * One instance created per index file.
+ */
+public class BAMIndexMetaData {
+
+ // information for the entire index.
+ // stored at the end of the index
+ private long noCoordinateRecords = 0;
+
+ // information for each reference.
+ // stored in two chunks in bin # MAX_BINS
+ private long firstOffset = -1;
+ private long lastOffset = 0;
+ private int alignedRecords = 0;
+ private int unAlignedRecords = 0; // unmapped, but associated with this reference
+
+ /**
+ * Constructor used when writing an index
+ * construct one instance for each index generated
+ */
+ BAMIndexMetaData() {
+ noCoordinateRecords = 0;
+ newReference();
+ }
+
+ /**
+ * Constructor used when reading an index
+ * construct one instance for each index generated
+ */
+ BAMIndexMetaData(List chunkList) {
+ noCoordinateRecords = 0;
+
+ if (chunkList == null || chunkList.isEmpty()) {
+ // System.out.println("No metadata chunks");
+ } else if (chunkList.size() != 2) {
+ throw new SAMException("Unexpected number of metadata chunks " + (chunkList.size()));
+ }
+ // fill in the first/lastOffset un/alignedRecords from this
+ boolean firstChunk = true;
+ if (chunkList != null) {
+ for (Chunk c : chunkList) {
+ long start = c.getChunkStart();
+ long end = c.getChunkEnd();
+ if (firstChunk) {
+ firstOffset = start;
+ lastOffset = end;
+ firstChunk = false;
+ } else {
+ firstChunk = true;
+ alignedRecords = (int) start;
+ unAlignedRecords = (int) end;
+ }
+ }
+ }
+ }
+
+ private BAMIndexMetaData(
+ final long firstOffset, final long lastOffset, final int alignedRecords, final int unAlignedRecords) {
+ this.firstOffset = firstOffset;
+ this.lastOffset = lastOffset;
+ this.alignedRecords = alignedRecords;
+ this.unAlignedRecords = unAlignedRecords;
+ }
+
+ /**
+ * @return the count of aligned records associated with this reference
+ */
+ public int getAlignedRecordCount() {
+ return alignedRecords;
+ }
+
+ /**
+ * @return the count of unaligned records associated with this reference
+ */
+ public int getUnalignedRecordCount() {
+ return unAlignedRecords;
+ }
+
+ /**
+ * Call for each new reference sequence encountered
+ */
+ void newReference() {
+ firstOffset = -1;
+ lastOffset = 0;
+ alignedRecords = 0;
+ unAlignedRecords = 0;
+ }
+
+ /**
+ * Extract relevant metaData from the record and its filePointer
+ * Call only once per record in the file being indexed
+ *
+ * @param rec
+ */
+ void recordMetaData(final SAMRecord rec) {
+
+ final int alignmentStart = rec.getAlignmentStart();
+ if (alignmentStart == SAMRecord.NO_ALIGNMENT_START) {
+ incrementNoCoordinateRecordCount();
+ return;
+ }
+
+ if (rec.getFileSource() == null) {
+ throw new SAMException("BAM cannot be indexed without setting a fileSource for record " + rec);
+ }
+ final Chunk newChunk = ((BAMFileSpan) rec.getFileSource().getFilePointer()).getSingleChunk();
+ final long start = newChunk.getChunkStart();
+ final long end = newChunk.getChunkEnd();
+
+ if (rec.getReadUnmappedFlag()) {
+ unAlignedRecords++;
+ } else {
+ alignedRecords++;
+ }
+ if (BlockCompressedFilePointerUtil.compare(start, firstOffset) < 1 || firstOffset == -1) {
+ this.firstOffset = start;
+ }
+ if (BlockCompressedFilePointerUtil.compare(lastOffset, end) < 1) {
+ this.lastOffset = end;
+ }
+ }
+
+ // The resolution of a CRAM BAI index is more coarse than for BAM BAI. Each entry
+ // is represented by a BAIEntry that represents a slice (or, in the case of
+ // MULTI_REFERENCE slices, a subset of a slice), rather than SAMRecords.
+ void recordMetaData(final BAIEntry baiEntry) {
+ alignedRecords += baiEntry.getMappedReadsCount();
+ noCoordinateRecords += baiEntry.getUnmappedUnplacedReadsCount();
+ unAlignedRecords += baiEntry.getUnmappedReadsCount();
+
+ final long start = baiEntry.getSliceByteOffsetFromCompressionHeaderStart();
+
+ if (BlockCompressedFilePointerUtil.compare(start, firstOffset) < 1 || firstOffset == -1) {
+ this.firstOffset = start;
+ // not actually used, so set it to a dummy value (start)
+ // see https://github.com/samtools/htsjdk/issues/401
+ this.lastOffset = start;
+ }
+ }
+
+ /**
+ * Call whenever a reference with no coordinate information is encountered in the bam file
+ */
+ void incrementNoCoordinateRecordCount() {
+ noCoordinateRecords++;
+ }
+
+ /**
+ * Set local variable. Normally noCoordinateRecord count accessed from AbstractBAMFileIndex when reading
+ */
+ private void setNoCoordinateRecordCount(long count) {
+ noCoordinateRecords = count;
+ }
+
+ /**
+ * @return the count of records with no coordinate information in the bam file.
+ * Not public, since only used by BAMIndexer when writing bam index.
+ * Readers of bam index should use AbstractBAMFileIndex.getNoCoordinateRecordCount.
+ */
+ long getNoCoordinateRecordCount() {
+ return noCoordinateRecords;
+ }
+
+ /**
+ * @return the first virtual file offset used by this reference
+ */
+ long getFirstOffset() {
+ return firstOffset;
+ }
+
+ /**
+ * @return the last virtual file offset used by this reference
+ */
+ long getLastOffset() {
+ return lastOffset;
+ }
+
+ /**
+ * Return a new metadata object shifted by a given (non-virtual) offset.
+ *
+ * @param offset the offset in bytes
+ * @return a new metadata object shifted by the given offset
+ * @see BlockCompressedFilePointerUtil#shift(long, long)
+ */
+ BAMIndexMetaData shift(final long offset) {
+ final long newFirstOffset = firstOffset == -1
+ ? firstOffset
+ : BlockCompressedFilePointerUtil.shift(firstOffset, offset); // -1 is unset
+ final long newLastOffset =
+ lastOffset == 0 ? lastOffset : BlockCompressedFilePointerUtil.shift(lastOffset, offset); // 0 is unset
+ return new BAMIndexMetaData(newFirstOffset, newLastOffset, alignedRecords, unAlignedRecords);
+ }
+
+ /**
+ * Prints meta-data statistics from BAM index (.bai or .csi) file
+ * Statistics include count of aligned and unaligned reads for each reference sequence
+ * and a count of all records with no start coordinate
+ */
+ public static void printIndexStats(final File inputBamFile) {
+ try {
+ final BAMFileReader bam = new BAMFileReader(
+ inputBamFile, null, false, false, ValidationStringency.SILENT, new DefaultSAMRecordFactory());
+ if (!bam.hasIndex() || bam.getIndexType() == null) {
+ throw new SAMException("No index for bam file " + inputBamFile);
+ }
+
+ BAMIndexMetaData[] data = getIndexStats(bam);
+ if (data == null) {
+ throw new SAMException("Exception in getting index statistics");
+ }
+
+ // read through all the bins of every reference.
+ int nRefs = bam.getFileHeader().getSequenceDictionary().size();
+ for (int i = 0; i < nRefs; i++) {
+ final SAMSequenceRecord seq = bam.getFileHeader().getSequence(i);
+ if (seq == null) continue;
+ final String sequenceName = seq.getSequenceName();
+ final int sequenceLength = seq.getSequenceLength();
+ System.out.print(sequenceName + ' ' + "length=\t" + sequenceLength);
+ if (data[i] == null) {
+ System.out.println();
+ continue;
+ }
+ System.out.println("\tAligned= " + data[i].getAlignedRecordCount() + "\tUnaligned= "
+ + data[i].getUnalignedRecordCount());
+ }
+ System.out.println("NoCoordinateCount= " + data[0].getNoCoordinateRecordCount());
+ } catch (IOException e) {
+ throw new SAMException("Exception in getting index statistics", e);
+ }
+ }
+
+ /**
+ * Prints meta-data statistics from BAM index (.bai or .csi) file
+ * Statistics include count of aligned and unaligned reads for each reference sequence
+ * and a count of all records with no start coordinate
+ */
+ public static BAMIndexMetaData[] getIndexStats(final BAMFileReader bam) {
+
+ AbstractBAMFileIndex index = (AbstractBAMFileIndex) bam.getIndex();
+ // read through all the bins of every reference.
+ int nRefs = index.getNumberOfReferences();
+ BAMIndexMetaData[] result = new BAMIndexMetaData[nRefs == 0 ? 1 : nRefs];
+ for (int i = 0; i < nRefs; i++) {
+ result[i] = index.getMetaData(i);
+ }
+
+ if (result[0] == null) {
+ result[0] = new BAMIndexMetaData();
+ }
+ final Long noCoordCount = index.getNoCoordinateCount();
+ if (noCoordCount != null) // null in old index files without metadata
+ result[0].setNoCoordinateRecordCount(noCoordCount);
+
+ return result;
+ }
+}
diff --git a/src/main/java/htsjdk/samtools/BAMIndexWriter.java b/src/main/java/htsjdk/samtools/BAMIndexWriter.java
index aafcb5fbff..b6aaa2a4cb 100644
--- a/src/main/java/htsjdk/samtools/BAMIndexWriter.java
+++ b/src/main/java/htsjdk/samtools/BAMIndexWriter.java
@@ -30,7 +30,7 @@
*
* @author mborkan
*/
-interface BAMIndexWriter extends Closeable { // note - only package visibility
+interface BAMIndexWriter extends Closeable { // note - only package visibility
/**
* Write the data for one alignments to one reference sequence
@@ -51,5 +51,4 @@ interface BAMIndexWriter extends Closeable { // note - only package visibility
*/
@Override
public void close();
-
-}
\ No newline at end of file
+}
diff --git a/src/main/java/htsjdk/samtools/BAMIndexer.java b/src/main/java/htsjdk/samtools/BAMIndexer.java
index 139af8d9a0..341b268bad 100644
--- a/src/main/java/htsjdk/samtools/BAMIndexer.java
+++ b/src/main/java/htsjdk/samtools/BAMIndexer.java
@@ -24,7 +24,6 @@
package htsjdk.samtools;
import htsjdk.samtools.util.Log;
-
import java.io.File;
import java.io.OutputStream;
import java.nio.file.Path;
@@ -88,7 +87,8 @@ public BAMIndexer(final OutputStream output, final SAMFileHeader fileHeader) {
* if false, leave uninitialized values as -1, which is required when merging index files
* (see {@link BAMIndexMerger})
*/
- public BAMIndexer(final OutputStream output, final SAMFileHeader fileHeader, final boolean fillInUninitializedValues) {
+ public BAMIndexer(
+ final OutputStream output, final SAMFileHeader fileHeader, final boolean fillInUninitializedValues) {
this(fileHeader, numRefs -> new BinaryBAMIndexWriter(numRefs, output), fillInUninitializedValues);
}
@@ -98,13 +98,16 @@ public BAMIndexer(final OutputStream output, final SAMFileHeader fileHeader, fin
* @param fileHeader header for the corresponding bam file.
* @param createWrite a lambda that, given an Integer numReferences value, will create a BinaryBAMIndexWriter
* with that value and an appropriate output.
- */
- private BAMIndexer(final SAMFileHeader fileHeader, Function createWriter, final boolean fillInUninitializedValues) {
+ */
+ private BAMIndexer(
+ final SAMFileHeader fileHeader,
+ Function createWriter,
+ final boolean fillInUninitializedValues) {
if (fileHeader.getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
if (fileHeader.getSortOrder() == SAMFileHeader.SortOrder.unsorted) {
- log.warn("For indexing, the BAM file is required to be coordinate sorted. Attempting to index \"unsorted\" BAM file.");
- }
- else {
+ log.warn(
+ "For indexing, the BAM file is required to be coordinate sorted. Attempting to index \"unsorted\" BAM file.");
+ } else {
throw new SAMException("Indexing requires a coordinate-sorted input BAM.");
}
}
@@ -163,7 +166,7 @@ private void advanceToReference(final int nextReference) {
* @param output BAM Index (.bai) file (or bai.txt file when text)
* @param textOutput Whether to create text output or binary
*/
- static public void createAndWriteIndex(final File input, final File output, final boolean textOutput) {
+ public static void createAndWriteIndex(final File input, final File output, final boolean textOutput) {
// content is from an existing bai file.
@@ -231,8 +234,8 @@ public void processAlignment(final SAMRecord rec) {
// various checks
final int reference = rec.getReferenceIndex();
if (reference != currentReference) {
- throw new SAMException("Unexpected reference " + reference +
- " when constructing index for " + currentReference + " for record " + rec);
+ throw new SAMException("Unexpected reference " + reference + " when constructing index for "
+ + currentReference + " for record " + rec);
}
binningIndexBuilder.processFeature(new BinningIndexBuilder.FeatureToBeIndexed() {
@@ -247,18 +250,20 @@ public int getEnd() {
}
@Override
- public Integer getIndexingBin() { return rec.computeIndexingBin(); }
+ public Integer getIndexingBin() {
+ return rec.computeIndexingBin();
+ }
@Override
public Chunk getChunk() {
final SAMFileSource source = rec.getFileSource();
if (source == null) {
- throw new SAMException("No source (virtual file offsets); needed for indexing on BAM Record " + rec);
+ throw new SAMException(
+ "No source (virtual file offsets); needed for indexing on BAM Record " + rec);
}
return ((BAMFileSpan) source.getFilePointer()).getSingleChunk();
}
});
-
}
/**
@@ -270,14 +275,17 @@ public Chunk getChunk() {
public BAMIndexContent processReference(final int reference) {
if (reference != currentReference) {
- throw new SAMException("Unexpected reference " + reference + " when constructing index for " + currentReference);
+ throw new SAMException(
+ "Unexpected reference " + reference + " when constructing index for " + currentReference);
}
final BinningIndexContent indexContent = binningIndexBuilder.generateIndexContent();
if (indexContent == null) return null;
- return new BAMIndexContent(indexContent.getReferenceSequence(), indexContent.getBins(),
- indexStats, indexContent.getLinearIndex());
-
+ return new BAMIndexContent(
+ indexContent.getReferenceSequence(),
+ indexContent.getBins(),
+ indexStats,
+ indexContent.getLinearIndex());
}
/**
@@ -295,8 +303,10 @@ void startNewReference() {
// I'm not crazy about recycling this object, but that is the way it was originally written and
// it helps keep track of no-coordinate read count (which shouldn't be stored in this class anyway).
indexStats.newReference();
- binningIndexBuilder = new BinningIndexBuilder(currentReference,
- sequenceDictionary.getSequence(currentReference).getSequenceLength(), fillInUninitializedValues);
+ binningIndexBuilder = new BinningIndexBuilder(
+ currentReference,
+ sequenceDictionary.getSequence(currentReference).getSequenceLength(),
+ fillInUninitializedValues);
}
}
diff --git a/src/main/java/htsjdk/samtools/BAMIteratorFilter.java b/src/main/java/htsjdk/samtools/BAMIteratorFilter.java
index bc7d2c0259..3af3ddaf47 100644
--- a/src/main/java/htsjdk/samtools/BAMIteratorFilter.java
+++ b/src/main/java/htsjdk/samtools/BAMIteratorFilter.java
@@ -1,12 +1,14 @@
package htsjdk.samtools;
-
/**
* Interface implemented by filetering iterators used for BAM/CRAM readers.
*/
interface BAMIteratorFilter {
public enum IntervalComparison {
- BEFORE, AFTER, OVERLAPPING, CONTAINED
+ BEFORE,
+ AFTER,
+ OVERLAPPING,
+ CONTAINED
}
/**
@@ -14,7 +16,9 @@ public enum IntervalComparison {
* how to handle each SAMRecord.
*/
public enum FilteringIteratorState {
- MATCHES_FILTER, STOP_ITERATION, CONTINUE_ITERATION
+ MATCHES_FILTER,
+ STOP_ITERATION,
+ CONTINUE_ITERATION
}
/**
@@ -23,4 +27,3 @@ public enum FilteringIteratorState {
*/
FilteringIteratorState compareToFilter(final SAMRecord record);
}
-
diff --git a/src/main/java/htsjdk/samtools/BAMQueryMultipleIntervalsIteratorFilter.java b/src/main/java/htsjdk/samtools/BAMQueryMultipleIntervalsIteratorFilter.java
index 8dadc692eb..2f1fba9e0b 100644
--- a/src/main/java/htsjdk/samtools/BAMQueryMultipleIntervalsIteratorFilter.java
+++ b/src/main/java/htsjdk/samtools/BAMQueryMultipleIntervalsIteratorFilter.java
@@ -10,9 +10,7 @@ public class BAMQueryMultipleIntervalsIteratorFilter implements BAMIteratorFilte
final boolean contained;
int intervalIndex = 0;
-
- public BAMQueryMultipleIntervalsIteratorFilter(final QueryInterval[] intervals,
- final boolean contained) {
+ public BAMQueryMultipleIntervalsIteratorFilter(final QueryInterval[] intervals, final boolean contained) {
this.contained = contained;
this.intervals = intervals;
}
@@ -23,14 +21,20 @@ public FilteringIteratorState compareToFilter(final SAMRecord record) {
final IntervalComparison comparison = compareIntervalToRecord(intervals[intervalIndex], record);
switch (comparison) {
// Interval is before SAMRecord. Try next interval;
- case BEFORE: ++intervalIndex; break;
+ case BEFORE:
+ ++intervalIndex;
+ break;
// Interval is after SAMRecord. Keep scanning forward in SAMRecords
- case AFTER: return FilteringIteratorState.CONTINUE_ITERATION;
+ case AFTER:
+ return FilteringIteratorState.CONTINUE_ITERATION;
// Found a good record
- case CONTAINED: return FilteringIteratorState.MATCHES_FILTER;
+ case CONTAINED:
+ return FilteringIteratorState.MATCHES_FILTER;
// Either found a good record, or else keep scanning SAMRecords
- case OVERLAPPING: return
- (contained ? FilteringIteratorState.CONTINUE_ITERATION : FilteringIteratorState.MATCHES_FILTER);
+ case OVERLAPPING:
+ return (contained
+ ? FilteringIteratorState.CONTINUE_ITERATION
+ : FilteringIteratorState.MATCHES_FILTER);
}
}
// Went past the last interval
@@ -39,7 +43,7 @@ public FilteringIteratorState compareToFilter(final SAMRecord record) {
public static IntervalComparison compareIntervalToRecord(final QueryInterval interval, final SAMRecord record) {
// interval.end <= 0 implies the end of the reference sequence.
- final int intervalEnd = (interval.end <= 0? Integer.MAX_VALUE: interval.end);
+ final int intervalEnd = (interval.end <= 0 ? Integer.MAX_VALUE : interval.end);
final int alignmentEnd;
if (record.getReadUnmappedFlag() && record.getAlignmentStart() != SAMRecord.NO_ALIGNMENT_START) {
// Unmapped read with coordinate of mate.
diff --git a/src/main/java/htsjdk/samtools/BAMRecord.java b/src/main/java/htsjdk/samtools/BAMRecord.java
index cd82fdb38c..e55080a1ee 100644
--- a/src/main/java/htsjdk/samtools/BAMRecord.java
+++ b/src/main/java/htsjdk/samtools/BAMRecord.java
@@ -23,13 +23,12 @@
*/
package htsjdk.samtools;
-import htsjdk.samtools.util.StringUtil;
+import static htsjdk.samtools.SAMTag.CG;
+import htsjdk.samtools.util.StringUtil;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
-import static htsjdk.samtools.SAMTag.CG;
-
/**
* Wrapper class for binary BAM records.
* Delays unpacking all data binary until requested.
@@ -44,7 +43,7 @@ public class BAMRecord extends SAMRecord {
* Constant for converting between the number of operators in a Cigar and the length
* of the int[] array needed to represent it in the BAM format
*/
- static public final short CIGAR_SIZE_MULTIPLIER = 4;
+ public static final short CIGAR_SIZE_MULTIPLIER = 4;
/**
* Maximal number of cigar operators that can be represented normally in the cigar part of the bam record.
@@ -54,13 +53,13 @@ public class BAMRecord extends SAMRecord {
* When a BAM record is decoded, the sentinel cigar informs of the existance of the CG tag, which is decoded and removed.
* The sentinel value is then replaced with the actual cigar (in memory).
*/
- public final static int MAX_CIGAR_OPERATORS = 0xffff;
+ public static final int MAX_CIGAR_OPERATORS = 0xffff;
- public final static int MAX_CIGAR_ELEMENT_LENGTH = (1 << 28) - 1;
+ public static final int MAX_CIGAR_ELEMENT_LENGTH = (1 << 28) - 1;
/**
* Number of operators in "Sentinel" cigar xSyN
*/
- private final static int LONG_CIGAR_SENTINEL_LENGTH = 2;
+ private static final int LONG_CIGAR_SENTINEL_LENGTH = 2;
/**
* Variable-length part of BAMRecord. Lazily decoded.
@@ -93,19 +92,20 @@ public class BAMRecord extends SAMRecord {
* than NO_ALIGNMENT_REFERENCE_INDEX (-1), then the specified index values must exist in the sequence dictionary
* in the header argument.
*/
- protected BAMRecord(final SAMFileHeader header,
- final int referenceID,
- final int coordinate,
- final short readNameLength,
- final short mappingQuality,
- final int indexingBin,
- final int cigarLen,
- final int flags,
- final int readLen,
- final int mateReferenceID,
- final int mateCoordinate,
- final int insertSize,
- final byte[] restOfData) {
+ protected BAMRecord(
+ final SAMFileHeader header,
+ final int referenceID,
+ final int coordinate,
+ final short readNameLength,
+ final short mappingQuality,
+ final int indexingBin,
+ final int cigarLen,
+ final int flags,
+ final int readLen,
+ final int mateReferenceID,
+ final int mateCoordinate,
+ final int insertSize,
+ final byte[] restOfData) {
super(header);
// Set reference index and name directly, avoiding the round-trip through
// setReferenceIndex -> resolveNameFromIndex -> setReferenceName -> resolveIndexFromName
@@ -281,7 +281,9 @@ public Cigar getCigar() {
extractCigarFromCGAttribute(super.getCigar());
}
- if (null != getHeader() && getValidationStringency() != ValidationStringency.SILENT && !this.getReadUnmappedFlag()) {
+ if (null != getHeader()
+ && getValidationStringency() != ValidationStringency.SILENT
+ && !this.getReadUnmappedFlag()) {
// Don't know line number, and don't want to force read name to be decoded.
SAMUtils.processValidationErrors(validateCigar(-1L), -1, getValidationStringency());
}
@@ -296,13 +298,12 @@ public Cigar getCigar() {
*/
static boolean isSentinelCigar(final Cigar cigar, final int readLength) {
// There's an implicit assumption here there readLength == length of read in cigar, unless readLength==0
- return cigar.numCigarElements() == 2 &&
- cigar.getCigarElement(1).getOperator() == CigarOperator.N &&
- cigar.getCigarElement(0).getOperator() == CigarOperator.S &&
- (cigar.getCigarElement(0).getLength() == readLength || readLength == 0) ;
+ return cigar.numCigarElements() == 2
+ && cigar.getCigarElement(1).getOperator() == CigarOperator.N
+ && cigar.getCigarElement(0).getOperator() == CigarOperator.S
+ && (cigar.getCigarElement(0).getLength() == readLength || readLength == 0);
}
-
/**
* Long cigars (with more than 64K operators) cannot be encoded into BAM. Instead a sentinel cigar is
* placed as a placeholder, and the actual cigar is placed in the CG tag. This method
@@ -314,8 +315,8 @@ private void extractCigarFromCGAttribute(final Cigar sentinelCigar) throws Illeg
if (cigarFromCG == null) return;
// place the integer array into a buffer so we can decode it
- final ByteBuffer byteBuffer = ByteBuffer.allocate(cigarFromCG.length * CIGAR_SIZE_MULTIPLIER)
- .order(ByteOrder.LITTLE_ENDIAN);
+ final ByteBuffer byteBuffer =
+ ByteBuffer.allocate(cigarFromCG.length * CIGAR_SIZE_MULTIPLIER).order(ByteOrder.LITTLE_ENDIAN);
byteBuffer.asIntBuffer().put(cigarFromCG);
// decode cigar
@@ -325,9 +326,7 @@ private void extractCigarFromCGAttribute(final Cigar sentinelCigar) throws Illeg
if (decodedCigar.numCigarElements() <= MAX_CIGAR_OPERATORS) {
throw new IllegalStateException(String.format(
"Only Cigar with > %d operators should be placed in CG tag. Found %d operators. \n Here's the Cigar:\n%s",
- MAX_CIGAR_OPERATORS,
- decodedCigar.getCigarElements().size(),
- decodedCigar.toString()));
+ MAX_CIGAR_OPERATORS, decodedCigar.getCigarElements().size(), decodedCigar.toString()));
}
if (decodedCigar.getReferenceLength() != sentinelCigar.getReferenceLength()) {
@@ -339,16 +338,13 @@ private void extractCigarFromCGAttribute(final Cigar sentinelCigar) throws Illeg
decodedCigar.toString()));
}
- if (decodedCigar.getReadLength() != sentinelCigar.getReadLength() ) {
+ if (decodedCigar.getReadLength() != sentinelCigar.getReadLength()) {
throw new IllegalStateException(String.format(
"Sentinel cigar and %s cigar should have the same read length. Found %d and %d.\n Here's the Cigar:\n%s",
- CG.name(),
- sentinelCigar.getReadLength(),
- decodedCigar.getReadLength(),
- decodedCigar.toString()));
+ CG.name(), sentinelCigar.getReadLength(), decodedCigar.getReadLength(), decodedCigar.toString()));
}
- //used initializeCigar instead of setCigar so as to not clobber the indexingBin.
+ // used initializeCigar instead of setCigar so as to not clobber the indexingBin.
initializeCigar(decodedCigar);
// remove CG attribute.
@@ -411,7 +407,8 @@ private void decodeAttributes() {
mAttributesDecoded = true;
final int tagsOffset = readNameSize() + cigarSize() + basesSize() + qualsSize();
final int tagsSize = mRestOfBinaryData.length - tagsOffset;
- final SAMBinaryTagAndValue attributes = BinaryTagCodec.readTags(mRestOfBinaryData, tagsOffset, tagsSize, getValidationStringency());
+ final SAMBinaryTagAndValue attributes =
+ BinaryTagCodec.readTags(mRestOfBinaryData, tagsOffset, tagsSize, getValidationStringency());
setAttributes(attributes);
// if there's a CG tag, we should getCigar() so that the CG tag has a chance of turning into the CIGAR
diff --git a/src/main/java/htsjdk/samtools/BAMRecordCodec.java b/src/main/java/htsjdk/samtools/BAMRecordCodec.java
index 6717364499..31c62fbe34 100644
--- a/src/main/java/htsjdk/samtools/BAMRecordCodec.java
+++ b/src/main/java/htsjdk/samtools/BAMRecordCodec.java
@@ -23,22 +23,21 @@
*/
package htsjdk.samtools;
+import static htsjdk.samtools.SAMTag.CG;
+
import htsjdk.samtools.util.BinaryCodec;
import htsjdk.samtools.util.Log;
import htsjdk.samtools.util.RuntimeEOFException;
import htsjdk.samtools.util.SortingCollection;
-
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
-import static htsjdk.samtools.SAMTag.CG;
-
/**
* Class for translating between in-memory and disk representation of BAMRecord.
*/
public class BAMRecordCodec implements SortingCollection.Codec {
- private final static Log LOG = Log.getInstance(BAMRecordCodec.class);
+ private static final Log LOG = Log.getInstance(BAMRecordCodec.class);
private final SAMFileHeader header;
private final BinaryCodec binaryCodec = new BinaryCodec();
@@ -116,14 +115,17 @@ public void encode(final SAMRecord alignment) {
final int[] cigarEncoding = BinaryCigarCodec.encode(alignment.getCigar());
alignment.setAttribute(CG.name(), cigarEncoding);
cigarToWrite = makeSentinelCigar(alignment.getCigar());
- }
- else {
+ } else {
cigarToWrite = alignment.getCigar();
}
- int blockSize = BAMFileConstants.FIXED_BLOCK_SIZE + alignment.getReadNameLength() + 1 + // null terminated
- cigarToWrite.numCigarElements() * BAMRecord.CIGAR_SIZE_MULTIPLIER +
- (readLength + 1) / 2 + // 2 bases per byte, round up
+ int blockSize = BAMFileConstants.FIXED_BLOCK_SIZE
+ + alignment.getReadNameLength()
+ + 1
+ + // null terminated
+ cigarToWrite.numCigarElements() * BAMRecord.CIGAR_SIZE_MULTIPLIER
+ + (readLength + 1) / 2
+ + // 2 bases per byte, round up
readLength;
final int attributesSize = alignment.getAttributesBinarySize();
@@ -167,11 +169,12 @@ public void encode(final SAMRecord alignment) {
// when the record was read from a BAM file.
this.binaryCodec.writeBytes(variableLengthBinaryBlock);
} else {
- if (alignment.getReadLength() != alignment.getBaseQualities().length &&
- alignment.getBaseQualities().length != 0) {
- throw new RuntimeException("Mismatch between read length and quals length writing read " +
- alignment.getReadName() + "; read length: " + alignment.getReadLength() +
- "; quals length: " + alignment.getBaseQualities().length);
+ if (alignment.getReadLength() != alignment.getBaseQualities().length
+ && alignment.getBaseQualities().length != 0) {
+ throw new RuntimeException(
+ "Mismatch between read length and quals length writing read " + alignment.getReadName()
+ + "; read length: " + alignment.getReadLength() + "; quals length: "
+ + alignment.getBaseQualities().length);
}
this.binaryCodec.writeString(alignment.getReadName(), false, true);
final int[] binaryCigar = BinaryCigarCodec.encode(cigarToWrite);
@@ -213,17 +216,15 @@ public void encode(final SAMRecord alignment) {
public static Cigar makeSentinelCigar(final Cigar cigar) {
// in BAM there are only 28 bits for a cigar operator, so this a protection against overflow.
if (cigar.getReadLength() > BAMRecord.MAX_CIGAR_ELEMENT_LENGTH) {
- throw new IllegalArgumentException(
- String.format(
- "Cannot encode (to BAM) a record with more than %d cigar operations and a read-length greater than %d.",
- BAMRecord.MAX_CIGAR_OPERATORS, BAMRecord.MAX_CIGAR_ELEMENT_LENGTH));
+ throw new IllegalArgumentException(String.format(
+ "Cannot encode (to BAM) a record with more than %d cigar operations and a read-length greater than %d.",
+ BAMRecord.MAX_CIGAR_OPERATORS, BAMRecord.MAX_CIGAR_ELEMENT_LENGTH));
}
if (cigar.getReferenceLength() > BAMRecord.MAX_CIGAR_ELEMENT_LENGTH) {
- throw new IllegalArgumentException(
- String.format(
- "Cannot encode (to BAM) a record that has than %d cigar operations and spans more than %d bases on the reference.",
- BAMRecord.MAX_CIGAR_OPERATORS, BAMRecord.MAX_CIGAR_ELEMENT_LENGTH));
+ throw new IllegalArgumentException(String.format(
+ "Cannot encode (to BAM) a record that has than %d cigar operations and spans more than %d bases on the reference.",
+ BAMRecord.MAX_CIGAR_OPERATORS, BAMRecord.MAX_CIGAR_ELEMENT_LENGTH));
}
return new Cigar(Arrays.asList(
@@ -237,11 +238,13 @@ public static Cigar makeSentinelCigar(final Cigar cigar) {
* @return true if the sequence is too large, false otherwise
*/
private boolean warnIfReferenceIsTooLargeForBinField(final SAMRecord rec) {
- final SAMSequenceRecord sequence = rec.getHeader() != null ? rec.getHeader().getSequence(rec.getReferenceName()) : null;
+ final SAMSequenceRecord sequence =
+ rec.getHeader() != null ? rec.getHeader().getSequence(rec.getReferenceName()) : null;
final boolean tooLarge = sequence != null && SAMUtils.isReferenceSequenceIncompatibleWithBAI(sequence);
if (!isReferenceSizeWarningShowed && tooLarge && rec.getValidationStringency() != ValidationStringency.SILENT) {
LOG.warn("Reference length is too large for BAM bin field.");
- LOG.warn("Reads on references longer than " + GenomicIndexUtil.BIN_GENOMIC_SPAN + "bp will have bin set to 0.");
+ LOG.warn("Reads on references longer than " + GenomicIndexUtil.BIN_GENOMIC_SPAN
+ + "bp will have bin set to 0.");
isReferenceSizeWarningShowed = true;
}
@@ -281,8 +284,19 @@ public SAMRecord decode() {
final byte[] restOfRecord = new byte[recordLength - BAMFileConstants.FIXED_BLOCK_SIZE];
this.binaryCodec.readBytes(restOfRecord);
final BAMRecord ret = this.samRecordFactory.createBAMRecord(
- header, referenceID, coordinate, readNameLength, mappingQuality,
- bin, cigarLen, flags, readLen, mateReferenceID, mateCoordinate, insertSize, restOfRecord);
+ header,
+ referenceID,
+ coordinate,
+ readNameLength,
+ mappingQuality,
+ bin,
+ cigarLen,
+ flags,
+ readLen,
+ mateReferenceID,
+ mateCoordinate,
+ insertSize,
+ restOfRecord);
return ret;
}
diff --git a/src/main/java/htsjdk/samtools/BAMSBIIndexer.java b/src/main/java/htsjdk/samtools/BAMSBIIndexer.java
index 6400f81ff7..ec0eb36813 100644
--- a/src/main/java/htsjdk/samtools/BAMSBIIndexer.java
+++ b/src/main/java/htsjdk/samtools/BAMSBIIndexer.java
@@ -30,7 +30,6 @@
import htsjdk.samtools.util.FileExtensions;
import htsjdk.samtools.util.IOUtil;
import htsjdk.samtools.util.RuntimeEOFException;
-
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
@@ -52,7 +51,8 @@ public final class BAMSBIIndexer {
*/
public static void createIndex(final Path bamFile, final long granularity) throws IOException {
final Path splittingBaiFile = IOUtil.addExtension(bamFile, FileExtensions.SBI);
- try (SeekableStream in = new SeekablePathStream(bamFile); OutputStream out = Files.newOutputStream(splittingBaiFile)) {
+ try (SeekableStream in = new SeekablePathStream(bamFile);
+ OutputStream out = Files.newOutputStream(splittingBaiFile)) {
createIndex(in, out, granularity);
}
}
@@ -65,7 +65,8 @@ public static void createIndex(final Path bamFile, final long granularity) throw
* @param granularity write the offset of every n-th alignment to the index
* @throws IOException as per java IO contract
*/
- public static void createIndex(final SeekableStream in, final OutputStream out, final long granularity) throws IOException {
+ public static void createIndex(final SeekableStream in, final OutputStream out, final long granularity)
+ throws IOException {
long recordStart = SAMUtils.findVirtualOffsetOfFirstRecordInBam(in);
try (BlockCompressedInputStream blockIn = new BlockCompressedInputStream(in)) {
blockIn.seek(recordStart);
diff --git a/src/main/java/htsjdk/samtools/BAMStartingAtIteratorFilter.java b/src/main/java/htsjdk/samtools/BAMStartingAtIteratorFilter.java
index 8bd8eb51c8..533dabd447 100644
--- a/src/main/java/htsjdk/samtools/BAMStartingAtIteratorFilter.java
+++ b/src/main/java/htsjdk/samtools/BAMStartingAtIteratorFilter.java
@@ -57,7 +57,7 @@ public FilteringIteratorState compareToFilter(final SAMRecord record) {
if (alignmentStart > mRegionStart) {
// If scanned beyond target region, end iteration
return FilteringIteratorState.STOP_ITERATION;
- } else if (alignmentStart == mRegionStart) {
+ } else if (alignmentStart == mRegionStart) {
return FilteringIteratorState.MATCHES_FILTER;
} else {
return FilteringIteratorState.CONTINUE_ITERATION;
diff --git a/src/main/java/htsjdk/samtools/BAMStreamWriter.java b/src/main/java/htsjdk/samtools/BAMStreamWriter.java
index c720655fb0..968c91a081 100644
--- a/src/main/java/htsjdk/samtools/BAMStreamWriter.java
+++ b/src/main/java/htsjdk/samtools/BAMStreamWriter.java
@@ -26,11 +26,10 @@
import htsjdk.samtools.util.BinaryCodec;
import htsjdk.samtools.util.BlockCompressedOutputStream;
import htsjdk.samtools.util.RuntimeIOException;
-import org.apache.commons.compress.utils.CountingOutputStream;
-
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
+import org.apache.commons.compress.utils.CountingOutputStream;
/**
* Class for writing SAMRecords in BAM format to an output stream.
@@ -53,7 +52,12 @@ public class BAMStreamWriter {
* @param sbiGranularity the granularity of the SBI index (reads per entry)
* @param header the SAM header
*/
- public BAMStreamWriter(OutputStream outputStream, OutputStream indexStream, OutputStream sbiStream, long sbiGranularity, SAMFileHeader header) {
+ public BAMStreamWriter(
+ OutputStream outputStream,
+ OutputStream indexStream,
+ OutputStream sbiStream,
+ long sbiGranularity,
+ SAMFileHeader header) {
countingOut = new CountingOutputStream(outputStream);
compressedOut = new BlockCompressedOutputStream(countingOut, (Path) null);
bamRecordCodec = new BAMRecordCodec(header);
@@ -123,8 +127,7 @@ public void finish(final boolean writeTerminatorBlock) {
// If we didn't do this then we would have an invalid virtual file pointer if a BGZF file
// were concatenated following this one.
if (bamIndexer != null && previousSamRecord != null) {
- previousSamRecordChunk =
- new Chunk(previousSamRecordChunk.getChunkStart(), finalVirtualOffset);
+ previousSamRecordChunk = new Chunk(previousSamRecordChunk.getChunkStart(), finalVirtualOffset);
previousSamRecord.setFileSource(new SAMFileSource(null, new BAMFileSpan(previousSamRecordChunk)));
bamIndexer.processAlignment(previousSamRecord);
}
diff --git a/src/main/java/htsjdk/samtools/BamConverter.java b/src/main/java/htsjdk/samtools/BamConverter.java
index 13d2500565..f5b14d4cac 100644
--- a/src/main/java/htsjdk/samtools/BamConverter.java
+++ b/src/main/java/htsjdk/samtools/BamConverter.java
@@ -15,15 +15,15 @@
*/
public class BamConverter {
- private static final String USAGE = String.join("\n",
+ private static final String USAGE = String.join(
+ "\n",
"Usage: BamConverter [output]",
"",
"Read and optionally convert a BAM file.",
"",
"Arguments:",
" input Input BAM file",
- " output Optional output BAM file (omit to read-only)"
- );
+ " output Optional output BAM file (omit to read-only)");
/**
* Entry point. Parses command-line arguments and performs the read/conversion.
@@ -42,9 +42,8 @@ public static void main(final String[] args) {
final boolean eager = hasFlag(args, "--eager");
// Collect positional args (non-flag arguments)
- final String[] positional = java.util.Arrays.stream(args)
- .filter(a -> !a.startsWith("--"))
- .toArray(String[]::new);
+ final String[] positional =
+ java.util.Arrays.stream(args).filter(a -> !a.startsWith("--")).toArray(String[]::new);
if (positional.length < 1) {
System.err.println(USAGE);
System.exit(1);
@@ -58,8 +57,8 @@ public static void main(final String[] args) {
System.err.printf("Reading %s (no output%s)%n", inputPath, eager ? ", eager decode" : "");
}
- final SamReaderFactory readerFactory = SamReaderFactory.makeDefault()
- .validationStringency(ValidationStringency.SILENT);
+ final SamReaderFactory readerFactory =
+ SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT);
long count = 0;
final long startTime = System.currentTimeMillis();
@@ -69,7 +68,8 @@ public static void main(final String[] args) {
if (outputPath != null) {
final SAMFileWriterFactory writerFactory = new SAMFileWriterFactory();
- try (final SAMFileWriter writer = writerFactory.makeBAMWriter(header, true, new File(outputPath).toPath())) {
+ try (final SAMFileWriter writer =
+ writerFactory.makeBAMWriter(header, true, new File(outputPath).toPath())) {
for (final SAMRecord record : reader) {
if (eager) record.eagerDecode();
writer.addAlignment(record);
@@ -97,12 +97,15 @@ public static void main(final String[] args) {
if (outputPath != null) {
final long outputSize = new File(outputPath).length();
- System.err.printf("Done. %,d records in %.1fs. Input: %,d bytes, Output: %,d bytes (%.1f%%)%n",
- count, elapsed / 1000.0, inputSize, outputSize,
+ System.err.printf(
+ "Done. %,d records in %.1fs. Input: %,d bytes, Output: %,d bytes (%.1f%%)%n",
+ count,
+ elapsed / 1000.0,
+ inputSize,
+ outputSize,
inputSize > 0 ? (100.0 * outputSize / inputSize) : 0);
} else {
- System.err.printf("Done. %,d records in %.1fs. Input: %,d bytes%n",
- count, elapsed / 1000.0, inputSize);
+ System.err.printf("Done. %,d records in %.1fs. Input: %,d bytes%n", count, elapsed / 1000.0, inputSize);
}
}
diff --git a/src/main/java/htsjdk/samtools/BamFileIoUtils.java b/src/main/java/htsjdk/samtools/BamFileIoUtils.java
index 709c8ed76d..761a22a8f7 100644
--- a/src/main/java/htsjdk/samtools/BamFileIoUtils.java
+++ b/src/main/java/htsjdk/samtools/BamFileIoUtils.java
@@ -13,14 +13,12 @@
import htsjdk.samtools.util.Md5CalculatingOutputStream;
import htsjdk.samtools.util.RuntimeIOException;
import htsjdk.utils.ValidationUtils;
-
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.util.List;
public class BamFileIoUtils {
@@ -40,11 +38,15 @@ public static void reheaderBamFile(final SAMFileHeader samFileHeader, final Path
reheaderBamFile(samFileHeader, inputFile, outputFile, true, true);
}
-
/**
* Support File input types for backward compatibility. Use the same method with Path inputs below.
*/
- public static void reheaderBamFile(final SAMFileHeader samFileHeader, final File inputFile, final File outputFile, final boolean createMd5, final boolean createIndex) {
+ public static void reheaderBamFile(
+ final SAMFileHeader samFileHeader,
+ final File inputFile,
+ final File outputFile,
+ final boolean createMd5,
+ final boolean createIndex) {
reheaderBamFile(samFileHeader, IOUtil.toPath(inputFile), IOUtil.toPath(outputFile), createMd5, createIndex);
}
@@ -57,7 +59,12 @@ public static void reheaderBamFile(final SAMFileHeader samFileHeader, final File
* @param createMd5 Whether or not to create an MD5 file for the new BAM
* @param createIndex Whether or not to create an index file for the new BAM
*/
- public static void reheaderBamFile(final SAMFileHeader samFileHeader, final Path inputFile, final Path outputFile, final boolean createMd5, final boolean createIndex) {
+ public static void reheaderBamFile(
+ final SAMFileHeader samFileHeader,
+ final Path inputFile,
+ final Path outputFile,
+ final boolean createMd5,
+ final boolean createIndex) {
ValidationUtils.nonNull(inputFile);
ValidationUtils.nonNull(outputFile);
IOUtil.assertFileIsReadable(inputFile);
@@ -79,7 +86,11 @@ public static void reheaderBamFile(final SAMFileHeader samFileHeader, final Path
}
}
- public static void blockCopyBamFile(final File inputFile, final OutputStream outputStream, final boolean skipHeader, final boolean skipTerminator) {
+ public static void blockCopyBamFile(
+ final File inputFile,
+ final OutputStream outputStream,
+ final boolean skipHeader,
+ final boolean skipTerminator) {
blockCopyBamFile(IOUtil.toPath(inputFile), outputStream, skipHeader, skipTerminator);
}
@@ -91,10 +102,16 @@ public static void blockCopyBamFile(final File inputFile, final OutputStream out
* @param skipHeader If true, the header of the input file will not be copied to the output stream
* @param skipTerminator If true, the terminator block of the input file will not be written to the output stream
*/
- public static void blockCopyBamFile(final Path inputFile, final OutputStream outputStream, final boolean skipHeader, final boolean skipTerminator) {
- try (final SeekablePathStream in = new SeekablePathStream(inputFile)){
- // a) It's good to check that the end of the file is valid and b) we need to know if there's a terminator block and not copy it if skipTerminator is true
- final BlockCompressedInputStream.FileTermination term = BlockCompressedInputStream.checkTermination(inputFile);
+ public static void blockCopyBamFile(
+ final Path inputFile,
+ final OutputStream outputStream,
+ final boolean skipHeader,
+ final boolean skipTerminator) {
+ try (final SeekablePathStream in = new SeekablePathStream(inputFile)) {
+ // a) It's good to check that the end of the file is valid and b) we need to know if there's a terminator
+ // block and not copy it if skipTerminator is true
+ final BlockCompressedInputStream.FileTermination term =
+ BlockCompressedInputStream.checkTermination(inputFile);
if (term == BlockCompressedInputStream.FileTermination.DEFECTIVE)
throw new SAMException(inputFile.toUri() + " does not have a valid GZIP block at the end of the file.");
@@ -109,7 +126,8 @@ public static void blockCopyBamFile(final Path inputFile, final OutputStream out
// If we found the end of the header then write the remainder of this block out as a
// new gzip block and then break out of the while loop (tsato: update this comment)
if (remainingInBlock >= 0) {
- final BlockCompressedOutputStream blockOut = new BlockCompressedOutputStream(outputStream, (Path) null);
+ final BlockCompressedOutputStream blockOut =
+ new BlockCompressedOutputStream(outputStream, (Path) null);
IOUtil.transferByStream(blockIn, blockOut, remainingInBlock);
blockOut.flush();
// Don't close blockOut because closing underlying stream would break everything
@@ -119,7 +137,7 @@ public static void blockCopyBamFile(final Path inputFile, final OutputStream out
blockIn.close(); // tsato: why doesn't IntelliJ say this is unnecessary?
in.seek(pos);
- } catch (IOException e){
+ } catch (IOException e) {
throw new HtsjdkException("Encountered an error.", e);
}
}
@@ -127,8 +145,10 @@ public static void blockCopyBamFile(final Path inputFile, final OutputStream out
// Copy remainder of input stream into output stream
final long currentPos = in.position();
final long length = Files.size(inputFile);
- final long skipLast = ((term == BlockCompressedInputStream.FileTermination.HAS_TERMINATOR_BLOCK) && skipTerminator) ?
- BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK.length : 0;
+ final long skipLast =
+ ((term == BlockCompressedInputStream.FileTermination.HAS_TERMINATOR_BLOCK) && skipTerminator)
+ ? BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK.length
+ : 0;
final long bytesToWrite = length - skipLast - currentPos;
IOUtil.transferByStream(in, outputStream, bytesToWrite);
@@ -143,7 +163,8 @@ public static void blockCopyBamFile(final Path inputFile, final OutputStream out
* (often the first block) and re-compress any data remaining in that block into a new block in the output file. Subsequent
* blocks (excluding a terminator block if present) are copied directly from input to output.
*/
- public static void gatherWithBlockCopying(final List bams, final File output, final boolean createIndex, final boolean createMd5) {
+ public static void gatherWithBlockCopying(
+ final List bams, final File output, final boolean createIndex, final boolean createMd5) {
try {
OutputStream out = new FileOutputStream(output);
if (createMd5) out = new Md5CalculatingOutputStream(out, new File(output.getAbsolutePath() + ".md5"));
@@ -165,12 +186,15 @@ public static void gatherWithBlockCopying(final List bams, final File outp
out.write(BlockCompressedStreamConstants.EMPTY_GZIP_BLOCK);
out.close();
- // It is possible that the modified time on the index file is ever so slightly older than the original BAM file
+ // It is possible that the modified time on the index file is ever so slightly older than the original BAM
+ // file
// and this makes ValidateSamFile unhappy.
if (createIndex && (output.lastModified() > indexFile.lastModified())) {
final boolean success = indexFile.setLastModified(System.currentTimeMillis());
if (!success) {
- System.err.print(String.format("Index file is older than BAM file for %s and unable to resolve this", output.getAbsolutePath()));
+ System.err.print(String.format(
+ "Index file is older than BAM file for %s and unable to resolve this",
+ output.getAbsolutePath()));
}
}
} catch (final IOException ioe) {
@@ -178,33 +202,39 @@ public static void gatherWithBlockCopying(final List bams, final File outp
}
}
- private static OutputStream buildOutputStream(final File outputFile, final boolean createMd5, final boolean createIndex) throws IOException {
+ private static OutputStream buildOutputStream(
+ final File outputFile, final boolean createMd5, final boolean createIndex) throws IOException {
return buildOutputStream(IOUtil.toPath(outputFile), createMd5, createIndex);
}
- private static OutputStream buildOutputStream(final Path outputFile, final boolean createMd5, final boolean createIndex) throws IOException {
+ private static OutputStream buildOutputStream(
+ final Path outputFile, final boolean createMd5, final boolean createIndex) throws IOException {
OutputStream outputStream = Files.newOutputStream(outputFile);
if (createMd5) {
- outputStream = new Md5CalculatingOutputStream(outputStream, IOUtil.addExtension(outputFile, FileExtensions.MD5));
+ outputStream =
+ new Md5CalculatingOutputStream(outputStream, IOUtil.addExtension(outputFile, FileExtensions.MD5));
}
if (createIndex) {
- outputStream = new StreamInflatingIndexingOutputStream(outputStream, outputFile.resolveSibling(outputFile.getFileName() + FileExtensions.BAI_INDEX));
+ outputStream = new StreamInflatingIndexingOutputStream(
+ outputStream, outputFile.resolveSibling(outputFile.getFileName() + FileExtensions.BAI_INDEX));
}
return outputStream;
}
-
@Deprecated
- private static void assertSortOrdersAreEqual(final SAMFileHeader newHeader, final File inputFile) throws IOException {
+ private static void assertSortOrdersAreEqual(final SAMFileHeader newHeader, final File inputFile)
+ throws IOException {
assertSortOrdersAreEqual(newHeader, IOUtil.toPath(inputFile));
}
- private static void assertSortOrdersAreEqual(final SAMFileHeader newHeader, final Path inputFile) throws IOException {
+ private static void assertSortOrdersAreEqual(final SAMFileHeader newHeader, final Path inputFile)
+ throws IOException {
final SamReader reader = SamReaderFactory.makeDefault().open(inputFile);
final SAMFileHeader origHeader = reader.getFileHeader();
final SAMFileHeader.SortOrder newSortOrder = newHeader.getSortOrder();
if (newSortOrder != SAMFileHeader.SortOrder.unsorted && newSortOrder != origHeader.getSortOrder()) {
- throw new SAMException("Sort order of new header does not match the original file, needs to be " + origHeader.getSortOrder());
+ throw new SAMException("Sort order of new header does not match the original file, needs to be "
+ + origHeader.getSortOrder());
}
reader.close();
}
diff --git a/src/main/java/htsjdk/samtools/BamIndexValidator.java b/src/main/java/htsjdk/samtools/BamIndexValidator.java
index f3b5cbe5ae..0295b8c3a2 100644
--- a/src/main/java/htsjdk/samtools/BamIndexValidator.java
+++ b/src/main/java/htsjdk/samtools/BamIndexValidator.java
@@ -1,204 +1,232 @@
-/*
- * The MIT License
- *
- * Copyright (c) 2010 The Broad Institute
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-package htsjdk.samtools;
-
-import htsjdk.samtools.util.CloseableIterator;
-
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Class to validate (at two different levels of thoroughness) the index for a BAM file.
- *
- * This class is [not] thread safe [because it is immutable].
- */
-public class BamIndexValidator {
-
- public enum IndexValidationStringency {
- EXHAUSTIVE, LESS_EXHAUSTIVE, NONE
- }
-
- public static int exhaustivelyTestIndex(final SamReader reader) { // throws Exception {
- // look at all chunk offsets in a linear index to make sure they are valid
-
- if (reader.indexing().hasBrowseableIndex()) {
- if (SamIndexes.BAI.fileNameSuffix.endsWith(reader.type().indexExtension())) {
-
- // content is from an existing bai file
- final CachingBAMFileIndex existingIndex = (CachingBAMFileIndex) reader.indexing().getBrowseableIndex(); // new CachingBAMFileIndex(inputBai, null);
- final int numRefs = existingIndex.getNumberOfReferences();
-
- int chunkCount = 0;
- int indexCount = 0;
- for (int i = 0; i < numRefs; i++) {
- final BAMIndexContent content = existingIndex.getQueryResults(i);
- for (final Chunk c : content.getAllChunks()) {
- final CloseableIterator iter = ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader).iterator(new BAMFileSpan(c));
- chunkCount++;
- SAMRecord sam = null;
- try {
- sam = iter.next();
- iter.close();
- } catch (final Exception e) {
- throw new SAMException("Exception in BamIndexValidator. Last good record " + sam + " in chunk " + c + " chunkCount=" + chunkCount, e);
- }
- }
- // also seek to every position in the linear index
- // final BAMRecordCodec bamRecordCodec = new BAMRecordCodec(reader.getFileHeader());
- // bamRecordCodec.setInputStream(reader.getInputStream());
-
- final LinearIndex linearIndex = content.getLinearIndex();
- for (final long l : linearIndex.getIndexEntries()) {
- try {
- if (l != 0) {
- final CloseableIterator iter = ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader).iterator(new BAMFileSpan(new Chunk(l, l + 1)));
- final SAMRecord sam = iter.next(); // read the first record identified by the linear index
- indexCount++;
- iter.close();
- }
- } catch (final Exception e) {
- throw new SAMException("Exception in BamIndexValidator. Linear index access failure " + l + " indexCount=" + indexCount, e);
- }
-
- }
- }
- return chunkCount;
- // System.out.println("Found " chunkCount + " chunks in test " + inputBai +
- // " linearIndex positions = " + indexCount);
- } else if (SamIndexes.CSI.fileNameSuffix.endsWith(reader.type().indexExtension())) {
-
- final CSIIndex existingIndex = (CSIIndex) reader.indexing().getBrowseableIndex(); // new CachingBAMFileIndex(inputBai, null);
- final int numRefs = existingIndex.getNumberOfReferences();
-
- int chunkCount = 0;
- for (int i = 0; i < numRefs; i++) {
- final BAMIndexContent content = existingIndex.getQueryResults(i);
- for (final Chunk c : content.getAllChunks()) {
- final CloseableIterator iter = ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader).iterator(new BAMFileSpan(c));
- chunkCount++;
- SAMRecord sam = null;
- try {
- sam = iter.next();
- iter.close();
- } catch (final Exception e) {
- throw new SAMException("Exception in BamIndexValidator. Last good record " + sam + " in chunk " + c + " chunkCount=" + chunkCount, e);
- }
- }
- }
- return chunkCount;
- }
- }
- // else not a bam file with a browseable index
- // System.err.println("No browseableIndex for reader");
- return 0;
- }
-
- /**
- * A less time-consuming index validation that only looks at the first and last references in the index
- * and the first and last chunks in each of those
- *
- * @param reader
- * @return # of chunks examined, or 0 if there is no browseable index for the reader
- */
- public static int lessExhaustivelyTestIndex(final SamReader reader) {
- // look at all chunk offsets in a linear index to make sure they are valid
- if (reader.indexing().hasBrowseableIndex()) {
- if (SamIndexes.BAI.fileNameSuffix.endsWith(reader.type().indexExtension())) {
-
- // content is from an existing bai file
- final CachingBAMFileIndex existingIndex = (CachingBAMFileIndex) reader.indexing().getBrowseableIndex();
- final int numRefs = existingIndex.getNumberOfReferences();
-
- int chunkCount = 0;
- int indexCount = 0;
- for (int i = 0; i < numRefs; i++) {
-
- final BAMIndexContent content = existingIndex.getQueryResults(i);
-
- final List chunks = content.getAllChunks();
- final int numChunks = chunks.size();
- // We are looking only at the first and last chunks
- for (final int chunkNo : Arrays.asList(0, numChunks - 1)) {
- chunkCount++;
-
- final Chunk c = chunks.get(chunkNo);
- final CloseableIterator iter = ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader).iterator(new BAMFileSpan(c));
- try {
- final SAMRecord sam = iter.next();
- iter.close();
- } catch (final Exception e) {
- throw new SAMException("Exception querying chunk " + chunkNo + " from reference index " + i, e);
- }
- }
-
- // also seek to first and last position in the linear index
- final long linearIndexEntries[] = content.getLinearIndex().getIndexEntries();
- for (final int binNo : Arrays.asList(0, linearIndexEntries.length - 1)) {
- indexCount++;
- final long l = linearIndexEntries[binNo];
- try {
- if (l != 0) {
- final CloseableIterator iter = ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader).iterator(new BAMFileSpan(new Chunk(l, l + 1)));
- final SAMRecord sam = iter.next(); // read the first record identified by the linear index
- iter.close();
- }
- } catch (final Exception e) {
- throw new SAMException("Exception in BamIndexValidator. Linear index access failure " + l + " indexCount=" + indexCount, e);
- }
- }
- }
- return chunkCount;
- } else if (SamIndexes.CSI.fileNameSuffix.endsWith(reader.type().indexExtension())) {
-
- final CSIIndex existingIndex = (CSIIndex) reader.indexing().getBrowseableIndex(); // new CachingBAMFileIndex(inputBai, null);
- final int numRefs = existingIndex.getNumberOfReferences();
-
- int chunkCount = 0;
- for (int i = 0; i < numRefs; i++) {
-
- final BAMIndexContent content = existingIndex.getQueryResults(i);
-
- final List chunks = content.getAllChunks();
- final int numChunks = chunks.size();
- // We are looking only at the first and last chunks
- for (final int chunkNo : Arrays.asList(0, numChunks - 1)) {
- chunkCount++;
-
- final Chunk c = chunks.get(chunkNo);
- final CloseableIterator iter = ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader).iterator(new BAMFileSpan(c));
- try {
- final SAMRecord sam = iter.next();
- iter.close();
- } catch (final Exception e) {
- throw new SAMException("Exception querying chunk " + chunkNo + " from reference index " + i, e);
- }
- }
- }
- return chunkCount;
- }
- }
- // else it's not a bam file with a browseable index
- return 0;
- }
-}
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2010 The Broad Institute
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package htsjdk.samtools;
+
+import htsjdk.samtools.util.CloseableIterator;
+import java.util.Arrays;
+import java.util.List;
+
+/**
+ * Class to validate (at two different levels of thoroughness) the index for a BAM file.
+ *
+ * This class is [not] thread safe [because it is immutable].
+ */
+public class BamIndexValidator {
+
+ public enum IndexValidationStringency {
+ EXHAUSTIVE,
+ LESS_EXHAUSTIVE,
+ NONE
+ }
+
+ public static int exhaustivelyTestIndex(final SamReader reader) { // throws Exception {
+ // look at all chunk offsets in a linear index to make sure they are valid
+
+ if (reader.indexing().hasBrowseableIndex()) {
+ if (SamIndexes.BAI.fileNameSuffix.endsWith(reader.type().indexExtension())) {
+
+ // content is from an existing bai file
+ final CachingBAMFileIndex existingIndex = (CachingBAMFileIndex)
+ reader.indexing().getBrowseableIndex(); // new CachingBAMFileIndex(inputBai, null);
+ final int numRefs = existingIndex.getNumberOfReferences();
+
+ int chunkCount = 0;
+ int indexCount = 0;
+ for (int i = 0; i < numRefs; i++) {
+ final BAMIndexContent content = existingIndex.getQueryResults(i);
+ for (final Chunk c : content.getAllChunks()) {
+ final CloseableIterator iter =
+ ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader).iterator(new BAMFileSpan(c));
+ chunkCount++;
+ SAMRecord sam = null;
+ try {
+ sam = iter.next();
+ iter.close();
+ } catch (final Exception e) {
+ throw new SAMException(
+ "Exception in BamIndexValidator. Last good record " + sam + " in chunk " + c
+ + " chunkCount=" + chunkCount,
+ e);
+ }
+ }
+ // also seek to every position in the linear index
+ // final BAMRecordCodec bamRecordCodec = new BAMRecordCodec(reader.getFileHeader());
+ // bamRecordCodec.setInputStream(reader.getInputStream());
+
+ final LinearIndex linearIndex = content.getLinearIndex();
+ for (final long l : linearIndex.getIndexEntries()) {
+ try {
+ if (l != 0) {
+ final CloseableIterator iter =
+ ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader)
+ .iterator(new BAMFileSpan(new Chunk(l, l + 1)));
+ final SAMRecord sam =
+ iter.next(); // read the first record identified by the linear index
+ indexCount++;
+ iter.close();
+ }
+ } catch (final Exception e) {
+ throw new SAMException(
+ "Exception in BamIndexValidator. Linear index access failure " + l + " indexCount="
+ + indexCount,
+ e);
+ }
+ }
+ }
+ return chunkCount;
+ // System.out.println("Found " chunkCount + " chunks in test " + inputBai +
+ // " linearIndex positions = " + indexCount);
+ } else if (SamIndexes.CSI.fileNameSuffix.endsWith(reader.type().indexExtension())) {
+
+ final CSIIndex existingIndex =
+ (CSIIndex) reader.indexing().getBrowseableIndex(); // new CachingBAMFileIndex(inputBai, null);
+ final int numRefs = existingIndex.getNumberOfReferences();
+
+ int chunkCount = 0;
+ for (int i = 0; i < numRefs; i++) {
+ final BAMIndexContent content = existingIndex.getQueryResults(i);
+ for (final Chunk c : content.getAllChunks()) {
+ final CloseableIterator iter =
+ ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader).iterator(new BAMFileSpan(c));
+ chunkCount++;
+ SAMRecord sam = null;
+ try {
+ sam = iter.next();
+ iter.close();
+ } catch (final Exception e) {
+ throw new SAMException(
+ "Exception in BamIndexValidator. Last good record " + sam + " in chunk " + c
+ + " chunkCount=" + chunkCount,
+ e);
+ }
+ }
+ }
+ return chunkCount;
+ }
+ }
+ // else not a bam file with a browseable index
+ // System.err.println("No browseableIndex for reader");
+ return 0;
+ }
+
+ /**
+ * A less time-consuming index validation that only looks at the first and last references in the index
+ * and the first and last chunks in each of those
+ *
+ * @param reader
+ * @return # of chunks examined, or 0 if there is no browseable index for the reader
+ */
+ public static int lessExhaustivelyTestIndex(final SamReader reader) {
+ // look at all chunk offsets in a linear index to make sure they are valid
+ if (reader.indexing().hasBrowseableIndex()) {
+ if (SamIndexes.BAI.fileNameSuffix.endsWith(reader.type().indexExtension())) {
+
+ // content is from an existing bai file
+ final CachingBAMFileIndex existingIndex =
+ (CachingBAMFileIndex) reader.indexing().getBrowseableIndex();
+ final int numRefs = existingIndex.getNumberOfReferences();
+
+ int chunkCount = 0;
+ int indexCount = 0;
+ for (int i = 0; i < numRefs; i++) {
+
+ final BAMIndexContent content = existingIndex.getQueryResults(i);
+
+ final List chunks = content.getAllChunks();
+ final int numChunks = chunks.size();
+ // We are looking only at the first and last chunks
+ for (final int chunkNo : Arrays.asList(0, numChunks - 1)) {
+ chunkCount++;
+
+ final Chunk c = chunks.get(chunkNo);
+ final CloseableIterator iter =
+ ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader).iterator(new BAMFileSpan(c));
+ try {
+ final SAMRecord sam = iter.next();
+ iter.close();
+ } catch (final Exception e) {
+ throw new SAMException(
+ "Exception querying chunk " + chunkNo + " from reference index " + i, e);
+ }
+ }
+
+ // also seek to first and last position in the linear index
+ final long linearIndexEntries[] = content.getLinearIndex().getIndexEntries();
+ for (final int binNo : Arrays.asList(0, linearIndexEntries.length - 1)) {
+ indexCount++;
+ final long l = linearIndexEntries[binNo];
+ try {
+ if (l != 0) {
+ final CloseableIterator iter =
+ ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader)
+ .iterator(new BAMFileSpan(new Chunk(l, l + 1)));
+ final SAMRecord sam =
+ iter.next(); // read the first record identified by the linear index
+ iter.close();
+ }
+ } catch (final Exception e) {
+ throw new SAMException(
+ "Exception in BamIndexValidator. Linear index access failure " + l + " indexCount="
+ + indexCount,
+ e);
+ }
+ }
+ }
+ return chunkCount;
+ } else if (SamIndexes.CSI.fileNameSuffix.endsWith(reader.type().indexExtension())) {
+
+ final CSIIndex existingIndex =
+ (CSIIndex) reader.indexing().getBrowseableIndex(); // new CachingBAMFileIndex(inputBai, null);
+ final int numRefs = existingIndex.getNumberOfReferences();
+
+ int chunkCount = 0;
+ for (int i = 0; i < numRefs; i++) {
+
+ final BAMIndexContent content = existingIndex.getQueryResults(i);
+
+ final List chunks = content.getAllChunks();
+ final int numChunks = chunks.size();
+ // We are looking only at the first and last chunks
+ for (final int chunkNo : Arrays.asList(0, numChunks - 1)) {
+ chunkCount++;
+
+ final Chunk c = chunks.get(chunkNo);
+ final CloseableIterator iter =
+ ((SamReader.PrimitiveSamReaderToSamReaderAdapter) reader).iterator(new BAMFileSpan(c));
+ try {
+ final SAMRecord sam = iter.next();
+ iter.close();
+ } catch (final Exception e) {
+ throw new SAMException(
+ "Exception querying chunk " + chunkNo + " from reference index " + i, e);
+ }
+ }
+ }
+ return chunkCount;
+ }
+ }
+ // else it's not a bam file with a browseable index
+ return 0;
+ }
+}
diff --git a/src/main/java/htsjdk/samtools/Bin.java b/src/main/java/htsjdk/samtools/Bin.java
index 68d83d6a51..e610b07164 100644
--- a/src/main/java/htsjdk/samtools/Bin.java
+++ b/src/main/java/htsjdk/samtools/Bin.java
@@ -24,7 +24,6 @@
package htsjdk.samtools;
import htsjdk.samtools.util.BlockCompressedFilePointerUtil;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -78,10 +77,10 @@ public int getBinNumber() {
*/
@Override
public boolean equals(final Object other) {
- if(other == null) return false;
- if(!(other instanceof Bin)) return false;
+ if (other == null) return false;
+ if (!(other instanceof Bin)) return false;
- final Bin otherBin = (Bin)other;
+ final Bin otherBin = (Bin) other;
return this.referenceSequence == otherBin.referenceSequence && this.binNumber == otherBin.binNumber;
}
@@ -91,7 +90,7 @@ public boolean equals(final Object other) {
*/
@Override
public int hashCode() {
- return ((Integer)referenceSequence).hashCode() ^ ((Integer)binNumber).hashCode();
+ return ((Integer) referenceSequence).hashCode() ^ ((Integer) binNumber).hashCode();
}
/**
@@ -109,12 +108,10 @@ public boolean containsChunks() {
*/
@Override
public int compareTo(final Bin other) {
- if(other == null)
- throw new ClassCastException("Cannot compare to a null object");
+ if (other == null) throw new ClassCastException("Cannot compare to a null object");
// Check the reference sequences first.
- if(this.referenceSequence != other.referenceSequence)
- return referenceSequence - other.referenceSequence;
+ if (this.referenceSequence != other.referenceSequence) return referenceSequence - other.referenceSequence;
// Then check the bin ordering.
return binNumber - other.binNumber;
@@ -123,7 +120,7 @@ public int compareTo(final Bin other) {
/**
* Adds the first chunk to the bin
*/
- public void addInitialChunk(final Chunk newChunk){
+ public void addInitialChunk(final Chunk newChunk) {
final List oldChunks = new ArrayList();
setChunkList(oldChunks);
setLastChunk(newChunk);
@@ -146,8 +143,7 @@ public void addChunk(final Chunk newChunk) {
// Coalesce chunks that are in the same or adjacent file blocks.
// Similar to AbstractBAMFileIndex.optimizeChunkList,
// but no need to copy the list, no minimumOffset, and maintain bin.lastChunk
- if (BlockCompressedFilePointerUtil.areInSameOrAdjacentBlocks(
- lastChunk.getChunkEnd(), chunkStart)) {
+ if (BlockCompressedFilePointerUtil.areInSameOrAdjacentBlocks(lastChunk.getChunkEnd(), chunkStart)) {
lastChunk.setChunkEnd(chunkEnd); // coalesced
} else {
chunkList.add(newChunk);
@@ -159,7 +155,7 @@ public void addChunk(final Chunk newChunk) {
/**
* Sets the chunks associated with this bin
*/
- public void setChunkList(final List list){
+ public void setChunkList(final List list) {
chunkList = list;
}
@@ -167,16 +163,15 @@ public void setChunkList(final List list){
* Gets the list of chunks associated with this bin.
* @return the chunks in this bin. If no chunks are associated, an empty list will be returned.
*/
- public List getChunkList(){
- if(chunkList == null)
- return Collections.emptyList();
+ public List getChunkList() {
+ if (chunkList == null) return Collections.emptyList();
return chunkList;
}
/**
* Optimization to keep lastChunk instead of iterating over all chunks repeatedly
*/
- public void setLastChunk(final Chunk c){
+ public void setLastChunk(final Chunk c) {
lastChunk = c;
}
@@ -185,7 +180,7 @@ public void setLastChunk(final Chunk c){
* (AbstractBAMFileIndex.optimizeChunkList doesn't maintain this)
* @return the last Chunk of the chunkList
*/
- public Chunk getLastChunk(){
+ public Chunk getLastChunk() {
return lastChunk;
}
diff --git a/src/main/java/htsjdk/samtools/BinList.java b/src/main/java/htsjdk/samtools/BinList.java
index 2111ba403f..8c1b9f7f6c 100644
--- a/src/main/java/htsjdk/samtools/BinList.java
+++ b/src/main/java/htsjdk/samtools/BinList.java
@@ -107,11 +107,10 @@ public boolean hasNext() {
*/
@Override
public Bin next() {
- if(!hasNext())
- throw new NoSuchElementException("This BinIterator is currently empty");
+ if (!hasNext()) throw new NoSuchElementException("This BinIterator is currently empty");
int currentBin = nextBin;
- nextBin = bins.nextSetBit(nextBin+1);
- return new Bin(referenceSequence,currentBin);
+ nextBin = bins.nextSetBit(nextBin + 1);
+ return new Bin(referenceSequence, currentBin);
}
@Override
@@ -120,4 +119,3 @@ public void remove() {
}
}
}
-
diff --git a/src/main/java/htsjdk/samtools/BinaryBAMIndexWriter.java b/src/main/java/htsjdk/samtools/BinaryBAMIndexWriter.java
index ec9c7e5371..606f07de87 100644
--- a/src/main/java/htsjdk/samtools/BinaryBAMIndexWriter.java
+++ b/src/main/java/htsjdk/samtools/BinaryBAMIndexWriter.java
@@ -26,7 +26,6 @@
import htsjdk.samtools.util.BinaryCodec;
import htsjdk.samtools.util.IOUtil;
-
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
@@ -97,11 +96,11 @@ public void writeReference(final BAMIndexContent content) {
return;
}
- if (content.getReferenceSequence() != count){
- throw new SAMException("Unexpectedly writing reference " + content.getReferenceSequence() +
- ", expecting reference " + count);
+ if (content.getReferenceSequence() != count) {
+ throw new SAMException("Unexpectedly writing reference " + content.getReferenceSequence()
+ + ", expecting reference " + count);
}
- count ++;
+ count++;
// write bins
@@ -113,21 +112,19 @@ public void writeReference(final BAMIndexContent content) {
return;
}
- //final List chunks = content.getMetaData() == null ? null
+ // final List chunks = content.getMetaData() == null ? null
// : content.getMetaData().getMetaDataChunks();
final BAMIndexMetaData metaData = content.getMetaData();
- codec.writeInt(size + ((metaData != null)? 1 : 0 ));
+ codec.writeInt(size + ((metaData != null) ? 1 : 0));
// codec.writeInt(size);
- for (final Bin bin : bins) { // note, bins will always be sorted
- if (bin.getBinNumber() == GenomicIndexUtil.MAX_BINS)
- continue;
+ for (final Bin bin : bins) { // note, bins will always be sorted
+ if (bin.getBinNumber() == GenomicIndexUtil.MAX_BINS) continue;
writeBin(bin);
}
- // write metadata "bin" and chunks
- if (metaData != null)
- writeChunkMetaData(metaData);
+ // write metadata "bin" and chunks
+ if (metaData != null) writeChunkMetaData(metaData);
// write linear index
@@ -149,7 +146,8 @@ public void writeReference(final BAMIndexContent content) {
try {
codec.getOutputStream().flush();
} catch (final IOException e) {
- throw new SAMException("IOException in BinaryBAMIndexWriter reference " + content.getReferenceSequence(), e);
+ throw new SAMException(
+ "IOException in BinaryBAMIndexWriter reference " + content.getReferenceSequence(), e);
}
}
@@ -173,12 +171,12 @@ public void close() {
private void writeBin(final Bin bin) {
final int binNumber = bin.getBinNumber();
- if (binNumber >= GenomicIndexUtil.MAX_BINS){
+ if (binNumber >= GenomicIndexUtil.MAX_BINS) {
throw new SAMException("Unexpected bin number when writing bam index " + binNumber);
}
-
+
codec.writeInt(binNumber);
- if (bin.getChunkList() == null){
+ if (bin.getChunkList() == null) {
codec.writeInt(0);
return;
}
@@ -204,7 +202,6 @@ private void writeChunkMetaData(final BAMIndexMetaData metaData) {
codec.writeLong(metaData.getLastOffset());
codec.writeLong(metaData.getAlignedRecordCount());
codec.writeLong(metaData.getUnalignedRecordCount());
-
}
private void writeHeader() {
@@ -215,6 +212,6 @@ private void writeHeader() {
}
private void writeNullContent() {
- codec.writeLong(0); // 0 bins , 0 intv
+ codec.writeLong(0); // 0 bins , 0 intv
}
}
diff --git a/src/main/java/htsjdk/samtools/BinaryTagCodec.java b/src/main/java/htsjdk/samtools/BinaryTagCodec.java
index c0d9d33ee2..94f5c8bdf0 100644
--- a/src/main/java/htsjdk/samtools/BinaryTagCodec.java
+++ b/src/main/java/htsjdk/samtools/BinaryTagCodec.java
@@ -25,7 +25,6 @@
import htsjdk.samtools.util.BinaryCodec;
import htsjdk.samtools.util.StringUtil;
-
import java.lang.reflect.Array;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -69,7 +68,7 @@ public BinaryTagCodec(final BinaryCodec binaryCodec) {
private static int getBinaryValueSize(final Object attributeValue) {
switch (getTagValueType(attributeValue)) {
case 'Z':
- return ((String)attributeValue).length() + 1;
+ return ((String) attributeValue).length() + 1;
case 'A':
return 1;
case 'I':
@@ -84,26 +83,26 @@ private static int getBinaryValueSize(final Object attributeValue) {
case 'f':
return 4;
case 'H':
- final byte[] byteArray = (byte[])attributeValue;
+ final byte[] byteArray = (byte[]) attributeValue;
return byteArray.length * 2 + 1;
case 'B':
final int numElements = Array.getLength(attributeValue);
final int elementSize;
- if(attributeValue instanceof byte[]) {
+ if (attributeValue instanceof byte[]) {
elementSize = 1;
- } else if(attributeValue instanceof short[]) {
+ } else if (attributeValue instanceof short[]) {
elementSize = 2;
- } else if(attributeValue instanceof int[]) {
+ } else if (attributeValue instanceof int[]) {
elementSize = 4;
- } else if(attributeValue instanceof float[]) {
+ } else if (attributeValue instanceof float[]) {
elementSize = 4;
} else {
throw new IllegalArgumentException("Unsupported array type: " + attributeValue.getClass());
}
return numElements * elementSize + FIXED_BINARY_ARRAY_TAG_SIZE;
default:
- throw new IllegalArgumentException("When writing BAM, unrecognized tag type " +
- attributeValue.getClass().getName());
+ throw new IllegalArgumentException("When writing BAM, unrecognized tag type "
+ + attributeValue.getClass().getName());
}
}
@@ -127,21 +126,27 @@ static char getTagValueType(final Object value) {
} else if (value instanceof Float) {
return 'f';
} else if (value instanceof Number) {
- if (!(value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long)) {
- throw new IllegalArgumentException("Unrecognized tag type " + value.getClass().getName());
+ if (!(value instanceof Byte
+ || value instanceof Short
+ || value instanceof Integer
+ || value instanceof Long)) {
+ throw new IllegalArgumentException(
+ "Unrecognized tag type " + value.getClass().getName());
}
- return getIntegerType(((Number)value).longValue());
+ return getIntegerType(((Number) value).longValue());
} /*
Note that H tag type is never written anymore, because B style is more compact.
else if (value instanceof byte[]) {
return 'H';
}
- */
- else if (value instanceof byte[] || value instanceof short[] || value instanceof int[] || value instanceof float[]) {
+ */ else if (value instanceof byte[]
+ || value instanceof short[]
+ || value instanceof int[]
+ || value instanceof float[]) {
return 'B';
} else {
- throw new IllegalArgumentException("When writing BAM, unrecognized tag type " +
- value.getClass().getName());
+ throw new IllegalArgumentException("When writing BAM, unrecognized tag type "
+ + value.getClass().getName());
}
}
@@ -149,7 +154,7 @@ else if (value instanceof byte[] || value instanceof short[] || value instanceof
* @param val Integer tag value.
* @return Tag type corresponding to the smallest integer type that will hold the given value.
*/
- static private char getIntegerType(final long val) {
+ private static char getIntegerType(final long val) {
if (val > MAX_UINT) {
throw new IllegalArgumentException("Integer attribute value too large to be encoded in BAM");
}
@@ -190,31 +195,31 @@ public void writeTag(final short tag, final Object value, final boolean isUnsign
switch (tagValueType) {
case 'Z':
- binaryCodec.writeString((String)value, false, true);
+ binaryCodec.writeString((String) value, false, true);
break;
case 'A':
- binaryCodec.writeByte(((Character)value));
+ binaryCodec.writeByte(((Character) value));
break;
case 'I':
- binaryCodec.writeUInt((Long)value);
+ binaryCodec.writeUInt((Long) value);
break;
case 'i':
- binaryCodec.writeInt(((Number)value).intValue());
+ binaryCodec.writeInt(((Number) value).intValue());
break;
case 's':
- binaryCodec.writeShort(((Number)value).shortValue());
+ binaryCodec.writeShort(((Number) value).shortValue());
break;
case 'S':
- binaryCodec.writeUShort(((Number)value).intValue());
+ binaryCodec.writeUShort(((Number) value).intValue());
break;
case 'c':
- binaryCodec.writeByte(((Number)value).byteValue());
+ binaryCodec.writeByte(((Number) value).byteValue());
break;
case 'C':
- binaryCodec.writeUByte(((Integer)value).shortValue());
+ binaryCodec.writeUByte(((Integer) value).shortValue());
break;
case 'f':
- binaryCodec.writeFloat((Float)value);
+ binaryCodec.writeFloat((Float) value);
break;
/*
Writing H is no longer supported
@@ -227,35 +232,35 @@ public void writeTag(final short tag, final Object value, final boolean isUnsign
writeArray(value, isUnsignedArray);
break;
default:
- throw new IllegalArgumentException("When writing BAM, unrecognized tag type " +
- value.getClass().getName());
+ throw new IllegalArgumentException("When writing BAM, unrecognized tag type "
+ + value.getClass().getName());
}
}
private void writeArray(final Object value, final boolean isUnsignedArray) {
if (value instanceof byte[]) {
- binaryCodec.writeByte(isUnsignedArray? 'C': 'c');
+ binaryCodec.writeByte(isUnsignedArray ? 'C' : 'c');
final byte[] array = (byte[]) value;
binaryCodec.writeInt(array.length);
- for (final byte element: array) binaryCodec.writeByte(element);
+ for (final byte element : array) binaryCodec.writeByte(element);
} else if (value instanceof short[]) {
- binaryCodec.writeByte(isUnsignedArray? 'S': 's');
+ binaryCodec.writeByte(isUnsignedArray ? 'S' : 's');
final short[] array = (short[]) value;
binaryCodec.writeInt(array.length);
- for (final short element: array) binaryCodec.writeShort(element);
+ for (final short element : array) binaryCodec.writeShort(element);
} else if (value instanceof int[]) {
- binaryCodec.writeByte(isUnsignedArray? 'I': 'i');
+ binaryCodec.writeByte(isUnsignedArray ? 'I' : 'i');
final int[] array = (int[]) value;
binaryCodec.writeInt(array.length);
- for (final int element: array) binaryCodec.writeInt(element);
+ for (final int element : array) binaryCodec.writeInt(element);
} else if (value instanceof float[]) {
binaryCodec.writeByte('f');
final float[] array = (float[]) value;
binaryCodec.writeInt(array.length);
- for (final float element: array) binaryCodec.writeFloat(element);
+ for (final float element : array) binaryCodec.writeFloat(element);
} else throw new SAMException("Unrecognized array value type: " + value.getClass());
}
@@ -266,8 +271,11 @@ private void writeArray(final Object value, final boolean isUnsignedArray) {
* @param offset Where in binaryRep tags start.
* @param length How many bytes in binaryRep are tag storage.
*/
- public static SAMBinaryTagAndValue readTags(final byte[] binaryRep, final int offset,
- final int length, final ValidationStringency validationStringency) {
+ public static SAMBinaryTagAndValue readTags(
+ final byte[] binaryRep,
+ final int offset,
+ final int length,
+ final ValidationStringency validationStringency) {
final ByteBuffer byteBuffer = ByteBuffer.wrap(binaryRep, offset, length);
byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
@@ -282,7 +290,8 @@ public static SAMBinaryTagAndValue readTags(final byte[] binaryRep, final int of
tmp = new SAMBinaryTagAndValue(tag, readSingleValue(tagType, byteBuffer, validationStringency), true);
} else {
final TagValueAndUnsignedArrayFlag valueAndFlag = readArray(byteBuffer, validationStringency);
- if (valueAndFlag.isUnsignedArray) tmp = new SAMBinaryTagAndUnsignedArrayValue(tag, valueAndFlag.value, true);
+ if (valueAndFlag.isUnsignedArray)
+ tmp = new SAMBinaryTagAndUnsignedArrayValue(tag, valueAndFlag.value, true);
else tmp = new SAMBinaryTagAndValue(tag, valueAndFlag.value, true);
}
@@ -292,12 +301,10 @@ public static SAMBinaryTagAndValue readTags(final byte[] binaryRep, final int of
if (head == null) {
head = tmp;
tail = tmp;
- }
- else if (tmp.tag > tail.tag) {
+ } else if (tmp.tag > tail.tag) {
tail.next = tmp;
tail = tmp;
- }
- else {
+ } else {
head = head.insert(tmp);
}
}
@@ -311,57 +318,58 @@ else if (tmp.tag > tail.tag) {
* @param byteBuffer Little-ending byte buffer to read value from.
* @return Value in in-memory Object form.
*/
- private static Object readSingleValue(final byte tagType, final ByteBuffer byteBuffer,
- final ValidationStringency validationStringency) {
+ private static Object readSingleValue(
+ final byte tagType, final ByteBuffer byteBuffer, final ValidationStringency validationStringency) {
switch (tagType) {
case 'Z':
return readNullTerminatedString(byteBuffer);
case 'A':
- return (char)byteBuffer.get();
+ return (char) byteBuffer.get();
case 'I':
final long val = byteBuffer.getInt() & 0xffffffffL;
- if ( val <= Integer.MAX_VALUE ) {
- return (int)val;
+ if (val <= Integer.MAX_VALUE) {
+ return (int) val;
}
// If it won't fit into a signed integer, but is within range for an unsigned 32-bit integer,
// return it directly as a long
- if (! SAMUtils.isValidUnsignedIntegerAttribute(val)) {
- SAMUtils.processValidationError(new SAMValidationError(SAMValidationError.Type.TAG_VALUE_TOO_LARGE,
- "Unsigned integer is out of range for a 32-bit unsigned value: " + val, null), validationStringency);
+ if (!SAMUtils.isValidUnsignedIntegerAttribute(val)) {
+ SAMUtils.processValidationError(
+ new SAMValidationError(
+ SAMValidationError.Type.TAG_VALUE_TOO_LARGE,
+ "Unsigned integer is out of range for a 32-bit unsigned value: " + val,
+ null),
+ validationStringency);
}
return val;
case 'i':
return byteBuffer.getInt();
case 's':
- return (int)byteBuffer.getShort();
+ return (int) byteBuffer.getShort();
case 'S':
// Convert to unsigned short stored in an int
return byteBuffer.getShort() & 0xffff;
case 'c':
- return (int)byteBuffer.get();
+ return (int) byteBuffer.get();
case 'C':
// Convert to unsigned byte stored in an int
- return (int)byteBuffer.get() & 0xff;
+ return (int) byteBuffer.get() & 0xff;
case 'f':
return byteBuffer.getFloat();
case 'H':
final String hexRep = readNullTerminatedString(byteBuffer);
return StringUtil.hexStringToBytes(hexRep);
default:
- throw new SAMFormatException("Unrecognized tag type: " + (char)tagType);
+ throw new SAMFormatException("Unrecognized tag type: " + (char) tagType);
}
}
-
-
-
/**
* Read value of specified type.
* @param byteBuffer Little-ending byte buffer to read value from.
* @return CVO containing the value in in-memory Object form, and a flag indicating whether it is unsigned or not.
*/
- private static TagValueAndUnsignedArrayFlag readArray(final ByteBuffer byteBuffer,
- final ValidationStringency validationStringency) {
+ private static TagValueAndUnsignedArrayFlag readArray(
+ final ByteBuffer byteBuffer, final ValidationStringency validationStringency) {
final byte arrayType = byteBuffer.get();
final boolean isUnsigned = Character.isUpperCase(arrayType);
final int length = byteBuffer.getInt();
@@ -401,7 +409,7 @@ private static TagValueAndUnsignedArrayFlag readArray(final ByteBuffer byteBuffe
}
default:
- throw new SAMFormatException("Unrecognized tag array type: " + (char)arrayType);
+ throw new SAMFormatException("Unrecognized tag array type: " + (char) arrayType);
}
return new TagValueAndUnsignedArrayFlag(value, isUnsigned);
}
@@ -412,7 +420,9 @@ private static String readNullTerminatedString(final ByteBuffer byteBuffer) {
final int start = byteBuffer.arrayOffset() + byteBuffer.position();
final int limit = byteBuffer.arrayOffset() + byteBuffer.limit();
int end = start;
- while (end < limit && array[end] != 0) { end++; }
+ while (end < limit && array[end] != 0) {
+ end++;
+ }
if (end >= limit) {
throw new SAMFormatException("Null-terminated string tag value is not null terminated.");
}
diff --git a/src/main/java/htsjdk/samtools/BinningIndexBuilder.java b/src/main/java/htsjdk/samtools/BinningIndexBuilder.java
index 3b329d2bc1..76046558fd 100644
--- a/src/main/java/htsjdk/samtools/BinningIndexBuilder.java
+++ b/src/main/java/htsjdk/samtools/BinningIndexBuilder.java
@@ -23,12 +23,9 @@
*/
package htsjdk.samtools;
-import htsjdk.samtools.util.BlockCompressedFilePointerUtil;
+import static htsjdk.samtools.GenomicIndexUtil.MAX_BINS;
import java.util.Arrays;
-import java.util.List;
-
-import static htsjdk.samtools.GenomicIndexUtil.MAX_BINS;
/**
* Builder for a BinningIndexContent object.
@@ -54,7 +51,8 @@ public class BinningIndexBuilder {
* if false, leave uninitialized values as -1, which is required when merging index files
* (see {@link BAMIndexMerger})
*/
- public BinningIndexBuilder(final int referenceSequence, final int sequenceLength, final boolean fillInUninitializedValues) {
+ public BinningIndexBuilder(
+ final int referenceSequence, final int sequenceLength, final boolean fillInUninitializedValues) {
this.referenceSequence = referenceSequence;
this.fillInUninitializedValues = fillInUninitializedValues;
// Initially set each window to -1 so we can distinguish between windows that have no overlapping
@@ -84,8 +82,11 @@ public BinningIndexBuilder(final int referenceSequence) {
*/
public interface FeatureToBeIndexed {
public int getStart();
+
public int getEnd();
+
public Integer getIndexingBin();
+
public Chunk getChunk();
}
@@ -96,7 +97,6 @@ public void processFeature(final FeatureToBeIndexed feature) {
final Integer binNumber = feature.getIndexingBin();
final int binNum = binNumber == null ? computeIndexingBin(feature) : binNumber;
-
// is there a bin already represented for this index? if not, add one
final Bin bin;
if (bins[binNum] != null) {
@@ -120,7 +120,7 @@ public void processFeature(final FeatureToBeIndexed feature) {
int startWindow = LinearIndex.convertToLinearIndexOffset(feature.getStart()); // the 16k window
final int endWindow;
- if (featureEnd == GenomicIndexUtil.UNSET_GENOMIC_LOCATION) { // assume feature uses one position
+ if (featureEnd == GenomicIndexUtil.UNSET_GENOMIC_LOCATION) { // assume feature uses one position
// Next line for C (samtools index) compatibility. Differs only when on a window boundary
startWindow = LinearIndex.convertToLinearIndexOffset(feature.getStart() - 1);
endWindow = startWindow;
@@ -151,16 +151,16 @@ public void processFeature(final FeatureToBeIndexed feature) {
*/
public BinningIndexContent generateIndexContent() {
-
// process bins
- if (binsSeen == 0) return null; // no bins for this reference
+ if (binsSeen == 0) return null; // no bins for this reference
// process chunks
// nothing needed
// process linear index
// linear index will only be as long as the largest index seen
- final long[] newIndex = new long[largestIndexSeen + 1]; // in java1.6 Arrays.copyOf(index, largestIndexSeen + 1);
+ final long[] newIndex =
+ new long[largestIndexSeen + 1]; // in java1.6 Arrays.copyOf(index, largestIndexSeen + 1);
// C (samtools index) also fills in intermediate 0's with values. This seems unnecessary, but safe
long lastNonZeroOffset = 0;
@@ -183,7 +183,7 @@ public BinningIndexContent generateIndexContent() {
private int computeIndexingBin(final FeatureToBeIndexed feature) {
// regionToBin has zero-based, half-open API
- final int start = feature.getStart()-1;
+ final int start = feature.getStart() - 1;
int end = feature.getEnd();
if (end <= 0) {
// If feature end cannot be determined (e.g. because a read is not really aligned),
diff --git a/src/main/java/htsjdk/samtools/BinningIndexContent.java b/src/main/java/htsjdk/samtools/BinningIndexContent.java
index bc55ef693d..e2ad018566 100644
--- a/src/main/java/htsjdk/samtools/BinningIndexContent.java
+++ b/src/main/java/htsjdk/samtools/BinningIndexContent.java
@@ -51,7 +51,6 @@ public class BinningIndexContent {
*/
private final LinearIndex mLinearIndex;
-
/**
* @param referenceSequence Content corresponds to this reference.
* @param binList Array of bins represented by this content, possibly sparse
@@ -110,7 +109,6 @@ public LinearIndex getLinearIndex() {
return mLinearIndex;
}
-
/**
*
* @param startPos 1-based, inclusive
@@ -118,7 +116,7 @@ public LinearIndex getLinearIndex() {
* @return List of Chunks overlapping the given region. May return null if there are none.
*/
public List getChunksOverlapping(final int startPos, final int endPos) {
- final BitSet overlappingBins = GenomicIndexUtil.regionToBins(startPos,endPos);
+ final BitSet overlappingBins = GenomicIndexUtil.regionToBins(startPos, endPos);
if (overlappingBins == null) return null;
// System.out.println("# Sequence target TID: " + referenceIndex);
@@ -147,7 +145,7 @@ public static class BinList implements Iterable {
private final Bin[] mBinArray;
public final int numberOfNonNullBins;
- public final int maxBinNumber; // invariant: maxBinNumber = mBinArray.length -1 since array is 0 based
+ public final int maxBinNumber; // invariant: maxBinNumber = mBinArray.length -1 since array is 0 based
/**
* @param binArray a sparse array representation of the bins. The index into the array is the bin number.
@@ -207,8 +205,7 @@ public boolean hasNext() {
*/
@Override
public Bin next() {
- if (!hasNext())
- throw new NoSuchElementException("This BinIterator is currently empty");
+ if (!hasNext()) throw new NoSuchElementException("This BinIterator is currently empty");
final Bin result = getBin(nextBin);
nextBin++;
return result;
diff --git a/src/main/java/htsjdk/samtools/BrowseableBAMIndex.java b/src/main/java/htsjdk/samtools/BrowseableBAMIndex.java
index c6eca51e55..8ebe3d722e 100644
--- a/src/main/java/htsjdk/samtools/BrowseableBAMIndex.java
+++ b/src/main/java/htsjdk/samtools/BrowseableBAMIndex.java
@@ -21,7 +21,7 @@ public interface BrowseableBAMIndex extends BAMIndex {
* @return the level associated with the given bin number.
*/
public int getLevelForBin(final Bin bin);
-
+
/**
* Gets the first locus that this bin can index into.
* @param bin The bin to test.
@@ -50,5 +50,5 @@ public interface BrowseableBAMIndex extends BAMIndex {
* @param bin The bin over which to perform an overlapping query.
* @return The file pointers
*/
- BAMFileSpan getSpanOverlapping(final Bin bin);
+ BAMFileSpan getSpanOverlapping(final Bin bin);
}
diff --git a/src/main/java/htsjdk/samtools/CRAMBAIIndexer.java b/src/main/java/htsjdk/samtools/CRAMBAIIndexer.java
index 38bdc35b62..496d697ca6 100755
--- a/src/main/java/htsjdk/samtools/CRAMBAIIndexer.java
+++ b/src/main/java/htsjdk/samtools/CRAMBAIIndexer.java
@@ -1,452 +1,453 @@
-/*******************************************************************************
- * Copyright 2013 EMBL-EBI
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- ******************************************************************************/
-/*
- * The MIT License
- *
- * Copyright (c) 2014 The Broad Institute
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy
- * of this software and associated documentation files (the "Software"), to deal
- * in the Software without restriction, including without limitation the rights
- * to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
- * copies of the Software, and to permit persons to whom the Software is
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in
- * all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- * THE SOFTWARE.
- */
-package htsjdk.samtools;
-
-import htsjdk.samtools.cram.BAIEntry;
-import htsjdk.samtools.cram.CRAIEntry;
-import htsjdk.samtools.cram.CRAIIndex;
-import htsjdk.samtools.cram.build.CramIO;
-import htsjdk.samtools.cram.ref.ReferenceContext;
-import htsjdk.samtools.cram.structure.*;
-import htsjdk.samtools.seekablestream.SeekableStream;
-import htsjdk.samtools.util.BlockCompressedFilePointerUtil;
-import htsjdk.samtools.util.Log;
-import htsjdk.samtools.util.ProgressLogger;
-import htsjdk.samtools.util.RuntimeIOException;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.*;
-
-/**
- * Class for both constructing BAM index content and writing it out.
- *
- * There are two usage patterns:
- *
- * 1) Building a bam index (BAI) while building the CRAM file
- * 2) Building a bam index (BAI) from an existing CRAI file
- *
- * 1) is driven by {@link CRAMContainerStreamWriter} and proceeds by calling {@link CRAMBAIIndexer#processContainer}
- * after each {@link Container} is built, and {@link CRAMBAIIndexer#finish()} is called at the end.
- *
- * 2) is driven by {@link CRAIIndex#openCraiFileAsBaiStream(InputStream, SAMSequenceDictionary)}
- * and proceeds by processing {@link CRAIEntry} elements obtained from
- * {@link CRAMCRAIIndexer#readIndex(InputStream)}. {@link CRAMBAIIndexer#processBAIEntry(BAIEntry)}
- * is called on each {@link CRAIEntry} and {@link CRAMBAIIndexer#finish()} is called at the end.
- *
- * NOTE: a third pattern of building a BAI from a CRAM file is also supported by this class,
- * but it is unused. This would be accomplished via {@link #createIndex(SeekableStream, File, Log, ValidationStringency)}.
- */
-public class CRAMBAIIndexer implements CRAMIndexer {
-
- // The number of references (chromosomes) in the BAM file
- private final int numReferences;
-
- // output written as binary, or (for debugging) as text
- private final BAMIndexWriter outputWriter;
-
- private int currentReference = 0;
-
- // content is built up from the input bam file using this
- private final CRAMBAIIndexBuilder indexBuilder;
- private final CompressorCache compressorCache = new CompressorCache();
-
- /**
- * Create a CRAM indexer that writes BAI to a file.
- *
- * @param output binary BAM Index (.bai) file
- * @param fileHeader header for the corresponding bam file
- */
- private CRAMBAIIndexer(final File output, final SAMFileHeader fileHeader) {
- if (fileHeader.getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
- throw new SAMException("CRAM file must be coordinate-sorted for indexing.");
- }
- numReferences = fileHeader.getSequenceDictionary().size();
- indexBuilder = new CRAMBAIIndexBuilder(fileHeader);
- outputWriter = new BinaryBAMIndexWriter(numReferences, output);
- }
-
- /**
- * Create a CRAM indexer that writes BAI to a stream.
- *
- * @param output Index will be written here. output will be closed when finish() method is called.
- * @param fileHeader header for the corresponding bam file.
- */
- public CRAMBAIIndexer(final OutputStream output, final SAMFileHeader fileHeader) {
- if (fileHeader.getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
- throw new SAMException("CRAM file mut be coordinate-sorted for indexing.");
- }
- numReferences = fileHeader.getSequenceDictionary().size();
- indexBuilder = new CRAMBAIIndexBuilder(fileHeader);
- outputWriter = new BinaryBAMIndexWriter(numReferences, output);
- }
-
- /**
- * Index a container, any of mapped, unmapped and multiple references are allowed.
- * The only requirement is sort order by coordinate.
- * For multiref containers the method reads the container through unpacking all reads.
- * This is slower than single reference but should be faster than normal reading.
- *
- * @param container container to be indexed
- */
- @Override
- public void processContainer(final Container container, final ValidationStringency validationStringency) {
- container.getBAIEntries(compressorCache).forEach(b -> processBAIEntry(b));
- }
-
- public final void processBAIEntry(final BAIEntry baiEntry) {
-
- final ReferenceContext entryContext = baiEntry.getReferenceContext();
- if (entryContext.isMultiRef()) {
- throw new SAMException("Expecting a single reference or unmapped slice.");
- }
-
- if (entryContext.isMappedSingleRef()) {
- final int reference = entryContext.getReferenceSequenceID();
- if (reference != currentReference) {
- // process any completed references
- advanceToReference(reference);
- }
-
- // check that it advanced properly
- if (reference != currentReference) {
- throw new SAMException(
- String.format("Unexpected reference %s when constructing index for reference %d for slice",
- reference,
- currentReference));
- }
- }
-
- indexBuilder.recordBAIEntryIndexMetadata(baiEntry);
-
- if (entryContext.isMappedSingleRef()) {
- indexBuilder.processBAIEntry(baiEntry);
- }
- }
-
- /**
- * After all the slices have been processed, finish is called.
- * Writes any final information and closes the output file.
- */
- @Override
- public void finish() {
- // process any remaining references
- advanceToReference(numReferences);
- outputWriter.writeNoCoordinateRecordCount(indexBuilder.getNoCoordinateRecordCount());
- outputWriter.close();
- }
-
- /**
- * write out any references between the currentReference and the nextReference
- */
- private void advanceToReference(final int nextReference) {
- while (currentReference < nextReference) {
- final BAMIndexContent content = indexBuilder.processCurrentReference();
- outputWriter.writeReference(content);
- currentReference++;
- indexBuilder.startNewReference();
- }
- }
-
- /**
- * Generates a BAI index file from an input CRAM stream
- *
- * @param stream CRAM stream to index
- * @param output File for output index file
- * @param log optional {@link htsjdk.samtools.util.Log} to output progress
- */
- public static void createIndex(final SeekableStream stream,
- final File output,
- final Log log,
- final ValidationStringency validationStringency) {
-
- final CramHeader cramHeader = CramIO.readCramHeader(stream);
- final SAMFileHeader samFileHeader = Container.readSAMFileHeaderContainer(cramHeader.getCRAMVersion(), stream, null);
- if (samFileHeader.getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
- throw new SAMException(String.format(
- "Input must be coordinate sorted (found %s) to create an index.",
- samFileHeader.getSortOrder()));
- }
- final CRAMBAIIndexer indexer = new CRAMBAIIndexer(output, samFileHeader);
-
- Container container = null;
- final ProgressLogger progressLogger = new ProgressLogger(log, 1, "indexed", "slices");
- do {
- try {
- container = new Container(cramHeader.getCRAMVersion(), stream, stream.position());
- } catch (final IOException e) {
- throw new RuntimeIOException("error getting stream position", e);
- }
- if (container == null || container.isEOF()) {
- break;
- }
-
- indexer.processContainer(container, validationStringency);
-
- if (null != log) {
- String sequenceName;
- final AlignmentContext alignmentContext = container.getAlignmentContext();
- final ReferenceContext containerReferenceContext = alignmentContext.getReferenceContext();
- switch (containerReferenceContext.getType()) {
- case UNMAPPED_UNPLACED_TYPE:
- sequenceName = "?";
- break;
- case MULTIPLE_REFERENCE_TYPE:
- sequenceName = "???";
- break;
- default:
- sequenceName = samFileHeader.getSequence(
- containerReferenceContext.getReferenceSequenceID()).getSequenceName();
- break;
- }
- progressLogger.record(sequenceName, alignmentContext.getAlignmentStart());
- }
-
- } while (!container.isEOF());
-
- indexer.finish();
- }
-
- /**
- * Class for constructing BAM index files.
- * One instance is used to construct an entire index.
- * processAlignment is called for each alignment until a new reference is encountered, then
- * processReference is called when all records for the reference have been processed.
- */
- private class CRAMBAIIndexBuilder {
-
- private final SAMFileHeader bamHeader;
-
- // the bins for the current reference
- private Bin[] bins; // made only as big as needed for each reference
- private int binsSeen = 0;
-
- // linear index for the current reference
- private final long[] index = new long[LinearIndex.MAX_LINEAR_INDEX_SIZE];
- private int largestIndexSeen = -1;
-
- // information in meta data
- private final BAMIndexMetaData indexStats = new BAMIndexMetaData();
-
- /**
- * @param header SAMFileHeader used for reference name (in index stats) and for max bin number
- */
- private CRAMBAIIndexBuilder(final SAMFileHeader header) {
- this.bamHeader = header;
- }
-
- private SAMFileHeader getBamHeader() {
- return bamHeader;
- }
-
- private void recordBAIEntryIndexMetadata(final BAIEntry baiEntry) {
- indexStats.recordMetaData(baiEntry);
- }
-
- private int computeIndexingBin(final BAIEntry baiEntry) {
- // regionToBin has zero-based, half-open API
- //final AlignmentContext sliceAlignmentContext = baiEntry.getAlignmentContext();
- final int alignmentStart = baiEntry.getAlignmentStart() - 1;
- int alignmentEnd = baiEntry.getAlignmentStart() + baiEntry.getAlignmentSpan() - 1;
- if (alignmentEnd <= alignmentStart) {
- // If alignment end cannot be determined (e.g. because this read is not really aligned),
- // then treat this as a one base alignment for indexing purposes.
- alignmentEnd = alignmentStart + 1;
- }
- return GenomicIndexUtil.regionToBin(alignmentStart, alignmentEnd);
- }
-
- /**
- * Record any index information for a given CRAM slice
- *
- * Reads these Slice fields:
- * sequenceId, alignmentStart, alignmentSpan, containerByteOffset, index
- *
- //* @param slice CRAM slice, single ref only.
- */
- private void processBAIEntry(final BAIEntry baiEntry) {
- final ReferenceContext sliceContext = baiEntry.getReferenceContext();
- if (! sliceContext.isMappedSingleRef()) {
- return; // do nothing for records without coordinates, but count them
- }
-
- // various checks
- final int reference = sliceContext.getReferenceSequenceID();
- if (reference != currentReference) {
- throw new SAMException(
- String.format("Unexpected reference %s when constructing index for reference %d for slice",
- reference,
- currentReference));
- }
-
- // process bins
-
- final int binNum = computeIndexingBin(baiEntry);
-
- // has the bins array been allocated? If not, do so
- if (bins == null) {
- final SAMSequenceRecord seq = bamHeader.getSequence(reference);
- if (seq == null) {
- bins = new Bin[GenomicIndexUtil.MAX_BINS + 1];
- } else {
- bins = new Bin[AbstractBAMFileIndex.getMaxBinNumberForSequenceLength(seq.getSequenceLength()) + 1];
- }
- }
-
- // is there a bin already represented for this index? if not, add one
- final Bin bin;
- if (bins[binNum] != null) {
- bin = bins[binNum];
- } else {
- bin = new Bin(reference, binNum);
- bins[binNum] = bin;
- binsSeen++;
- }
-
- // process chunks
-
- final long chunkStart = (baiEntry.getContainerStartByteOffset() << 16) | baiEntry.getLandmarkIndex();
- final long chunkEnd = ((baiEntry.getContainerStartByteOffset() << 16) | baiEntry.getLandmarkIndex()) + 1;
-
- final Chunk newChunk = new Chunk(chunkStart, chunkEnd);
-
- final List oldChunks = bin.getChunkList();
- if (!bin.containsChunks()) {
- bin.addInitialChunk(newChunk);
-
- } else {
- final Chunk lastChunk = bin.getLastChunk();
-
- // Coalesce chunks that are in the same or adjacent file blocks.
- // Similar to AbstractBAMFileIndex.optimizeChunkList,
- // but no need to copy the list, no minimumOffset, and maintain bin.lastChunk
- if (BlockCompressedFilePointerUtil.areInSameOrAdjacentBlocks(lastChunk.getChunkEnd(), chunkStart)) {
- lastChunk.setChunkEnd(chunkEnd); // coalesced
- } else {
- oldChunks.add(newChunk);
- bin.setLastChunk(newChunk);
- }
- }
-
- // process linear index
-
- // the smallest file offset that appears in the 16k window for this bin
- final int alignmentStart = baiEntry.getAlignmentStart();
- final int alignmentEnd = baiEntry.getAlignmentStart() + baiEntry.getAlignmentSpan();
- int startWindow = LinearIndex.convertToLinearIndexOffset(alignmentStart); // the 16k window
- final int endWindow;
-
- if (alignmentEnd == SAMRecord.NO_ALIGNMENT_START) { // assume alignment uses one position
- // Next line for C (samtools index) compatibility. Differs only when on a window boundary
- startWindow = LinearIndex.convertToLinearIndexOffset(alignmentStart - 1);
- endWindow = startWindow;
- } else {
- endWindow = LinearIndex.convertToLinearIndexOffset(alignmentEnd);
- }
-
- if (endWindow > largestIndexSeen) {
- largestIndexSeen = endWindow;
- }
-
- // set linear index at every 16K window that this alignment overlaps
- for (int win = startWindow; win <= endWindow; win++) {
- if (index[win] == 0 || chunkStart < index[win]) {
- index[win] = chunkStart;
- }
- }
- }
-
- /**
- * Creates the BAMIndexContent for this reference.
- * Requires all alignments of the reference have already been processed.
- */
- private BAMIndexContent processCurrentReference() {
-
- // process bins
- if (binsSeen == 0) {
- return null; // no bins for this reference
- }
-
- // process chunks
- // nothing needed
-
- // process linear index
- // linear index will only be as long as the largest index seen
- final long[] newIndex = new long[largestIndexSeen + 1]; // in java1.6 Arrays.copyOf(index, largestIndexSeen + 1);
-
- // C (samtools index) also fills in intermediate 0's with values. This seems unnecessary, but safe
- long lastNonZeroOffset = 0;
- for (int i = 0; i <= largestIndexSeen; i++) {
- if (index[i] == 0) {
- index[i] = lastNonZeroOffset; // not necessary, but C (samtools index) does this
- // note, if you remove the above line BAMIndexWriterTest.compareTextual and compareBinary will have to change
- } else {
- lastNonZeroOffset = index[i];
- }
- newIndex[i] = index[i];
- }
-
- final LinearIndex linearIndex = new LinearIndex(currentReference, 0, newIndex);
-
- return new BAMIndexContent(currentReference, bins, binsSeen, indexStats, linearIndex);
- }
-
- /**
- * @return the count of records with no coordinate positions
- */
- private long getNoCoordinateRecordCount() {
- return indexStats.getNoCoordinateRecordCount();
- }
-
- /**
- * reinitialize all data structures when the reference changes
- */
- private void startNewReference() {
- bins = null;
- if (binsSeen > 0) {
- Arrays.fill(index, 0);
- }
- binsSeen = 0;
- largestIndexSeen = -1;
- indexStats.newReference();
- }
- }
-}
+/*******************************************************************************
+ * Copyright 2013 EMBL-EBI
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ ******************************************************************************/
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2014 The Broad Institute
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package htsjdk.samtools;
+
+import htsjdk.samtools.cram.BAIEntry;
+import htsjdk.samtools.cram.CRAIEntry;
+import htsjdk.samtools.cram.CRAIIndex;
+import htsjdk.samtools.cram.build.CramIO;
+import htsjdk.samtools.cram.ref.ReferenceContext;
+import htsjdk.samtools.cram.structure.*;
+import htsjdk.samtools.seekablestream.SeekableStream;
+import htsjdk.samtools.util.BlockCompressedFilePointerUtil;
+import htsjdk.samtools.util.Log;
+import htsjdk.samtools.util.ProgressLogger;
+import htsjdk.samtools.util.RuntimeIOException;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.*;
+
+/**
+ * Class for both constructing BAM index content and writing it out.
+ *
+ * There are two usage patterns:
+ *
+ * 1) Building a bam index (BAI) while building the CRAM file
+ * 2) Building a bam index (BAI) from an existing CRAI file
+ *
+ * 1) is driven by {@link CRAMContainerStreamWriter} and proceeds by calling {@link CRAMBAIIndexer#processContainer}
+ * after each {@link Container} is built, and {@link CRAMBAIIndexer#finish()} is called at the end.
+ *
+ * 2) is driven by {@link CRAIIndex#openCraiFileAsBaiStream(InputStream, SAMSequenceDictionary)}
+ * and proceeds by processing {@link CRAIEntry} elements obtained from
+ * {@link CRAMCRAIIndexer#readIndex(InputStream)}. {@link CRAMBAIIndexer#processBAIEntry(BAIEntry)}
+ * is called on each {@link CRAIEntry} and {@link CRAMBAIIndexer#finish()} is called at the end.
+ *
+ * NOTE: a third pattern of building a BAI from a CRAM file is also supported by this class,
+ * but it is unused. This would be accomplished via {@link #createIndex(SeekableStream, File, Log, ValidationStringency)}.
+ */
+public class CRAMBAIIndexer implements CRAMIndexer {
+
+ // The number of references (chromosomes) in the BAM file
+ private final int numReferences;
+
+ // output written as binary, or (for debugging) as text
+ private final BAMIndexWriter outputWriter;
+
+ private int currentReference = 0;
+
+ // content is built up from the input bam file using this
+ private final CRAMBAIIndexBuilder indexBuilder;
+ private final CompressorCache compressorCache = new CompressorCache();
+
+ /**
+ * Create a CRAM indexer that writes BAI to a file.
+ *
+ * @param output binary BAM Index (.bai) file
+ * @param fileHeader header for the corresponding bam file
+ */
+ private CRAMBAIIndexer(final File output, final SAMFileHeader fileHeader) {
+ if (fileHeader.getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
+ throw new SAMException("CRAM file must be coordinate-sorted for indexing.");
+ }
+ numReferences = fileHeader.getSequenceDictionary().size();
+ indexBuilder = new CRAMBAIIndexBuilder(fileHeader);
+ outputWriter = new BinaryBAMIndexWriter(numReferences, output);
+ }
+
+ /**
+ * Create a CRAM indexer that writes BAI to a stream.
+ *
+ * @param output Index will be written here. output will be closed when finish() method is called.
+ * @param fileHeader header for the corresponding bam file.
+ */
+ public CRAMBAIIndexer(final OutputStream output, final SAMFileHeader fileHeader) {
+ if (fileHeader.getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
+ throw new SAMException("CRAM file mut be coordinate-sorted for indexing.");
+ }
+ numReferences = fileHeader.getSequenceDictionary().size();
+ indexBuilder = new CRAMBAIIndexBuilder(fileHeader);
+ outputWriter = new BinaryBAMIndexWriter(numReferences, output);
+ }
+
+ /**
+ * Index a container, any of mapped, unmapped and multiple references are allowed.
+ * The only requirement is sort order by coordinate.
+ * For multiref containers the method reads the container through unpacking all reads.
+ * This is slower than single reference but should be faster than normal reading.
+ *
+ * @param container container to be indexed
+ */
+ @Override
+ public void processContainer(final Container container, final ValidationStringency validationStringency) {
+ container.getBAIEntries(compressorCache).forEach(b -> processBAIEntry(b));
+ }
+
+ public final void processBAIEntry(final BAIEntry baiEntry) {
+
+ final ReferenceContext entryContext = baiEntry.getReferenceContext();
+ if (entryContext.isMultiRef()) {
+ throw new SAMException("Expecting a single reference or unmapped slice.");
+ }
+
+ if (entryContext.isMappedSingleRef()) {
+ final int reference = entryContext.getReferenceSequenceID();
+ if (reference != currentReference) {
+ // process any completed references
+ advanceToReference(reference);
+ }
+
+ // check that it advanced properly
+ if (reference != currentReference) {
+ throw new SAMException(String.format(
+ "Unexpected reference %s when constructing index for reference %d for slice",
+ reference, currentReference));
+ }
+ }
+
+ indexBuilder.recordBAIEntryIndexMetadata(baiEntry);
+
+ if (entryContext.isMappedSingleRef()) {
+ indexBuilder.processBAIEntry(baiEntry);
+ }
+ }
+
+ /**
+ * After all the slices have been processed, finish is called.
+ * Writes any final information and closes the output file.
+ */
+ @Override
+ public void finish() {
+ // process any remaining references
+ advanceToReference(numReferences);
+ outputWriter.writeNoCoordinateRecordCount(indexBuilder.getNoCoordinateRecordCount());
+ outputWriter.close();
+ }
+
+ /**
+ * write out any references between the currentReference and the nextReference
+ */
+ private void advanceToReference(final int nextReference) {
+ while (currentReference < nextReference) {
+ final BAMIndexContent content = indexBuilder.processCurrentReference();
+ outputWriter.writeReference(content);
+ currentReference++;
+ indexBuilder.startNewReference();
+ }
+ }
+
+ /**
+ * Generates a BAI index file from an input CRAM stream
+ *
+ * @param stream CRAM stream to index
+ * @param output File for output index file
+ * @param log optional {@link htsjdk.samtools.util.Log} to output progress
+ */
+ public static void createIndex(
+ final SeekableStream stream,
+ final File output,
+ final Log log,
+ final ValidationStringency validationStringency) {
+
+ final CramHeader cramHeader = CramIO.readCramHeader(stream);
+ final SAMFileHeader samFileHeader =
+ Container.readSAMFileHeaderContainer(cramHeader.getCRAMVersion(), stream, null);
+ if (samFileHeader.getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
+ throw new SAMException(String.format(
+ "Input must be coordinate sorted (found %s) to create an index.", samFileHeader.getSortOrder()));
+ }
+ final CRAMBAIIndexer indexer = new CRAMBAIIndexer(output, samFileHeader);
+
+ Container container = null;
+ final ProgressLogger progressLogger = new ProgressLogger(log, 1, "indexed", "slices");
+ do {
+ try {
+ container = new Container(cramHeader.getCRAMVersion(), stream, stream.position());
+ } catch (final IOException e) {
+ throw new RuntimeIOException("error getting stream position", e);
+ }
+ if (container == null || container.isEOF()) {
+ break;
+ }
+
+ indexer.processContainer(container, validationStringency);
+
+ if (null != log) {
+ String sequenceName;
+ final AlignmentContext alignmentContext = container.getAlignmentContext();
+ final ReferenceContext containerReferenceContext = alignmentContext.getReferenceContext();
+ switch (containerReferenceContext.getType()) {
+ case UNMAPPED_UNPLACED_TYPE:
+ sequenceName = "?";
+ break;
+ case MULTIPLE_REFERENCE_TYPE:
+ sequenceName = "???";
+ break;
+ default:
+ sequenceName = samFileHeader
+ .getSequence(containerReferenceContext.getReferenceSequenceID())
+ .getSequenceName();
+ break;
+ }
+ progressLogger.record(sequenceName, alignmentContext.getAlignmentStart());
+ }
+
+ } while (!container.isEOF());
+
+ indexer.finish();
+ }
+
+ /**
+ * Class for constructing BAM index files.
+ * One instance is used to construct an entire index.
+ * processAlignment is called for each alignment until a new reference is encountered, then
+ * processReference is called when all records for the reference have been processed.
+ */
+ private class CRAMBAIIndexBuilder {
+
+ private final SAMFileHeader bamHeader;
+
+ // the bins for the current reference
+ private Bin[] bins; // made only as big as needed for each reference
+ private int binsSeen = 0;
+
+ // linear index for the current reference
+ private final long[] index = new long[LinearIndex.MAX_LINEAR_INDEX_SIZE];
+ private int largestIndexSeen = -1;
+
+ // information in meta data
+ private final BAMIndexMetaData indexStats = new BAMIndexMetaData();
+
+ /**
+ * @param header SAMFileHeader used for reference name (in index stats) and for max bin number
+ */
+ private CRAMBAIIndexBuilder(final SAMFileHeader header) {
+ this.bamHeader = header;
+ }
+
+ private SAMFileHeader getBamHeader() {
+ return bamHeader;
+ }
+
+ private void recordBAIEntryIndexMetadata(final BAIEntry baiEntry) {
+ indexStats.recordMetaData(baiEntry);
+ }
+
+ private int computeIndexingBin(final BAIEntry baiEntry) {
+ // regionToBin has zero-based, half-open API
+ // final AlignmentContext sliceAlignmentContext = baiEntry.getAlignmentContext();
+ final int alignmentStart = baiEntry.getAlignmentStart() - 1;
+ int alignmentEnd = baiEntry.getAlignmentStart() + baiEntry.getAlignmentSpan() - 1;
+ if (alignmentEnd <= alignmentStart) {
+ // If alignment end cannot be determined (e.g. because this read is not really aligned),
+ // then treat this as a one base alignment for indexing purposes.
+ alignmentEnd = alignmentStart + 1;
+ }
+ return GenomicIndexUtil.regionToBin(alignmentStart, alignmentEnd);
+ }
+
+ /**
+ * Record any index information for a given CRAM slice
+ *
+ * Reads these Slice fields:
+ * sequenceId, alignmentStart, alignmentSpan, containerByteOffset, index
+ *
+ * //* @param slice CRAM slice, single ref only.
+ */
+ private void processBAIEntry(final BAIEntry baiEntry) {
+ final ReferenceContext sliceContext = baiEntry.getReferenceContext();
+ if (!sliceContext.isMappedSingleRef()) {
+ return; // do nothing for records without coordinates, but count them
+ }
+
+ // various checks
+ final int reference = sliceContext.getReferenceSequenceID();
+ if (reference != currentReference) {
+ throw new SAMException(String.format(
+ "Unexpected reference %s when constructing index for reference %d for slice",
+ reference, currentReference));
+ }
+
+ // process bins
+
+ final int binNum = computeIndexingBin(baiEntry);
+
+ // has the bins array been allocated? If not, do so
+ if (bins == null) {
+ final SAMSequenceRecord seq = bamHeader.getSequence(reference);
+ if (seq == null) {
+ bins = new Bin[GenomicIndexUtil.MAX_BINS + 1];
+ } else {
+ bins = new Bin[AbstractBAMFileIndex.getMaxBinNumberForSequenceLength(seq.getSequenceLength()) + 1];
+ }
+ }
+
+ // is there a bin already represented for this index? if not, add one
+ final Bin bin;
+ if (bins[binNum] != null) {
+ bin = bins[binNum];
+ } else {
+ bin = new Bin(reference, binNum);
+ bins[binNum] = bin;
+ binsSeen++;
+ }
+
+ // process chunks
+
+ final long chunkStart = (baiEntry.getContainerStartByteOffset() << 16) | baiEntry.getLandmarkIndex();
+ final long chunkEnd = ((baiEntry.getContainerStartByteOffset() << 16) | baiEntry.getLandmarkIndex()) + 1;
+
+ final Chunk newChunk = new Chunk(chunkStart, chunkEnd);
+
+ final List oldChunks = bin.getChunkList();
+ if (!bin.containsChunks()) {
+ bin.addInitialChunk(newChunk);
+
+ } else {
+ final Chunk lastChunk = bin.getLastChunk();
+
+ // Coalesce chunks that are in the same or adjacent file blocks.
+ // Similar to AbstractBAMFileIndex.optimizeChunkList,
+ // but no need to copy the list, no minimumOffset, and maintain bin.lastChunk
+ if (BlockCompressedFilePointerUtil.areInSameOrAdjacentBlocks(lastChunk.getChunkEnd(), chunkStart)) {
+ lastChunk.setChunkEnd(chunkEnd); // coalesced
+ } else {
+ oldChunks.add(newChunk);
+ bin.setLastChunk(newChunk);
+ }
+ }
+
+ // process linear index
+
+ // the smallest file offset that appears in the 16k window for this bin
+ final int alignmentStart = baiEntry.getAlignmentStart();
+ final int alignmentEnd = baiEntry.getAlignmentStart() + baiEntry.getAlignmentSpan();
+ int startWindow = LinearIndex.convertToLinearIndexOffset(alignmentStart); // the 16k window
+ final int endWindow;
+
+ if (alignmentEnd == SAMRecord.NO_ALIGNMENT_START) { // assume alignment uses one position
+ // Next line for C (samtools index) compatibility. Differs only when on a window boundary
+ startWindow = LinearIndex.convertToLinearIndexOffset(alignmentStart - 1);
+ endWindow = startWindow;
+ } else {
+ endWindow = LinearIndex.convertToLinearIndexOffset(alignmentEnd);
+ }
+
+ if (endWindow > largestIndexSeen) {
+ largestIndexSeen = endWindow;
+ }
+
+ // set linear index at every 16K window that this alignment overlaps
+ for (int win = startWindow; win <= endWindow; win++) {
+ if (index[win] == 0 || chunkStart < index[win]) {
+ index[win] = chunkStart;
+ }
+ }
+ }
+
+ /**
+ * Creates the BAMIndexContent for this reference.
+ * Requires all alignments of the reference have already been processed.
+ */
+ private BAMIndexContent processCurrentReference() {
+
+ // process bins
+ if (binsSeen == 0) {
+ return null; // no bins for this reference
+ }
+
+ // process chunks
+ // nothing needed
+
+ // process linear index
+ // linear index will only be as long as the largest index seen
+ final long[] newIndex =
+ new long[largestIndexSeen + 1]; // in java1.6 Arrays.copyOf(index, largestIndexSeen + 1);
+
+ // C (samtools index) also fills in intermediate 0's with values. This seems unnecessary, but safe
+ long lastNonZeroOffset = 0;
+ for (int i = 0; i <= largestIndexSeen; i++) {
+ if (index[i] == 0) {
+ index[i] = lastNonZeroOffset; // not necessary, but C (samtools index) does this
+ // note, if you remove the above line BAMIndexWriterTest.compareTextual and compareBinary will have
+ // to change
+ } else {
+ lastNonZeroOffset = index[i];
+ }
+ newIndex[i] = index[i];
+ }
+
+ final LinearIndex linearIndex = new LinearIndex(currentReference, 0, newIndex);
+
+ return new BAMIndexContent(currentReference, bins, binsSeen, indexStats, linearIndex);
+ }
+
+ /**
+ * @return the count of records with no coordinate positions
+ */
+ private long getNoCoordinateRecordCount() {
+ return indexStats.getNoCoordinateRecordCount();
+ }
+
+ /**
+ * reinitialize all data structures when the reference changes
+ */
+ private void startNewReference() {
+ bins = null;
+ if (binsSeen > 0) {
+ Arrays.fill(index, 0);
+ }
+ binsSeen = 0;
+ largestIndexSeen = -1;
+ indexStats.newReference();
+ }
+ }
+}
diff --git a/src/main/java/htsjdk/samtools/CRAMCRAIIndexer.java b/src/main/java/htsjdk/samtools/CRAMCRAIIndexer.java
index aaff4847fe..4b03425ee6 100644
--- a/src/main/java/htsjdk/samtools/CRAMCRAIIndexer.java
+++ b/src/main/java/htsjdk/samtools/CRAMCRAIIndexer.java
@@ -7,11 +7,10 @@
import htsjdk.samtools.cram.structure.*;
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.samtools.util.RuntimeIOException;
-
import java.io.BufferedOutputStream;
+import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
-import java.io.IOException;
import java.util.Collection;
import java.util.Scanner;
import java.util.zip.GZIPInputStream;
@@ -28,8 +27,8 @@
*/
public class CRAMCRAIIndexer implements CRAMIndexer {
- final private CRAIIndex craiIndex = new CRAIIndex();
- final private GZIPOutputStream os;
+ private final CRAIIndex craiIndex = new CRAIIndex();
+ private final GZIPOutputStream os;
/**
* Create a CRAMCRAIIndexer that writes to the given output stream.
@@ -43,8 +42,7 @@ public CRAMCRAIIndexer(final OutputStream os, final SAMFileHeader samHeader) {
}
try {
this.os = new GZIPOutputStream(new BufferedOutputStream(os));
- }
- catch (IOException e) {
+ } catch (IOException e) {
throw new RuntimeIOException("Error opening CRAI index output stream");
}
}
@@ -57,9 +55,7 @@ public CRAMCRAIIndexer(final OutputStream os, final SAMFileHeader samHeader) {
* @param samHeader SAMFileHeader - user to verify sort order
* @param entries the CRAI entries to index
*/
- public CRAMCRAIIndexer(final OutputStream os,
- final SAMFileHeader samHeader,
- final Collection entries) {
+ public CRAMCRAIIndexer(final OutputStream os, final SAMFileHeader samHeader, final Collection entries) {
this(os, samHeader);
craiIndex.addEntries(entries);
}
@@ -73,9 +69,7 @@ public void processContainer(final Container container) {
}
@Override
- public void processContainer(
- final Container container,
- final ValidationStringency validationStringency) {
+ public void processContainer(final Container container, final ValidationStringency validationStringency) {
processContainer(container);
}
@@ -88,8 +82,7 @@ public void finish() {
craiIndex.writeIndex(os);
os.flush();
os.close();
- }
- catch (IOException e) {
+ } catch (IOException e) {
throw new RuntimeIOException("Error writing CRAI index to output stream");
}
}
@@ -102,11 +95,11 @@ public void finish() {
*/
public static void writeIndex(final SeekableStream cramStream, OutputStream craiStream) {
final CramHeader cramHeader = CramIO.readCramHeader(cramStream);
- final SAMFileHeader samFileHeader = Container.readSAMFileHeaderContainer(cramHeader.getCRAMVersion(), cramStream, null);
+ final SAMFileHeader samFileHeader =
+ Container.readSAMFileHeaderContainer(cramHeader.getCRAMVersion(), cramStream, null);
if (samFileHeader.getSortOrder() != SAMFileHeader.SortOrder.coordinate) {
throw new SAMException(String.format(
- "Input must be coordinate sorted (found %s) to create an index.",
- samFileHeader.getSortOrder()));
+ "Input must be coordinate sorted (found %s) to create an index.", samFileHeader.getSortOrder()));
}
final CRAMCRAIIndexer indexer = new CRAMCRAIIndexer(craiStream, samFileHeader);
final CRAMVersion cramVersion = cramHeader.getCRAMVersion();
@@ -141,11 +134,9 @@ public static CRAIIndex readIndex(final InputStream is) {
final String line = scanner.nextLine();
craiIndex.addEntry(new CRAIEntry(line));
}
- }
- catch (IOException e) {
+ } catch (IOException e) {
throw new RuntimeIOException("Error reading CRAI index from output stream");
- }
- finally {
+ } finally {
if (null != scanner) {
scanner.close();
}
@@ -153,5 +144,4 @@ public static CRAIIndex readIndex(final InputStream is) {
return craiIndex;
}
-
-}
\ No newline at end of file
+}
diff --git a/src/main/java/htsjdk/samtools/CRAMContainerStreamWriter.java b/src/main/java/htsjdk/samtools/CRAMContainerStreamWriter.java
index 85d1f0f8c7..85db82e02a 100644
--- a/src/main/java/htsjdk/samtools/CRAMContainerStreamWriter.java
+++ b/src/main/java/htsjdk/samtools/CRAMContainerStreamWriter.java
@@ -6,7 +6,6 @@
import htsjdk.samtools.cram.ref.CRAMReferenceSource;
import htsjdk.samtools.cram.structure.*;
import htsjdk.samtools.util.RuntimeIOException;
-
import java.io.IOException;
import java.io.OutputStream;
@@ -39,13 +38,14 @@ public CRAMContainerStreamWriter(
final CRAMReferenceSource source,
final SAMFileHeader samFileHeader,
final String outputIdentifier) {
- this(recordOutputStream,
+ this(
+ recordOutputStream,
source,
samFileHeader,
outputIdentifier,
- indexOutputStream == null ?
- null :
- new CRAMBAIIndexer(indexOutputStream, samFileHeader)); // default to BAI index
+ indexOutputStream == null
+ ? null
+ : new CRAMBAIIndexer(indexOutputStream, samFileHeader)); // default to BAI index
}
/**
@@ -111,7 +111,8 @@ public void writeAlignment(final SAMRecord alignment) {
public void writeHeader(final SAMFileHeader requestedSAMFileHeader) {
final CramHeader cramHeader = new CramHeader(cramVersion, outputStreamIdentifier);
streamOffset = CramIO.writeCramHeader(cramHeader, outputStream);
- streamOffset += Container.writeSAMFileHeaderContainer(cramHeader.getCRAMVersion(), requestedSAMFileHeader, outputStream);
+ streamOffset += Container.writeSAMFileHeaderContainer(
+ cramHeader.getCRAMVersion(), requestedSAMFileHeader, outputStream);
}
/**
@@ -150,8 +151,7 @@ protected void writeContainer(final Container container) {
if (cramIndexer != null) {
// using silent validation here because the reads have been through validation already or
// they have been generated somehow through the htsjdk
- cramIndexer.processContainer(container, ValidationStringency.SILENT);
+ cramIndexer.processContainer(container, ValidationStringency.SILENT);
}
}
-
}
diff --git a/src/main/java/htsjdk/samtools/CRAMFileReader.java b/src/main/java/htsjdk/samtools/CRAMFileReader.java
index 126b4b0829..730aa3f504 100644
--- a/src/main/java/htsjdk/samtools/CRAMFileReader.java
+++ b/src/main/java/htsjdk/samtools/CRAMFileReader.java
@@ -23,7 +23,6 @@
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.samtools.util.*;
import htsjdk.utils.ValidationUtils;
-
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
@@ -48,7 +47,7 @@ public class CRAMFileReader extends SamReader.ReaderImplementation implements Sa
private ValidationStringency validationStringency;
- private final static Log log = Log.getInstance(CRAMFileReader.class);
+ private static final Log log = Log.getInstance(CRAMFileReader.class);
/**
* Create a CRAMFileReader from either a file or input stream using the reference source returned by
@@ -76,11 +75,10 @@ public CRAMFileReader(final File cramFile, final InputStream inputStream) {
* @throws IllegalArgumentException if the {@code cramFile} and the {@code inputStream} are both null
* or if the {@code CRAMReferenceSource} is null
*/
- public CRAMFileReader(final File cramFile,
- final InputStream inputStream,
- final CRAMReferenceSource referenceSource) {
- ValidationUtils.validateArg(cramFile != null || inputStream != null,
- "Either file or input stream is required.");
+ public CRAMFileReader(
+ final File cramFile, final InputStream inputStream, final CRAMReferenceSource referenceSource) {
+ ValidationUtils.validateArg(
+ cramFile != null || inputStream != null, "Either file or input stream is required.");
this.cramFile = cramFile;
this.inputStream = new BufferedInputStream(inputStream);
@@ -101,10 +99,8 @@ public CRAMFileReader(final File cramFile,
* reference sequences. May not be null.
* @throws IllegalArgumentException if the {@code cramFile} or the {@code CRAMReferenceSource} is null
*/
- public CRAMFileReader(final File cramFile,
- final File indexFile,
- final CRAMReferenceSource referenceSource) {
- ValidationUtils.nonNull(cramFile,"File is required.");
+ public CRAMFileReader(final File cramFile, final File indexFile, final CRAMReferenceSource referenceSource) {
+ ValidationUtils.nonNull(cramFile, "File is required.");
this.cramFile = cramFile;
mIndexFile = findIndexForFile(indexFile, cramFile);
@@ -122,7 +118,7 @@ public CRAMFileReader(final File cramFile,
* @throws IllegalArgumentException if the {@code cramFile} or the {@code CRAMReferenceSource} is null
*/
public CRAMFileReader(final File cramFile, final CRAMReferenceSource referenceSource) {
- ValidationUtils.nonNull(cramFile,"File is required.");
+ ValidationUtils.nonNull(cramFile, "File is required.");
this.cramFile = cramFile;
this.referenceSource = referenceSource;
@@ -143,10 +139,12 @@ public CRAMFileReader(final File cramFile, final CRAMReferenceSource referenceSo
*
* @throws IllegalArgumentException if the {@code inputStream} or the {@code CRAMReferenceSource} is null
*/
- public CRAMFileReader(final InputStream inputStream,
- final SeekableStream indexInputStream,
- final CRAMReferenceSource referenceSource,
- final ValidationStringency validationStringency) throws IOException {
+ public CRAMFileReader(
+ final InputStream inputStream,
+ final SeekableStream indexInputStream,
+ final CRAMReferenceSource referenceSource,
+ final ValidationStringency validationStringency)
+ throws IOException {
ValidationUtils.nonNull(inputStream, "Input stream can not be null for CRAM reader");
this.referenceSource = referenceSource;
initWithStreams(inputStream, indexInputStream, validationStringency);
@@ -164,11 +162,17 @@ public CRAMFileReader(final InputStream inputStream,
*
* @throws IllegalArgumentException if the {@code inputStream} or the {@code CRAMReferenceSource} is null
*/
- public CRAMFileReader(final InputStream stream,
- final File indexFile,
- final CRAMReferenceSource referenceSource,
- final ValidationStringency validationStringency) throws IOException {
- this(stream, indexFile == null ? null : new SeekableFileStream(indexFile), referenceSource, validationStringency);
+ public CRAMFileReader(
+ final InputStream stream,
+ final File indexFile,
+ final CRAMReferenceSource referenceSource,
+ final ValidationStringency validationStringency)
+ throws IOException {
+ this(
+ stream,
+ indexFile == null ? null : new SeekableFileStream(indexFile),
+ referenceSource,
+ validationStringency);
}
/**
@@ -183,8 +187,12 @@ public CRAMFileReader(final InputStream stream,
*
* @throws IllegalArgumentException if the {@code cramFile} or the {@code CRAMReferenceSource} is null
*/
- public CRAMFileReader(final File cramFile, final File indexFile, final CRAMReferenceSource referenceSource,
- final ValidationStringency validationStringency) throws IOException {
+ public CRAMFileReader(
+ final File cramFile,
+ final File indexFile,
+ final CRAMReferenceSource referenceSource,
+ final ValidationStringency validationStringency)
+ throws IOException {
ValidationUtils.nonNull(cramFile, "Input file can not be null for CRAM reader");
this.cramFile = cramFile;
@@ -194,17 +202,21 @@ public CRAMFileReader(final File cramFile, final File indexFile, final CRAMRefer
initWithStreams(new BufferedInputStream(new FileInputStream(cramFile)), indexStream, validationStringency);
}
- private void initWithStreams(final InputStream inputStream, final SeekableStream indexInputStream,
- final ValidationStringency validationStringency) throws IOException {
+ private void initWithStreams(
+ final InputStream inputStream,
+ final SeekableStream indexInputStream,
+ final ValidationStringency validationStringency)
+ throws IOException {
this.inputStream = inputStream;
this.validationStringency = validationStringency;
iterator = new CRAMIterator(inputStream, referenceSource, validationStringency);
if (indexInputStream != null) {
- SeekableStream baiStream = SamIndexes.asBaiSeekableStreamOrNull(indexInputStream, iterator.getSAMFileHeader().getSequenceDictionary());
- if (null != baiStream) {
- mIndex = new CachingBAMFileIndex(baiStream, iterator.getSAMFileHeader().getSequenceDictionary());
- }
- else {
+ SeekableStream baiStream = SamIndexes.asBaiSeekableStreamOrNull(
+ indexInputStream, iterator.getSAMFileHeader().getSequenceDictionary());
+ if (null != baiStream) {
+ mIndex = new CachingBAMFileIndex(
+ baiStream, iterator.getSAMFileHeader().getSequenceDictionary());
+ } else {
throw new IllegalArgumentException("CRAM index must be a BAI or CRAI stream");
}
}
@@ -213,8 +225,8 @@ private void initWithStreams(final InputStream inputStream, final SeekableStream
private File findIndexForFile(File indexFile, final File cramFile) {
indexFile = indexFile == null ? SamFiles.findIndex(cramFile) : indexFile;
if (indexFile != null && indexFile.lastModified() < cramFile.lastModified()) {
- log.warn("CRAM index file " + indexFile.getAbsolutePath() +
- " is older than CRAM " + cramFile.getAbsolutePath());
+ log.warn("CRAM index file " + indexFile.getAbsolutePath() + " is older than CRAM "
+ + cramFile.getAbsolutePath());
}
return indexFile;
}
@@ -237,8 +249,7 @@ void enableCrcChecking(final boolean enabled) {
}
@Override
- void setSAMRecordFactory(final SAMRecordFactory factory) {
- }
+ void setSAMRecordFactory(final SAMRecordFactory factory) {}
@Override
public boolean hasIndex() {
@@ -253,9 +264,9 @@ public BAMIndex getIndex() {
if (mIndex == null) {
final SAMSequenceDictionary dictionary = getFileHeader().getSequenceDictionary();
if (mIndexFile.getName().endsWith(FileExtensions.BAI_INDEX)) {
- mIndex = mEnableIndexCaching ?
- new CachingBAMFileIndex(mIndexFile, dictionary, mEnableIndexMemoryMapping) :
- new DiskBasedBAMFileIndex(mIndexFile, dictionary, mEnableIndexMemoryMapping);
+ mIndex = mEnableIndexCaching
+ ? new CachingBAMFileIndex(mIndexFile, dictionary, mEnableIndexMemoryMapping)
+ : new DiskBasedBAMFileIndex(mIndexFile, dictionary, mEnableIndexMemoryMapping);
return mIndex;
}
@@ -270,18 +281,22 @@ public BAMIndex getIndex() {
throw new RuntimeException(e);
}
- mIndex = mEnableIndexCaching ?
- new CachingBAMFileIndex(baiStream, getFileHeader().getSequenceDictionary()) :
- new DiskBasedBAMFileIndex(baiStream, getFileHeader().getSequenceDictionary());
+ mIndex = mEnableIndexCaching
+ ? new CachingBAMFileIndex(baiStream, getFileHeader().getSequenceDictionary())
+ : new DiskBasedBAMFileIndex(baiStream, getFileHeader().getSequenceDictionary());
}
return mIndex;
}
@Override
- public boolean hasBrowseableIndex() { return false; }
+ public boolean hasBrowseableIndex() {
+ return false;
+ }
@Override
- public BrowseableBAMIndex getBrowseableIndex() { return null; }
+ public BrowseableBAMIndex getBrowseableIndex() {
+ return null;
+ }
@Override
public SAMRecordIterator iterator(final SAMFileSpan fileSpan) {
@@ -297,7 +312,9 @@ public SAMRecordIterator iterator(final SAMFileSpan fileSpan) {
}
@Override
- public SAMFileHeader getFileHeader() { return iterator.getSAMFileHeader(); }
+ public SAMFileHeader getFileHeader() {
+ return iterator.getSAMFileHeader();
+ }
@Override
public SAMRecordIterator getIterator() {
@@ -306,7 +323,8 @@ public SAMRecordIterator getIterator() {
}
try {
if (cramFile != null) {
- iterator = new CRAMIterator(new BufferedInputStream(new FileInputStream(cramFile)), referenceSource, validationStringency);
+ iterator = new CRAMIterator(
+ new BufferedInputStream(new FileInputStream(cramFile)), referenceSource, validationStringency);
} else {
iterator = new CRAMIterator(inputStream, referenceSource, validationStringency);
}
@@ -348,8 +366,7 @@ public void remove() {
}
@Override
- public void close() {
- }
+ public void close() {}
@Override
public SAMRecordIterator assertSorted(final SortOrder sortOrder) {
@@ -358,8 +375,7 @@ public SAMRecordIterator assertSorted(final SortOrder sortOrder) {
};
@Override
- public CloseableIterator queryAlignmentStart(final String sequence,
- final int start) {
+ public CloseableIterator queryAlignmentStart(final String sequence, final int start) {
final SAMFileHeader fileHeader = getFileHeader();
final int referenceIndex = fileHeader.getSequenceIndex(sequence);
// alignment start requires a filtering iterator to ensure that records in the
@@ -381,7 +397,8 @@ public CloseableIterator queryUnmapped() {
}
boolean atAlignments;
do {
- atAlignments = iterator.advanceToAlignmentInContainer(SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX, SAMRecord.NO_ALIGNMENT_START);
+ atAlignments = iterator.advanceToAlignmentInContainer(
+ SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX, SAMRecord.NO_ALIGNMENT_START);
} while (!atAlignments && iterator.hasNext());
} catch (final IOException e) {
throw new RuntimeEOFException(e);
@@ -429,19 +446,29 @@ public DeferredCloseSeekableStream(final SeekableStream delegateStream) {
}
}
- public SeekableStream getDelegate() { return delegateStream; }
+ public SeekableStream getDelegate() {
+ return delegateStream;
+ }
@Override
- public long length() { return delegateStream.length(); }
+ public long length() {
+ return delegateStream.length();
+ }
@Override
- public long position() throws IOException { return delegateStream.position(); }
+ public long position() throws IOException {
+ return delegateStream.position();
+ }
@Override
- public void seek(long position) throws IOException { delegateStream.seek(position); }
+ public void seek(long position) throws IOException {
+ delegateStream.seek(position);
+ }
@Override
- public int read() throws IOException { return delegateStream.read(); }
+ public int read() throws IOException {
+ return delegateStream.read();
+ }
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
@@ -455,10 +482,14 @@ public void close() throws IOException {
}
@Override
- public boolean eof() throws IOException { return delegateStream.eof(); }
+ public boolean eof() throws IOException {
+ return delegateStream.eof();
+ }
@Override
- public String getSource() { return delegateStream.getSource(); }
+ public String getSource() {
+ return delegateStream.getSource();
+ }
}
@Override
@@ -486,8 +517,7 @@ public ValidationStringency getValidationStringency() {
}
@Override
- public CloseableIterator query(final QueryInterval[] intervals,
- final boolean contained) {
+ public CloseableIterator query(final QueryInterval[] intervals, final boolean contained) {
return new CRAMIntervalIterator(intervals, contained);
}
@@ -511,16 +541,16 @@ void enableFileSource(final SamReader reader, final boolean enabled) {
* @param filePointers file pointer pairs corresponding to chunk boundaries for the
* intervals
*/
- public CloseableIterator createIndexIterator(final QueryInterval[] intervals,
- final boolean contained,
- final long[] filePointers) {
+ public CloseableIterator createIndexIterator(
+ final QueryInterval[] intervals, final boolean contained, final long[] filePointers) {
return new CRAMIntervalIterator(intervals, contained, filePointers);
}
// convert queries -> merged BAMFileSpan -> coordinate array
private static long[] coordinatesFromQueryIntervals(BAMIndex index, QueryInterval[] queries) {
ArrayList spanList = new ArrayList<>(1);
- Arrays.asList(queries).forEach(qi -> spanList.add(index.getSpanOverlapping(qi.referenceIndex, qi.start, qi.end)));
+ Arrays.asList(queries)
+ .forEach(qi -> spanList.add(index.getSpanOverlapping(qi.referenceIndex, qi.start, qi.end)));
BAMFileSpan spanArray[] = new BAMFileSpan[spanList.size()];
for (int i = 0; i < spanList.size(); i++) {
spanArray[i] = spanList.get(i);
@@ -561,8 +591,7 @@ protected void initializeIterator(final QueryInterval[] queryIntervals, final lo
referenceSource,
validationStringency,
queryIntervals,
- coordinates
- );
+ coordinates);
getNextRecord(); // advance to the first record that matches the filter criteria
}
}
@@ -630,7 +659,7 @@ private class CRAMAlignmentStartIterator extends CRAMIntervalIteratorBase {
final BAMStartingAtIteratorFilter startingAtIteratorFilter;
public CRAMAlignmentStartIterator(final int referenceIndex, final int start) {
- super(new QueryInterval[]{new QueryInterval(referenceIndex, start, -1)}, true);
+ super(new QueryInterval[] {new QueryInterval(referenceIndex, start, -1)}, true);
startingAtIteratorFilter = new BAMStartingAtIteratorFilter(referenceIndex, start);
initializeIterator(intervals, coordinatesFromQueryIntervals(getIndex(), intervals));
}
diff --git a/src/main/java/htsjdk/samtools/CRAMFileWriter.java b/src/main/java/htsjdk/samtools/CRAMFileWriter.java
index 15c5c20a84..5342a377d2 100644
--- a/src/main/java/htsjdk/samtools/CRAMFileWriter.java
+++ b/src/main/java/htsjdk/samtools/CRAMFileWriter.java
@@ -19,7 +19,6 @@
import htsjdk.samtools.cram.structure.CRAMEncodingStrategy;
import htsjdk.samtools.util.BufferedLineReader;
import htsjdk.samtools.util.Log;
-
import java.io.OutputStream;
public class CRAMFileWriter extends SAMFileWriterImpl {
@@ -44,8 +43,7 @@ public CRAMFileWriter(
final OutputStream outputStream,
final CRAMReferenceSource referenceSource,
final SAMFileHeader samFileHeader,
- final String fileName)
- {
+ final String fileName) {
this(outputStream, null, referenceSource, samFileHeader, fileName); // defaults to presorted == true
}
@@ -66,8 +64,7 @@ public CRAMFileWriter(
final OutputStream indexOS,
final CRAMReferenceSource referenceSource,
final SAMFileHeader samFileHeader,
- final String fileName)
- {
+ final String fileName) {
this(outputStream, indexOS, true, referenceSource, samFileHeader, fileName); // defaults to presorted==true
}
@@ -83,24 +80,29 @@ public CRAMFileWriter(
*
* @throws IllegalArgumentException if the {@code outputStream}, {@code referenceSource} or {@code samFileHeader} are null
*/
- public CRAMFileWriter(final OutputStream outputStream, final OutputStream indexOS, final boolean presorted,
- final CRAMReferenceSource referenceSource, final SAMFileHeader samFileHeader, final String fileName) {
- this( new CRAMEncodingStrategy(), outputStream, indexOS, presorted, referenceSource, samFileHeader, fileName);
+ public CRAMFileWriter(
+ final OutputStream outputStream,
+ final OutputStream indexOS,
+ final boolean presorted,
+ final CRAMReferenceSource referenceSource,
+ final SAMFileHeader samFileHeader,
+ final String fileName) {
+ this(new CRAMEncodingStrategy(), outputStream, indexOS, presorted, referenceSource, samFileHeader, fileName);
}
/**
- * Create a CRAMFileWriter and optional index on output streams.
- *
- * @param encodingStrategy encoding strategy to use when writing
- * @param outputStream where to write the output. Can not be null.
- * @param indexOS where to write the output index. Can be null if no index is required.
- * @param presorted if true records written to this writer must already be sorted in the order specified by the header
- * @param referenceSource reference source
- * @param samFileHeader {@link SAMFileHeader} to be used. Can not be null. Sort order is determined by the sortOrder property of this arg.
- * @param fileName used for display in error message display
- *
- * @throws IllegalArgumentException if the {@code outputStream}, {@code referenceSource} or {@code samFileHeader} are null
- */
+ * Create a CRAMFileWriter and optional index on output streams.
+ *
+ * @param encodingStrategy encoding strategy to use when writing
+ * @param outputStream where to write the output. Can not be null.
+ * @param indexOS where to write the output index. Can be null if no index is required.
+ * @param presorted if true records written to this writer must already be sorted in the order specified by the header
+ * @param referenceSource reference source
+ * @param samFileHeader {@link SAMFileHeader} to be used. Can not be null. Sort order is determined by the sortOrder property of this arg.
+ * @param fileName used for display in error message display
+ *
+ * @throws IllegalArgumentException if the {@code outputStream}, {@code referenceSource} or {@code samFileHeader} are null
+ */
public CRAMFileWriter(
final CRAMEncodingStrategy encodingStrategy,
final OutputStream outputStream,
@@ -142,7 +144,8 @@ protected void writeAlignment(final SAMRecord alignment) {
@Override
protected void writeHeader(final String textHeader) {
- writeHeader(new SAMTextHeaderCodec().decode(BufferedLineReader.fromString(textHeader),fileName != null ? fileName : null));
+ writeHeader(new SAMTextHeaderCodec()
+ .decode(BufferedLineReader.fromString(textHeader), fileName != null ? fileName : null));
}
@Override
@@ -164,5 +167,4 @@ protected void finish() {
protected String getFilename() {
return fileName;
}
-
}
diff --git a/src/main/java/htsjdk/samtools/CRAMIndexer.java b/src/main/java/htsjdk/samtools/CRAMIndexer.java
index 5e332a87ea..f58a2d8ce8 100644
--- a/src/main/java/htsjdk/samtools/CRAMIndexer.java
+++ b/src/main/java/htsjdk/samtools/CRAMIndexer.java
@@ -1,6 +1,5 @@
package htsjdk.samtools;
-import htsjdk.samtools.cram.structure.CompressorCache;
import htsjdk.samtools.cram.structure.Container;
/**
diff --git a/src/main/java/htsjdk/samtools/CRAMIterator.java b/src/main/java/htsjdk/samtools/CRAMIterator.java
index 730c52b16b..2dc693c879 100644
--- a/src/main/java/htsjdk/samtools/CRAMIterator.java
+++ b/src/main/java/htsjdk/samtools/CRAMIterator.java
@@ -23,13 +23,11 @@
import htsjdk.samtools.cram.ref.CRAMReferenceSource;
import htsjdk.samtools.cram.structure.*;
import htsjdk.samtools.seekablestream.SeekableStream;
-
+import htsjdk.samtools.util.RuntimeIOException;
import java.io.Closeable;
import java.io.InputStream;
import java.util.*;
-import htsjdk.samtools.util.RuntimeIOException;
-
public class CRAMIterator implements SAMRecordIterator, Closeable {
private final CountingInputStream countingInputStream;
private final CramContainerIterator containerIterator;
@@ -54,11 +52,13 @@ public class CRAMIterator implements SAMRecordIterator, Closeable {
* (for identification by the validator which records are invalid)
*/
private long samRecordIndex;
+
private Iterator samRecordIterator = Collections.EMPTY_LIST.iterator();
- public CRAMIterator(final InputStream inputStream,
- final CRAMReferenceSource referenceSource,
- final ValidationStringency validationStringency) {
+ public CRAMIterator(
+ final InputStream inputStream,
+ final CRAMReferenceSource referenceSource,
+ final ValidationStringency validationStringency) {
this.countingInputStream = new CountingInputStream(inputStream);
this.containerIterator = new CramContainerIterator(this.countingInputStream);
@@ -71,11 +71,12 @@ public CRAMIterator(final InputStream inputStream,
this.queryIntervals = null;
}
- public CRAMIterator(final SeekableStream seekableStream,
- final CRAMReferenceSource referenceSource,
- final ValidationStringency validationStringency,
- final QueryInterval[] queryIntervals,
- final long[] coordinates) {
+ public CRAMIterator(
+ final SeekableStream seekableStream,
+ final CRAMReferenceSource referenceSource,
+ final ValidationStringency validationStringency,
+ final QueryInterval[] queryIntervals,
+ final long[] coordinates) {
this.countingInputStream = new CountingInputStream(seekableStream);
this.containerIterator = CramSpanContainerIterator.fromFileSpan(seekableStream, coordinates);
@@ -110,10 +111,7 @@ private BAMIteratorFilter.FilteringIteratorState nextContainer() {
if (containerMatchesQuery(container)) {
samRecords = container.getSAMRecords(
- validationStringency,
- cramReferenceRegion,
- compressorCache,
- getSAMFileHeader());
+ validationStringency, cramReferenceRegion, compressorCache, getSAMFileHeader());
samRecordIterator = samRecords.iterator();
// A container may match the query but produce no records (e.g. a container with
// only a compression header and no slices). Skip to the next container in that case.
@@ -132,21 +130,25 @@ private boolean containerMatchesQuery(final Container container) {
// binary search our query intervals to see if the alignment span of this container
// overlaps any query - it doesn't matter which one, we only care whether or not there is a match
final AlignmentContext alignmentContext = container.getAlignmentContext();
- return (!alignmentContext.getReferenceContext().isMappedSingleRef() ||
- Arrays.binarySearch(
- queryIntervals,
- new QueryInterval(
- alignmentContext.getReferenceContext().getReferenceContextID(),
- alignmentContext.getAlignmentStart(),
- alignmentContext.getAlignmentStart() + alignmentContext.getAlignmentSpan() - 1
- ),
- overlapsContainerSpan) >= 0);
+ return (!alignmentContext.getReferenceContext().isMappedSingleRef()
+ || Arrays.binarySearch(
+ queryIntervals,
+ new QueryInterval(
+ alignmentContext
+ .getReferenceContext()
+ .getReferenceContextID(),
+ alignmentContext.getAlignmentStart(),
+ alignmentContext.getAlignmentStart()
+ + alignmentContext.getAlignmentSpan()
+ - 1),
+ overlapsContainerSpan)
+ >= 0);
}
}
- //TODO: this should filter at the slice level!
- //we don't actually care which QueryInterval overlaps with the container; we just want to know if there is one...
- private final static Comparator overlapsContainerSpan = (queryInterval, containerInterval) -> {
+ // TODO: this should filter at the slice level!
+ // we don't actually care which QueryInterval overlaps with the container; we just want to know if there is one...
+ private static final Comparator overlapsContainerSpan = (queryInterval, containerInterval) -> {
int comp = queryInterval.referenceIndex - containerInterval.referenceIndex;
if (comp != 0) {
return comp;
@@ -154,9 +156,7 @@ private boolean containerMatchesQuery(final Container container) {
if (queryInterval.end <= 0) {
// our query interval specifies a symbolic end, so call it a match if the container span
// overlaps the start of the queryInterval
- return containerInterval.end <= queryInterval.start ?
- -1 :
- 0;
+ return containerInterval.end <= queryInterval.start ? -1 : 0;
} else if (containerInterval.overlaps(queryInterval)) {
return 0; // there is overlap so call it a match
}
@@ -169,7 +169,7 @@ private boolean containerMatchesQuery(final Container container) {
* @param refIndex reference sequence index
* @param pos alignment start to skip to
*/
- //TODO: this should first select the correct slice so we don't decode all slices unnecessarily
+ // TODO: this should first select the correct slice so we don't decode all slices unnecessarily
public boolean advanceToAlignmentInContainer(final int refIndex, final int pos) {
if (!hasNext()) return false;
int i = 0;
@@ -204,7 +204,7 @@ public boolean hasNext() {
if (!samRecordIterator.hasNext()) {
BAMIteratorFilter.FilteringIteratorState nextContainerPasses =
BAMIteratorFilter.FilteringIteratorState.CONTINUE_ITERATION;
- while (nextContainerPasses == BAMIteratorFilter.FilteringIteratorState.CONTINUE_ITERATION){
+ while (nextContainerPasses == BAMIteratorFilter.FilteringIteratorState.CONTINUE_ITERATION) {
nextContainerPasses = nextContainer();
}
return nextContainerPasses == BAMIteratorFilter.FilteringIteratorState.MATCHES_FILTER;
@@ -238,7 +238,8 @@ public void close() {
if (countingInputStream != null) {
countingInputStream.close();
}
- } catch (final RuntimeIOException e) { }
+ } catch (final RuntimeIOException e) {
+ }
}
public long getFirstContainerOffset() {
@@ -273,5 +274,4 @@ public void setFileSource(final SamReader mReader) {
public SAMFileHeader getSAMFileHeader() {
return samFileHeader;
}
-
}
diff --git a/src/main/java/htsjdk/samtools/CSIIndex.java b/src/main/java/htsjdk/samtools/CSIIndex.java
index 706eb450f8..4e34900e54 100644
--- a/src/main/java/htsjdk/samtools/CSIIndex.java
+++ b/src/main/java/htsjdk/samtools/CSIIndex.java
@@ -3,7 +3,6 @@
import htsjdk.samtools.seekablestream.SeekablePathStream;
import htsjdk.samtools.seekablestream.SeekableStream;
import htsjdk.samtools.util.RuntimeIOException;
-
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
@@ -23,6 +22,7 @@ public class CSIIndex extends AbstractBAMFileIndex implements BrowseableBAMIndex
* the superclass constructor.
*/
private int binDepth;
+
private int minShift;
private int maxBins;
private int maxSpan;
@@ -33,7 +33,6 @@ public class CSIIndex extends AbstractBAMFileIndex implements BrowseableBAMIndex
/**
* Constructors
*/
-
public CSIIndex(final SeekableStream stream, final SAMSequenceDictionary dictionary) {
this(IndexFileBufferFactory.getBuffer(stream), stream.getSource(), dictionary);
}
@@ -46,7 +45,8 @@ public CSIIndex(final File file, boolean enableMemoryMapping, final SAMSequenceD
this(IndexFileBufferFactory.getBuffer(file, enableMemoryMapping), file.getName(), dictionary);
}
- private CSIIndex(final IndexFileBuffer indexFileBuffer, final String source, final SAMSequenceDictionary dictionary) {
+ private CSIIndex(
+ final IndexFileBuffer indexFileBuffer, final String source, final SAMSequenceDictionary dictionary) {
super(indexFileBuffer, source, dictionary);
}
@@ -62,7 +62,9 @@ public int getBinDepth() {
return binDepth;
}
- private void setBinDepth(int binDepth) { this.binDepth = binDepth; }
+ private void setBinDepth(int binDepth) {
+ this.binDepth = binDepth;
+ }
/**
* 2^(min shift) is the smallest width of a bin
@@ -79,24 +81,34 @@ public int getMaxBins() {
return maxBins;
}
- private void setMaxBins(int binDepth) { this.maxBins = ((1<<3*binDepth) - 1)/7; }
+ private void setMaxBins(int binDepth) {
+ this.maxBins = ((1 << 3 * binDepth) - 1) / 7;
+ }
public int getMaxSpan() {
return maxSpan;
}
private void setMaxSpan(int binDepth, int minShift) {
- this.maxSpan = 1<<(minShift + 3*(binDepth - 1));
+ this.maxSpan = 1 << (minShift + 3 * (binDepth - 1));
}
- public byte[] getAuxData() { return auxData; }
+ public byte[] getAuxData() {
+ return auxData;
+ }
- private void setAuxData(byte[] auxData) { this.auxData = auxData; }
+ private void setAuxData(byte[] auxData) {
+ this.auxData = auxData;
+ }
@Override
- public int getNumberOfReferences() { return nReferences; }
+ public int getNumberOfReferences() {
+ return nReferences;
+ }
- private void setNumberOfReferences(int nReferences) { this.nReferences = nReferences; }
+ private void setNumberOfReferences(int nReferences) {
+ this.nReferences = nReferences;
+ }
/**
* Computes the number of bins on the given level.
@@ -106,9 +118,10 @@ private void setMaxSpan(int binDepth, int minShift) {
@Override
public int getLevelSize(final int levelNumber) {
if (levelNumber >= getBinDepth()) {
- throw new SAMException("Level number (" + levelNumber + ") is greater than or equal to maximum (" + getBinDepth() + ").");
+ throw new SAMException(
+ "Level number (" + levelNumber + ") is greater than or equal to maximum (" + getBinDepth() + ").");
}
- return 1<<3*(levelNumber);
+ return 1 << 3 * (levelNumber);
}
/**
@@ -117,46 +130,47 @@ public int getLevelSize(final int levelNumber) {
*/
public int getFirstBinInLevelForCSI(final int levelNumber) {
if (levelNumber >= getBinDepth()) {
- throw new SAMException("Level number (" + levelNumber + ") is greater than or equal to maximum (" + getBinDepth() + ").");
+ throw new SAMException(
+ "Level number (" + levelNumber + ") is greater than or equal to maximum (" + getBinDepth() + ").");
}
- return ((1<<3*levelNumber) - 1)/7;
+ return ((1 << 3 * levelNumber) - 1) / 7;
}
@Override
public int getLevelForBin(Bin bin) {
- if(bin == null || bin.getBinNumber() > getMaxBins()) {
- throw new SAMException("Tried to get level for invalid bin: " + bin);
+ if (bin == null || bin.getBinNumber() > getMaxBins()) {
+ throw new SAMException("Tried to get level for invalid bin: " + bin);
}
- for (int i = getBinDepth()-1; i > -1 ; i--) {
- if (bin.getBinNumber() >= getFirstBinInLevelForCSI(i)) {
- return i;
- }
+ for (int i = getBinDepth() - 1; i > -1; i--) {
+ if (bin.getBinNumber() >= getFirstBinInLevelForCSI(i)) {
+ return i;
+ }
}
throw new SAMException("Unable to find correct level for bin: " + bin);
}
@Override
public int getFirstLocusInBin(Bin bin) {
- if(bin == null || bin.getBinNumber() > getMaxBins()) {
+ if (bin == null || bin.getBinNumber() > getMaxBins()) {
throw new SAMException("Tried to get first locus for invalid bin: " + bin);
}
int level = getLevelForBin(bin);
int firstBinOnLevel = getFirstBinInLevelForCSI(level);
int levelSize = getLevelSize(level);
- return (bin.getBinNumber() - firstBinOnLevel)*(getMaxSpan()/levelSize) + 1;
+ return (bin.getBinNumber() - firstBinOnLevel) * (getMaxSpan() / levelSize) + 1;
}
@Override
public int getLastLocusInBin(Bin bin) {
- if(bin == null || bin.getBinNumber() > getMaxBins()) {
+ if (bin == null || bin.getBinNumber() > getMaxBins()) {
throw new SAMException("Tried to get last locus for invalid bin: " + bin);
}
int level = getLevelForBin(bin);
int firstBinOnLevel = getFirstBinInLevelForCSI(level);
int levelSize = getLevelSize(level);
- return (bin.getBinNumber() - firstBinOnLevel + 1)*(getMaxSpan()/levelSize);
+ return (bin.getBinNumber() - firstBinOnLevel + 1) * (getMaxSpan() / levelSize);
}
@Override
@@ -165,7 +179,7 @@ public BinList getBinsOverlapping(int referenceIndex, int startPos, int endPos)
if (regionBins == null) {
return null;
}
- return new BinList(referenceIndex,regionBins);
+ return new BinList(referenceIndex, regionBins);
}
@Override
@@ -175,28 +189,27 @@ public BAMFileSpan getSpanOverlapping(int referenceIndex, int startPos, int endP
long minimumOffset = 0L;
Bin targetBin;
- if(queryResults == null) {
+ if (queryResults == null) {
return null;
}
/** Compute 'minimumOffset' by searching the lowest level bin containing 'startPos'.
- If the computed bin is not in the index, try the next bin to the left, belonging
- to the same parent. If it is the first sibling bin, try the parent bin.
+ * If the computed bin is not in the index, try the next bin to the left, belonging
+ * to the same parent. If it is the first sibling bin, try the parent bin.
*/
-
do {
int firstBinNumber;
targetBin = queryResults.getBins().getBin(initialBinNumber);
if (targetBin != null) {
break;
}
- firstBinNumber = (getParentBinNumber(initialBinNumber)<<3) + 1;
+ firstBinNumber = (getParentBinNumber(initialBinNumber) << 3) + 1;
if (initialBinNumber > firstBinNumber) {
initialBinNumber--;
} else {
initialBinNumber = getParentBinNumber(initialBinNumber);
}
- } while(initialBinNumber != 0);
+ } while (initialBinNumber != 0);
if (initialBinNumber == 0) {
targetBin = queryResults.getBins().getBin(initialBinNumber);
@@ -207,7 +220,7 @@ public BAMFileSpan getSpanOverlapping(int referenceIndex, int startPos, int endP
}
List chunkList = new ArrayList();
- for(final Chunk chunk: queryResults.getAllChunks()) {
+ for (final Chunk chunk : queryResults.getAllChunks()) {
chunkList.add(chunk.clone());
}
@@ -217,42 +230,41 @@ public BAMFileSpan getSpanOverlapping(int referenceIndex, int startPos, int endP
@Override
public BAMFileSpan getSpanOverlapping(final Bin bin) {
- if(bin == null) {
+ if (bin == null) {
return null;
}
final int referenceSequence = bin.getReferenceSequence();
final BAMIndexContent queryResults = getQueryResults(referenceSequence);
- if(queryResults == null) {
+ if (queryResults == null) {
return null;
}
final int binLevel = getLevelForBin(bin);
final int firstLocusInBin = getFirstLocusInBin(bin);
- long minimumOffset = bin instanceof BinWithOffset ? ((BinWithOffset)bin).getlOffset() : 0L;
+ long minimumOffset = bin instanceof BinWithOffset ? ((BinWithOffset) bin).getlOffset() : 0L;
// Add the specified bin to the tree if it exists.
final List binTree = new ArrayList();
- if(queryResults.containsBin(bin)) {
+ if (queryResults.containsBin(bin)) {
binTree.add(queryResults.getBins().getBin(bin.getBinNumber()));
}
int currentBinLevel = binLevel;
- while(--currentBinLevel >= 0) {
+ while (--currentBinLevel >= 0) {
final int binStart = getFirstBinInLevelForCSI(currentBinLevel);
- final int binWidth = getMaxSpan()/getLevelSize(currentBinLevel);
- final int parentBinNumber = firstLocusInBin/binWidth + binStart;
+ final int binWidth = getMaxSpan() / getLevelSize(currentBinLevel);
+ final int parentBinNumber = firstLocusInBin / binWidth + binStart;
final Bin parentBin = queryResults.getBins().getBin(parentBinNumber);
- if(parentBin != null && queryResults.containsBin(parentBin)) {
+ if (parentBin != null && queryResults.containsBin(parentBin)) {
binTree.add(parentBin);
}
}
List chunkList = new ArrayList();
- for(final Bin coveringBin: binTree) {
- for(final Chunk chunk: coveringBin.getChunkList())
- chunkList.add(chunk.clone());
+ for (final Bin coveringBin : binTree) {
+ for (final Chunk chunk : coveringBin.getChunkList()) chunkList.add(chunk.clone());
}
chunkList = Chunk.optimizeChunkList(chunkList, minimumOffset);
@@ -291,8 +303,8 @@ protected void verifyIndexMagicNumber(final String sourceName) {
final byte[] buffer = new byte[BAMFileConstants.CSI_MINSHIFT_OFFSET];
readBytes(buffer); // magic
if (!Arrays.equals(buffer, BAMFileConstants.CSI_INDEX_MAGIC)) {
- throw new RuntimeIOException("Invalid file header in BAM CSI index " + sourceName +
- ": " + new String(buffer));
+ throw new RuntimeIOException(
+ "Invalid file header in BAM CSI index " + sourceName + ": " + new String(buffer));
}
}
@@ -310,7 +322,7 @@ private void readAuxDataAndNRef() {
if (BAMFileConstants.CSI_AUXDATA_OFFSET != position()) {
seek(BAMFileConstants.CSI_AUXDATA_OFFSET);
}
- //set the aux data length first
+ // set the aux data length first
byte[] auxData = new byte[readInteger()]; // l_aux
readBytes(auxData); // aux
setAuxData(auxData);
@@ -379,11 +391,11 @@ protected BAMIndexContent query(final int referenceSequence, final int startPos,
final int binCount = readInteger(); // n_bin
boolean metaDataSeen = false;
- final Bin[] bins = new BinWithOffset[getMaxBinNumberForReference(referenceSequence) +1];
+ final Bin[] bins = new BinWithOffset[getMaxBinNumberForReference(referenceSequence) + 1];
for (int binNumber = 0; binNumber < binCount; binNumber++) {
final int indexBin = readInteger(); // bin
final long lOffset = readLong(); // l_offset
- final int nChunks = readInteger(); // n_chunk
+ final int nChunks = readInteger(); // n_chunk
List chunks;
Chunk lastChunk = null;
@@ -406,7 +418,8 @@ protected BAMIndexContent query(final int referenceSequence, final int startPos,
bins[indexBin] = bin;
}
- return new BAMIndexContent(referenceSequence, bins, binCount - (metaDataSeen? 1 : 0), new BAMIndexMetaData(metaDataChunks), null);
+ return new BAMIndexContent(
+ referenceSequence, bins, binCount - (metaDataSeen ? 1 : 0), new BAMIndexMetaData(metaDataChunks), null);
}
/**
@@ -472,12 +485,13 @@ public BAMIndexContent getQueryResults(final int referenceSequence) {
@Override
protected void skipToSequence(final int sequenceIndex) {
- if(sequenceIndex > getNumberOfReferences()) {
- throw new SAMException("Sequence index (" + sequenceIndex + ") is greater than maximum (" + getNumberOfReferences() + ").");
+ if (sequenceIndex > getNumberOfReferences()) {
+ throw new SAMException("Sequence index (" + sequenceIndex + ") is greater than maximum ("
+ + getNumberOfReferences() + ").");
}
- //Use sequence position cache if available
- if(sequenceIndexes[sequenceIndex] != -1){
+ // Use sequence position cache if available
+ if (sequenceIndexes[sequenceIndex] != -1) {
seek(sequenceIndexes[sequenceIndex]);
return;
}
@@ -497,7 +511,7 @@ protected void skipToSequence(final int sequenceIndex) {
}
}
- //Update sequence position cache
+ // Update sequence position cache
sequenceIndexes[sequenceIndex] = position();
}
}
diff --git a/src/main/java/htsjdk/samtools/CachingBAMFileIndex.java b/src/main/java/htsjdk/samtools/CachingBAMFileIndex.java
index 4a1a264d92..2bffd3f4d3 100644
--- a/src/main/java/htsjdk/samtools/CachingBAMFileIndex.java
+++ b/src/main/java/htsjdk/samtools/CachingBAMFileIndex.java
@@ -24,7 +24,6 @@
package htsjdk.samtools;
import htsjdk.samtools.seekablestream.SeekableStream;
-
import java.io.File;
import java.util.ArrayList;
import java.util.BitSet;
@@ -34,8 +33,7 @@
* Class for reading BAM file indices, caching each contig as it's loaded and
* dropping values when the next contig is loaded.
*/
-class CachingBAMFileIndex extends AbstractBAMFileIndex implements BrowseableBAMIndex
-{
+class CachingBAMFileIndex extends AbstractBAMFileIndex implements BrowseableBAMIndex {
// Since null is a valid return value for this index, it's possible to have lastReferenceIndex != null and
// lastReference == null, this is effectively caching the return value null
private Integer lastReferenceIndex = null;
@@ -52,7 +50,8 @@ public CachingBAMFileIndex(final SeekableStream stream, final SAMSequenceDiction
super(stream, dictionary);
}
- public CachingBAMFileIndex(final File file, final SAMSequenceDictionary dictionary, final boolean useMemoryMapping) {
+ public CachingBAMFileIndex(
+ final File file, final SAMSequenceDictionary dictionary, final boolean useMemoryMapping) {
super(file, dictionary, useMemoryMapping);
}
@@ -69,8 +68,7 @@ public CachingBAMFileIndex(final File file, final SAMSequenceDictionary dictiona
public BAMFileSpan getSpanOverlapping(final int referenceIndex, final int startPos, final int endPos) {
final BAMIndexContent queryResults = getQueryResults(referenceIndex);
- if(queryResults == null)
- return null;
+ if (queryResults == null) return null;
final List chunkList = queryResults.getChunksOverlapping(startPos, endPos);
if (chunkList == null) return null;
@@ -91,7 +89,7 @@ public BinList getBinsOverlapping(final int referenceIndex, final int startPos,
if (regionBins == null) {
return null;
}
- return new BinList(referenceIndex,regionBins);
+ return new BinList(referenceIndex, regionBins);
}
/**
@@ -101,62 +99,59 @@ public BinList getBinsOverlapping(final int referenceIndex, final int startPos,
*/
@Override
public BAMFileSpan getSpanOverlapping(final Bin bin) {
- if(bin == null)
- return null;
+ if (bin == null) return null;
final int referenceSequence = bin.getReferenceSequence();
final BAMIndexContent indexQuery = getQueryResults(referenceSequence);
- if(indexQuery == null)
- return null;
+ if (indexQuery == null) return null;
final int binLevel = getLevelForBin(bin);
final int firstLocusInBin = getFirstLocusInBin(bin);
// Add the specified bin to the tree if it exists.
final List binTree = new ArrayList<>();
- if(indexQuery.containsBin(bin))
- binTree.add(indexQuery.getBins().getBin(bin.getBinNumber()));
+ if (indexQuery.containsBin(bin)) binTree.add(indexQuery.getBins().getBin(bin.getBinNumber()));
int currentBinLevel = binLevel;
- while(--currentBinLevel >= 0) {
+ while (--currentBinLevel >= 0) {
final int binStart = getFirstBinInLevel(currentBinLevel);
- final int binWidth = getMaxAddressibleGenomicLocation()/getLevelSize(currentBinLevel);
- final int binNumber = firstLocusInBin/binWidth + binStart;
+ final int binWidth = getMaxAddressibleGenomicLocation() / getLevelSize(currentBinLevel);
+ final int binNumber = firstLocusInBin / binWidth + binStart;
final Bin parentBin = indexQuery.getBins().getBin(binNumber);
- if(parentBin != null && indexQuery.containsBin(parentBin))
- binTree.add(parentBin);
+ if (parentBin != null && indexQuery.containsBin(parentBin)) binTree.add(parentBin);
}
List chunkList = new ArrayList();
- for(final Bin coveringBin: binTree) {
- for(final Chunk chunk: coveringBin.getChunkList())
- chunkList.add(chunk.clone());
+ for (final Bin coveringBin : binTree) {
+ for (final Chunk chunk : coveringBin.getChunkList()) chunkList.add(chunk.clone());
}
final int start = getFirstLocusInBin(bin);
- chunkList = Chunk.optimizeChunkList(chunkList,indexQuery.getLinearIndex().getMinimumOffset(start));
+ chunkList =
+ Chunk.optimizeChunkList(chunkList, indexQuery.getLinearIndex().getMinimumOffset(start));
return new BAMFileSpan(chunkList);
}
/**
* Looks up the cached BAM query results if they're still in the cache and not expired. Otherwise,
* retrieves the cache results from disk.
- * @param referenceIndex The reference to load. CachingBAMFileIndex only stores index data for entire references.
+ * @param referenceIndex The reference to load. CachingBAMFileIndex only stores index data for entire references.
* @return The index information for this reference or null if no index information is available for the given index.
*/
@Override
protected BAMIndexContent getQueryResults(final int referenceIndex) {
// If this query is for the same reference index as the last query, return it.
- // This compares a boxed Integer to an int with == which is ok because the Integer will be unboxed to the primitive value
- if(lastReferenceIndex!=null && lastReferenceIndex == referenceIndex){
+ // This compares a boxed Integer to an int with == which is ok because the Integer will be unboxed to the
+ // primitive value
+ if (lastReferenceIndex != null && lastReferenceIndex == referenceIndex) {
cacheHits++;
return lastReference;
}
// If not attempt to load it from disk.
- final BAMIndexContent queryResults = query(referenceIndex,1,-1);
+ final BAMIndexContent queryResults = query(referenceIndex, 1, -1);
cacheMisses++;
lastReferenceIndex = referenceIndex;
lastReference = queryResults;
diff --git a/src/main/java/htsjdk/samtools/CachingBamFileIndexOptimizedForMerging.java b/src/main/java/htsjdk/samtools/CachingBamFileIndexOptimizedForMerging.java
index ae0ae98056..04bb820794 100644
--- a/src/main/java/htsjdk/samtools/CachingBamFileIndexOptimizedForMerging.java
+++ b/src/main/java/htsjdk/samtools/CachingBamFileIndexOptimizedForMerging.java
@@ -7,28 +7,28 @@
* null BAMIndexContent objects if all bins are empty.
*/
class CachingBamFileIndexOptimizedForMerging extends CachingBAMFileIndex {
- CachingBamFileIndexOptimizedForMerging(SeekableStream stream, SAMSequenceDictionary dictionary) {
- super(stream, dictionary);
- }
+ CachingBamFileIndexOptimizedForMerging(SeekableStream stream, SAMSequenceDictionary dictionary) {
+ super(stream, dictionary);
+ }
- @Override
- protected BAMIndexContent query(final int referenceSequence, final int startPos, final int endPos) {
- seek(4);
+ @Override
+ protected BAMIndexContent query(final int referenceSequence, final int startPos, final int endPos) {
+ seek(4);
- final int sequenceCount = readInteger();
+ final int sequenceCount = readInteger();
- if (referenceSequence >= sequenceCount) {
- return null;
- }
+ if (referenceSequence >= sequenceCount) {
+ return null;
+ }
- skipToSequence(referenceSequence);
+ skipToSequence(referenceSequence);
- final int binCount = readInteger();
+ final int binCount = readInteger();
- if (binCount == 0) {
- return null;
- }
+ if (binCount == 0) {
+ return null;
+ }
- return super.query(referenceSequence, startPos, endPos);
- }
+ return super.query(referenceSequence, startPos, endPos);
+ }
}
diff --git a/src/main/java/htsjdk/samtools/ChainedDownsamplingIterator.java b/src/main/java/htsjdk/samtools/ChainedDownsamplingIterator.java
index 4fa3a7d86f..b400091ca2 100644
--- a/src/main/java/htsjdk/samtools/ChainedDownsamplingIterator.java
+++ b/src/main/java/htsjdk/samtools/ChainedDownsamplingIterator.java
@@ -56,16 +56,16 @@ class ChainedDownsamplingIterator extends HighAccuracyDownsamplingIterator {
* Uses an assumed number of reads tested as this is often not known until after the fact.
*/
private static double adjustProportion(final double p) {
- final double ciAdjustment99_9 = 3.3 * Math.sqrt(p/MIN_ACCURATE_INPUT_READS);
+ final double ciAdjustment99_9 = 3.3 * Math.sqrt(p / MIN_ACCURATE_INPUT_READS);
return Math.min(1, p + ciAdjustment99_9);
}
-
/**
* Resets statistics before reading from the underlying iterator.
*/
@Override
- protected void readFromUnderlyingIterator(final List recs, final Set names, final int templatesToRead) {
+ protected void readFromUnderlyingIterator(
+ final List recs, final Set names, final int templatesToRead) {
// Reset the stats on the underlying iterator
((ConstantMemoryDownsamplingIterator) getUnderlyingIterator()).resetStatistics();
@@ -79,7 +79,7 @@ protected int calculateTemplatesToKeep(final int templatesRead, final double ove
final ConstantMemoryDownsamplingIterator iter = (ConstantMemoryDownsamplingIterator) getUnderlyingIterator();
final double priorProportion = iter.getAcceptedFraction();
final double p = Math.max(0, Math.min(1, overallProportion / priorProportion));
- final int retval = super.calculateTemplatesToKeep(templatesRead, p);
+ final int retval = super.calculateTemplatesToKeep(templatesRead, p);
// Record all the discarded records to keep the overall statistics accurate, but do it after
// the call to super() so it doesn't affect the proportion calculation.
diff --git a/src/main/java/htsjdk/samtools/Chunk.java b/src/main/java/htsjdk/samtools/Chunk.java
index 8a6d4bf802..cdc919bbd6 100644
--- a/src/main/java/htsjdk/samtools/Chunk.java
+++ b/src/main/java/htsjdk/samtools/Chunk.java
@@ -1,7 +1,6 @@
package htsjdk.samtools;
import htsjdk.samtools.util.BlockCompressedFilePointerUtil;
-
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
@@ -17,7 +16,7 @@
*
* See the SAM/BAM spec for more details.
*/
-public class Chunk implements Cloneable, Serializable,Comparable {
+public class Chunk implements Cloneable, Serializable, Comparable {
private static final long serialVersionUID = 1L;
/**
@@ -40,7 +39,7 @@ public Chunk(final long start, final long end) {
@Override
public Chunk clone() {
- return new Chunk(mChunkStart,mChunkEnd);
+ return new Chunk(mChunkStart, mChunkEnd);
}
public long getChunkStart() {
@@ -88,12 +87,11 @@ public boolean equals(final Object o) {
*/
public boolean overlaps(final Chunk other) {
final int comparison = this.compareTo(other);
- if(comparison == 0)
- return true;
+ if (comparison == 0) return true;
// "sort" the two chunks using the comparator.
- final Chunk leftMost = comparison==-1 ? this : other;
- final Chunk rightMost = comparison==1 ? this : other;
+ final Chunk leftMost = comparison == -1 ? this : other;
+ final Chunk rightMost = comparison == 1 ? this : other;
final long leftMostBlockAddress = BlockCompressedFilePointerUtil.getBlockAddress(leftMost.getChunkEnd());
final long rightMostBlockAddress = BlockCompressedFilePointerUtil.getBlockAddress(rightMost.getChunkStart());
@@ -101,15 +99,12 @@ public boolean overlaps(final Chunk other) {
// If the left block's address is after the right block's address, compare the two blocks.
// If the two blocks are identical, compare the block offsets.
// If the right block is after the left block, no overlap is possible.
- if(leftMostBlockAddress > rightMostBlockAddress)
- return true;
- else if(leftMostBlockAddress == rightMostBlockAddress) {
+ if (leftMostBlockAddress > rightMostBlockAddress) return true;
+ else if (leftMostBlockAddress == rightMostBlockAddress) {
final int leftMostOffset = BlockCompressedFilePointerUtil.getBlockOffset(leftMost.getChunkEnd());
final int rightMostOffset = BlockCompressedFilePointerUtil.getBlockOffset(rightMost.getChunkStart());
return leftMostOffset > rightMostOffset;
- }
- else
- return false;
+ } else return false;
}
/**
@@ -118,12 +113,17 @@ else if(leftMostBlockAddress == rightMostBlockAddress) {
* @return True if the two chunks are adjacent. Returns false if the chunks overlap or are discontinuous.
*/
public boolean isAdjacentTo(final Chunk other) {
- // Simpler implementation would be to == the chunk end of one to the chunk start of the other. Chose this implementation to ensure that all chunk
- // comparisons point directly to the
- return (BlockCompressedFilePointerUtil.getBlockAddress(this.getChunkEnd()) == BlockCompressedFilePointerUtil.getBlockAddress(other.getChunkStart()) &&
- BlockCompressedFilePointerUtil.getBlockOffset(this.getChunkEnd()) == BlockCompressedFilePointerUtil.getBlockOffset(other.getChunkStart())) ||
- (BlockCompressedFilePointerUtil.getBlockAddress(this.getChunkStart()) == BlockCompressedFilePointerUtil.getBlockAddress(other.getChunkEnd()) &&
- BlockCompressedFilePointerUtil.getBlockOffset(this.getChunkStart()) == BlockCompressedFilePointerUtil.getBlockOffset(other.getChunkEnd()));
+ // Simpler implementation would be to == the chunk end of one to the chunk start of the other. Chose this
+ // implementation to ensure that all chunk
+ // comparisons point directly to the
+ return (BlockCompressedFilePointerUtil.getBlockAddress(this.getChunkEnd())
+ == BlockCompressedFilePointerUtil.getBlockAddress(other.getChunkStart())
+ && BlockCompressedFilePointerUtil.getBlockOffset(this.getChunkEnd())
+ == BlockCompressedFilePointerUtil.getBlockOffset(other.getChunkStart()))
+ || (BlockCompressedFilePointerUtil.getBlockAddress(this.getChunkStart())
+ == BlockCompressedFilePointerUtil.getBlockAddress(other.getChunkEnd())
+ && BlockCompressedFilePointerUtil.getBlockOffset(this.getChunkStart())
+ == BlockCompressedFilePointerUtil.getBlockOffset(other.getChunkEnd()));
}
/**
@@ -148,7 +148,8 @@ public int hashCode() {
@Override
public String toString() {
- return String.format("%d:%d-%d:%d",mChunkStart >> 16,mChunkStart & 0xFFFF,mChunkEnd >> 16,mChunkEnd & 0xFFFF);
+ return String.format(
+ "%d:%d-%d:%d", mChunkStart >> 16, mChunkStart & 0xFFFF, mChunkEnd >> 16, mChunkEnd & 0xFFFF);
}
/**
@@ -161,7 +162,7 @@ public static List optimizeChunkList(final List chunks, final long
final List result = new ArrayList();
for (final Chunk chunk : chunks) {
if (chunk.getChunkEnd() <= minimumOffset) {
- continue; // linear index optimization
+ continue; // linear index optimization
}
if (result.isEmpty()) {
result.add(chunk);
diff --git a/src/main/java/htsjdk/samtools/Cigar.java b/src/main/java/htsjdk/samtools/Cigar.java
index 8fafd639f1..5eb3259cd8 100644
--- a/src/main/java/htsjdk/samtools/Cigar.java
+++ b/src/main/java/htsjdk/samtools/Cigar.java
@@ -43,8 +43,7 @@ public class Cigar implements Serializable, Iterable {
private final List cigarElements = new ArrayList();
- public Cigar() {
- }
+ public Cigar() {}
public Cigar(final List cigarElements) {
this.cigarElements.addAll(cigarElements);
@@ -84,7 +83,8 @@ public int getReferenceLength() {
case X:
length += element.getLength();
break;
- default: break;
+ default:
+ break;
}
}
return length;
@@ -105,7 +105,8 @@ public int getPaddedReferenceLength() {
case P:
length += element.getLength();
break;
- default: break;
+ default:
+ break;
}
}
return length;
@@ -124,8 +125,8 @@ public int getReadLength() {
public static int getReadLength(final List cigarElements) {
int length = 0;
for (final CigarElement element : cigarElements) {
- if (element.getOperator().consumesReadBases()){
- length += element.getLength();
+ if (element.getOperator().consumesReadBases()) {
+ length += element.getLength();
}
}
return length;
@@ -149,8 +150,11 @@ public List isValid(final String readName, final long record
final CigarElement element = cigarElements.get(i);
if (element.getLength() == 0) {
if (ret == null) ret = new ArrayList