From 3890b7013b0e9c530b8d17fb95c86071cf7e4156 Mon Sep 17 00:00:00 2001 From: PJ Fanning Date: Sat, 22 May 2021 20:56:44 +0000 Subject: [PATCH] convert tabs to spaces git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1890120 13f79535-47bb-0310-9956-ffa450edef68 --- .../org/apache/poi/EmptyFileException.java | 12 +- .../poi/EncryptedDocumentException.java | 6 +- .../apache/poi/OldFileFormatException.java | 4 +- .../main/java/org/apache/poi/POIDocument.java | 4 +- .../poi/UnsupportedFileFormatException.java | 4 +- .../apache/poi/ddf/EscherMetafileBlip.java | 8 +- .../apache/poi/ddf/UnknownEscherRecord.java | 16 +- .../poi/extractor/POIOLE2TextExtractor.java | 56 +- .../poi/extractor/POITextExtractor.java | 92 +- .../java/org/apache/poi/hpsf/ClassID.java | 2 +- .../poi/hpsf/DocumentSummaryInformation.java | 2 +- .../apache/poi/hpsf/HPSFRuntimeException.java | 4 +- .../apache/poi/hpsf/SummaryInformation.java | 2 +- .../org/apache/poi/hpsf/VariantSupport.java | 2 +- .../poi/hssf/OldExcelFormatException.java | 6 +- .../org/apache/poi/hssf/dev/BiffViewer.java | 556 ++++----- .../apache/poi/hssf/dev/FormulaViewer.java | 6 +- .../hssf/eventmodel/EventRecordFactory.java | 154 +-- .../eventusermodel/AbortableHSSFListener.java | 40 +- .../eventusermodel/EventWorkbookBuilder.java | 222 ++-- .../FormatTrackingHSSFListener.java | 276 ++--- .../hssf/eventusermodel/HSSFEventFactory.java | 170 +-- .../poi/hssf/eventusermodel/HSSFRequest.java | 134 +-- .../MissingRecordAwareHSSFListener.java | 280 ++--- .../dummyrecord/DummyRecordBase.java | 20 +- .../dummyrecord/LastCellOfRowDummyRecord.java | 82 +- .../dummyrecord/MissingCellDummyRecord.java | 46 +- .../dummyrecord/MissingRowDummyRecord.java | 42 +- .../poi/hssf/extractor/ExcelExtractor.java | 676 +++++------ .../poi/hssf/extractor/OldExcelExtractor.java | 50 +- .../poi/hssf/model/DrawingManager2.java | 2 +- .../apache/poi/hssf/model/InternalSheet.java | 4 +- .../poi/hssf/model/InternalWorkbook.java | 48 +- .../apache/poi/hssf/model/RecordOrderer.java | 700 +++++------ .../apache/poi/hssf/model/RecordStream.java | 114 +- .../poi/hssf/model/RowBlocksReader.java | 148 +-- .../poi/hssf/model/WorkbookRecordList.java | 266 ++--- .../record/AbstractEscherHolderRecord.java | 48 +- .../apache/poi/hssf/record/ArrayRecord.java | 120 +- .../poi/hssf/record/BiffHeaderInput.java | 34 +- .../apache/poi/hssf/record/BoolErrRecord.java | 304 ++--- .../poi/hssf/record/BoundSheetRecord.java | 328 ++--- .../poi/hssf/record/CFRule12Record.java | 2 +- .../apache/poi/hssf/record/CFRuleBase.java | 2 +- .../poi/hssf/record/CRNCountRecord.java | 98 +- .../org/apache/poi/hssf/record/CRNRecord.java | 112 +- .../record/CommonObjectDataSubRecord.java | 8 +- .../apache/poi/hssf/record/DVALRecord.java | 164 +-- .../org/apache/poi/hssf/record/DVRecord.java | 482 ++++---- .../record/DrawingRecordForBiffViewer.java | 16 +- .../hssf/record/DrawingSelectionRecord.java | 182 +-- .../org/apache/poi/hssf/record/EOFRecord.java | 4 +- .../record/EmbeddedObjectRefSubRecord.java | 542 ++++----- .../apache/poi/hssf/record/EndSubRecord.java | 2 +- .../apache/poi/hssf/record/ExtSSTRecord.java | 8 +- .../poi/hssf/record/ExtendedFormatRecord.java | 44 +- .../poi/hssf/record/ExternSheetRecord.java | 332 ++--- .../poi/hssf/record/ExternalNameRecord.java | 328 ++--- .../apache/poi/hssf/record/FeatHdrRecord.java | 164 +-- .../apache/poi/hssf/record/FeatRecord.java | 268 ++--- .../poi/hssf/record/FilePassRecord.java | 52 +- .../poi/hssf/record/FileSharingRecord.java | 2 +- .../apache/poi/hssf/record/FontRecord.java | 868 +++++++------- .../apache/poi/hssf/record/FooterRecord.java | 42 +- .../apache/poi/hssf/record/FormulaRecord.java | 406 +++---- .../poi/hssf/record/FtCblsSubRecord.java | 2 +- .../poi/hssf/record/GroupMarkerSubRecord.java | 2 +- .../poi/hssf/record/HeaderFooterBase.java | 166 +-- .../poi/hssf/record/HeaderFooterRecord.java | 36 +- .../apache/poi/hssf/record/HeaderRecord.java | 42 +- .../record/HorizontalPageBreakRecord.java | 50 +- .../apache/poi/hssf/record/IndexRecord.java | 6 +- .../apache/poi/hssf/record/LabelRecord.java | 4 +- .../poi/hssf/record/LabelSSTRecord.java | 2 +- .../org/apache/poi/hssf/record/Margin.java | 26 +- .../poi/hssf/record/MergeCellsRecord.java | 30 +- .../poi/hssf/record/MulBlankRecord.java | 186 +-- .../apache/poi/hssf/record/MulRKRecord.java | 216 ++-- .../apache/poi/hssf/record/NameRecord.java | 980 +++++++-------- .../apache/poi/hssf/record/NoteRecord.java | 408 +++---- .../hssf/record/NoteStructureSubRecord.java | 2 +- .../poi/hssf/record/PageBreakRecord.java | 2 +- .../org/apache/poi/hssf/record/RKRecord.java | 6 +- .../poi/hssf/record/RecalcIdRecord.java | 6 +- .../apache/poi/hssf/record/RecordBase.java | 34 +- .../hssf/record/RecordFactoryInputStream.java | 556 ++++----- .../poi/hssf/record/RecordInputStream.java | 746 ++++++------ .../org/apache/poi/hssf/record/RowRecord.java | 28 +- .../poi/hssf/record/SSTDeserializer.java | 2 +- .../apache/poi/hssf/record/SSTSerializer.java | 8 +- .../poi/hssf/record/SharedFormulaRecord.java | 6 +- .../hssf/record/SharedValueRecordBase.java | 144 +-- .../apache/poi/hssf/record/StringRecord.java | 6 +- .../apache/poi/hssf/record/StyleRecord.java | 296 ++--- .../org/apache/poi/hssf/record/SubRecord.java | 216 ++-- .../apache/poi/hssf/record/SupBookRecord.java | 66 +- .../apache/poi/hssf/record/TableRecord.java | 274 ++--- .../poi/hssf/record/TableStylesRecord.java | 130 +- .../poi/hssf/record/TextObjectRecord.java | 524 ++++---- .../poi/hssf/record/UncalcedRecord.java | 68 +- .../poi/hssf/record/UserSViewBegin.java | 34 +- .../apache/poi/hssf/record/UserSViewEnd.java | 36 +- .../apache/poi/hssf/record/VCenterRecord.java | 2 +- .../hssf/record/VerticalPageBreakRecord.java | 50 +- .../poi/hssf/record/WindowOneRecord.java | 6 +- .../poi/hssf/record/WriteAccessRecord.java | 224 ++-- .../ChartSubstreamRecordAggregate.java | 94 +- .../ColumnInfoRecordsAggregate.java | 916 +++++++------- .../ConditionalFormattingTable.java | 100 +- .../CustomViewSettingsRecordAggregate.java | 90 +- .../record/aggregates/DataValidityTable.java | 58 +- .../aggregates/FormulaRecordAggregate.java | 406 +++---- .../record/aggregates/MergedCellsTable.java | 166 +-- .../record/aggregates/PageSettingsBlock.java | 2 +- .../record/aggregates/RecordAggregate.java | 164 +-- .../record/aggregates/SharedValueManager.java | 374 +++--- .../aggregates/ValueRecordsAggregate.java | 566 ++++----- .../aggregates/WorksheetProtectionBlock.java | 372 +++--- .../poi/hssf/record/cf/FontFormatting.java | 2 +- .../poi/hssf/record/chart/CatLabRecord.java | 132 +- .../record/chart/ChartEndBlockRecord.java | 116 +- .../record/chart/ChartEndObjectRecord.java | 120 +- .../hssf/record/chart/ChartFRTInfoRecord.java | 162 +-- .../record/chart/ChartStartBlockRecord.java | 122 +- .../record/chart/ChartStartObjectRecord.java | 120 +- .../record/chart/ChartTitleFormatRecord.java | 160 +-- .../chart/DataLabelExtensionRecord.java | 90 +- .../hssf/record/chart/SeriesListRecord.java | 12 +- .../hssf/record/chart/SeriesTextRecord.java | 184 +-- .../hssf/record/common/FeatFormulaErr2.java | 182 +-- .../hssf/record/common/FeatProtection.java | 136 +-- .../poi/hssf/record/common/FeatSmartTag.java | 56 +- .../poi/hssf/record/common/SharedFeature.java | 8 +- .../poi/hssf/record/common/UnicodeString.java | 18 +- .../hssf/record/cont/ContinuableRecord.java | 86 +- .../record/cont/ContinuableRecordOutput.java | 464 +++---- .../cont/UnknownLengthRecordOutput.java | 158 +-- .../record/crypto/Biff8DecryptingStream.java | 122 +- .../record/crypto/Biff8EncryptionKey.java | 50 +- .../record/pivottable/DataItemRecord.java | 128 +- .../ExtendedPivotTableViewFieldsRecord.java | 194 +-- .../record/pivottable/PageItemRecord.java | 152 +-- .../record/pivottable/StreamIDRecord.java | 66 +- .../pivottable/ViewDefinitionRecord.java | 290 ++--- .../record/pivottable/ViewFieldsRecord.java | 180 +-- .../record/pivottable/ViewSourceRecord.java | 66 +- .../poi/hssf/usermodel/DVConstraint.java | 734 ++++++------ .../poi/hssf/usermodel/EscherGraphics.java | 22 +- .../poi/hssf/usermodel/EscherGraphics2d.java | 10 +- .../apache/poi/hssf/usermodel/HSSFCell.java | 2 +- .../apache/poi/hssf/usermodel/HSSFChart.java | 12 +- .../poi/hssf/usermodel/HSSFDataFormat.java | 236 ++-- .../hssf/usermodel/HSSFDataValidation.java | 332 ++--- .../usermodel/HSSFDataValidationHelper.java | 186 +-- .../poi/hssf/usermodel/HSSFDateUtil.java | 6 +- .../hssf/usermodel/HSSFEvaluationCell.java | 140 +-- .../apache/poi/hssf/usermodel/HSSFFont.java | 24 +- .../apache/poi/hssf/usermodel/HSSFFooter.java | 42 +- .../apache/poi/hssf/usermodel/HSSFHeader.java | 42 +- .../poi/hssf/usermodel/HSSFOptimiser.java | 464 +++---- .../poi/hssf/usermodel/HSSFPalette.java | 10 +- .../poi/hssf/usermodel/HSSFPatriarch.java | 32 +- .../poi/hssf/usermodel/HSSFPicture.java | 4 +- .../poi/hssf/usermodel/HSSFPolygon.java | 4 +- .../poi/hssf/usermodel/HSSFPrintSetup.java | 56 +- .../hssf/usermodel/HSSFRichTextString.java | 2 +- .../poi/hssf/usermodel/HSSFShapeFactory.java | 2 +- .../HSSFSheetConditionalFormatting.java | 20 +- .../poi/hssf/usermodel/HeaderFooter.java | 574 ++++----- .../poi/hssf/usermodel/StaticFontMetrics.java | 128 +- .../poi/hssf/util/CellRangeAddress8Bit.java | 54 +- .../poi/poifs/crypt/EncryptionHeader.java | 2 +- .../org/apache/poi/poifs/crypt/Encryptor.java | 4 +- .../apache/poi/poifs/crypt/HashAlgorithm.java | 8 +- .../poi/poifs/crypt/agile/AgileEncryptor.java | 12 +- .../poifs/filesystem/DocumentInputStream.java | 136 +-- .../filesystem/DocumentOutputStream.java | 62 +- .../poi/poifs/filesystem/EntryUtils.java | 2 +- .../filesystem/NotOLE2FileException.java | 6 +- .../filesystem/OfficeXmlFileException.java | 6 +- .../poi/poifs/filesystem/POIFSDocument.java | 6 +- .../apache/poi/poifs/storage/HeaderBlock.java | 390 +++--- .../apache/poi/sl/draw/DrawTexturePaint.java | 2 +- .../apache/poi/sl/draw/geom/ArcToCommand.java | 2 +- .../org/apache/poi/sl/draw/geom/Path.java | 4 +- .../apache/poi/sl/usermodel/MasterSheet.java | 14 +- .../org/apache/poi/sl/usermodel/Notes.java | 2 +- .../apache/poi/sl/usermodel/PictureData.java | 38 +- .../apache/poi/sl/usermodel/PictureShape.java | 28 +- .../org/apache/poi/sl/usermodel/Shape.java | 2 +- .../poi/sl/usermodel/ShapeContainer.java | 26 +- .../org/apache/poi/sl/usermodel/Sheet.java | 38 +- .../apache/poi/sl/usermodel/SimpleShape.java | 12 +- .../apache/poi/sl/usermodel/SlideShow.java | 10 +- .../apache/poi/ss/formula/CellCacheEntry.java | 184 +-- .../poi/ss/formula/CellEvaluationFrame.java | 88 +- .../poi/ss/formula/EvaluationCache.java | 324 ++--- .../apache/poi/ss/formula/EvaluationCell.java | 38 +- .../apache/poi/ss/formula/EvaluationName.java | 12 +- .../poi/ss/formula/EvaluationTracker.java | 204 ++-- .../ss/formula/ExternSheetReferenceToken.java | 10 +- .../org/apache/poi/ss/formula/Formula.java | 308 ++--- .../poi/ss/formula/FormulaCellCache.java | 68 +- .../poi/ss/formula/FormulaCellCacheEntry.java | 164 +-- .../ss/formula/FormulaCellCacheEntrySet.java | 226 ++-- .../poi/ss/formula/FormulaParseException.java | 8 +- .../apache/poi/ss/formula/FormulaParser.java | 4 +- .../ss/formula/FormulaRenderingWorkbook.java | 20 +- .../ss/formula/FormulaUsedBlankCellSet.java | 300 ++--- .../poi/ss/formula/IEvaluationListener.java | 46 +- .../poi/ss/formula/IStabilityClassifier.java | 42 +- .../apache/poi/ss/formula/LazyAreaEval.java | 104 +- .../apache/poi/ss/formula/LazyRefEval.java | 56 +- .../ss/formula/OperandClassTransformer.java | 430 +++---- .../ss/formula/OperationEvaluatorFactory.java | 144 +-- .../org/apache/poi/ss/formula/ParseNode.java | 296 ++--- .../apache/poi/ss/formula/PlainCellCache.java | 92 +- .../ss/formula/PlainValueCellCacheEntry.java | 6 +- .../poi/ss/formula/SheetNameFormatter.java | 432 +++---- .../poi/ss/formula/SheetRangeEvaluator.java | 62 +- .../poi/ss/formula/SheetRefEvaluator.java | 48 +- .../org/apache/poi/ss/formula/ThreeDEval.java | 14 +- .../org/apache/poi/ss/formula/TwoDEval.java | 60 +- .../poi/ss/formula/UserDefinedFunction.java | 54 +- .../ss/formula/WorkbookDependentFormula.java | 2 +- .../apache/poi/ss/formula/atp/IfError.java | 48 +- .../org/apache/poi/ss/formula/atp/MRound.java | 12 +- .../poi/ss/formula/atp/ParityFunction.java | 54 +- .../poi/ss/formula/atp/RandBetween.java | 64 +- .../poi/ss/formula/atp/WorkdayCalculator.java | 34 +- .../apache/poi/ss/formula/atp/YearFrac.java | 90 +- .../ss/formula/atp/YearFracCalculator.java | 532 ++++----- .../formula/constant/ConstantValueParser.java | 226 ++-- .../ss/formula/constant/ErrorConstant.java | 68 +- .../poi/ss/formula/eval/AreaEvalBase.java | 204 ++-- .../apache/poi/ss/formula/eval/BlankEval.java | 8 +- .../apache/poi/ss/formula/eval/BoolEval.java | 62 +- .../poi/ss/formula/eval/ConcatEval.java | 58 +- .../ss/formula/eval/EvaluationException.java | 132 +- .../poi/ss/formula/eval/ExternalNameEval.java | 24 +- .../poi/ss/formula/eval/FunctionNameEval.java | 30 +- .../poi/ss/formula/eval/IntersectionEval.java | 120 +- .../poi/ss/formula/eval/MissingArgEval.java | 8 +- .../formula/eval/NotImplementedException.java | 10 +- .../eval/NotImplementedFunctionException.java | 22 +- .../poi/ss/formula/eval/PercentEval.java | 36 +- .../apache/poi/ss/formula/eval/RangeEval.java | 78 +- .../poi/ss/formula/eval/RefEvalBase.java | 30 +- .../formula/eval/RelationalOperationEval.java | 282 ++--- .../poi/ss/formula/eval/StringEval.java | 40 +- .../eval/TwoOperandNumericOperation.java | 166 +-- .../poi/ss/formula/eval/UnaryMinusEval.java | 52 +- .../poi/ss/formula/eval/UnaryPlusEval.java | 58 +- .../apache/poi/ss/formula/eval/ValueEval.java | 2 +- .../eval/forked/ForkedEvaluationCell.java | 224 ++-- .../formula/eval/forked/ForkedEvaluator.java | 146 +-- .../formula/function/FunctionDataBuilder.java | 100 +- .../ss/formula/function/FunctionMetadata.java | 120 +- .../function/FunctionMetadataReader.java | 280 ++--- .../function/FunctionMetadataRegistry.java | 136 +-- .../poi/ss/formula/functions/Address.java | 2 +- .../ss/formula/functions/BooleanFunction.java | 202 ++-- .../functions/CalendarFieldFunction.java | 86 +- .../poi/ss/formula/functions/Choose.java | 46 +- .../poi/ss/formula/functions/Columns.java | 22 +- .../poi/ss/formula/functions/Count.java | 60 +- .../poi/ss/formula/functions/CountUtils.java | 58 +- .../poi/ss/formula/functions/Counta.java | 58 +- .../poi/ss/formula/functions/Countblank.java | 38 +- .../poi/ss/formula/functions/DateFunc.java | 140 +-- .../poi/ss/formula/functions/Errortype.java | 46 +- .../poi/ss/formula/functions/Finance.java | 104 +- .../formula/functions/Fixed0ArgFunction.java | 12 +- .../formula/functions/Fixed1ArgFunction.java | 12 +- .../formula/functions/Fixed2ArgFunction.java | 12 +- .../formula/functions/Fixed3ArgFunction.java | 12 +- .../formula/functions/Fixed4ArgFunction.java | 12 +- .../ss/formula/functions/FreeRefFunction.java | 18 +- .../poi/ss/formula/functions/Function.java | 22 +- .../ss/formula/functions/Function0Arg.java | 8 +- .../ss/formula/functions/Function1Arg.java | 8 +- .../ss/formula/functions/Function2Arg.java | 8 +- .../ss/formula/functions/Function3Arg.java | 8 +- .../ss/formula/functions/Function4Arg.java | 8 +- .../poi/ss/formula/functions/Hlookup.java | 72 +- .../poi/ss/formula/functions/Hyperlink.java | 16 +- .../apache/poi/ss/formula/functions/IPMT.java | 40 +- .../poi/ss/formula/functions/Index.java | 220 ++-- .../poi/ss/formula/functions/Intercept.java | 18 +- .../functions/LinearRegressionFunction.java | 298 ++--- .../ss/formula/functions/LogicalFunction.java | 172 +-- .../poi/ss/formula/functions/Lookup.java | 116 +- .../poi/ss/formula/functions/LookupUtils.java | 1058 ++++++++-------- .../poi/ss/formula/functions/Match.java | 312 ++--- .../poi/ss/formula/functions/MinaMaxa.java | 26 +- .../apache/poi/ss/formula/functions/Mode.java | 182 +-- .../apache/poi/ss/formula/functions/Na.java | 6 +- .../functions/NotImplementedFunction.java | 26 +- .../apache/poi/ss/formula/functions/Now.java | 14 +- .../apache/poi/ss/formula/functions/Npv.java | 22 +- .../ss/formula/functions/NumericFunction.java | 352 +++--- .../apache/poi/ss/formula/functions/PPMT.java | 22 +- .../apache/poi/ss/formula/functions/Rank.java | 8 +- .../poi/ss/formula/functions/Replace.java | 60 +- .../apache/poi/ss/formula/functions/Rept.java | 2 +- .../apache/poi/ss/formula/functions/Rows.java | 22 +- .../poi/ss/formula/functions/Slope.java | 18 +- .../poi/ss/formula/functions/Substitute.java | 144 +-- .../poi/ss/formula/functions/Subtotal.java | 120 +- .../poi/ss/formula/functions/Sumif.java | 158 +-- .../poi/ss/formula/functions/Sumproduct.java | 314 ++--- .../poi/ss/formula/functions/Sumx2my2.java | 18 +- .../poi/ss/formula/functions/Sumx2py2.java | 18 +- .../poi/ss/formula/functions/Sumxmy2.java | 20 +- .../ss/formula/functions/TextFunction.java | 638 +++++----- .../poi/ss/formula/functions/TimeFunc.java | 94 +- .../poi/ss/formula/functions/Today.java | 22 +- .../formula/functions/Var1or2ArgFunction.java | 18 +- .../formula/functions/Var2or3ArgFunction.java | 18 +- .../formula/functions/Var3or4ArgFunction.java | 18 +- .../poi/ss/formula/functions/Vlookup.java | 74 +- .../poi/ss/formula/functions/WeekNum.java | 4 +- .../poi/ss/formula/functions/WeekdayFunc.java | 156 +-- .../formula/functions/XYNumericFunction.java | 278 ++--- .../org/apache/poi/ss/formula/ptg/AddPtg.java | 2 +- .../poi/ss/formula/ptg/Area2DPtgBase.java | 46 +- .../apache/poi/ss/formula/ptg/Area3DPtg.java | 140 +-- .../apache/poi/ss/formula/ptg/AreaErrPtg.java | 84 +- .../org/apache/poi/ss/formula/ptg/AreaI.java | 82 +- .../apache/poi/ss/formula/ptg/AreaNPtg.java | 30 +- .../apache/poi/ss/formula/ptg/AreaPtg.java | 36 +- .../poi/ss/formula/ptg/ArrayInitialPtg.java | 126 +- .../apache/poi/ss/formula/ptg/ArrayPtg.java | 340 +++--- .../apache/poi/ss/formula/ptg/BoolPtg.java | 78 +- .../apache/poi/ss/formula/ptg/ConcatPtg.java | 2 +- .../apache/poi/ss/formula/ptg/ControlPtg.java | 16 +- .../poi/ss/formula/ptg/DeletedArea3DPtg.java | 104 +- .../poi/ss/formula/ptg/DeletedRef3DPtg.java | 90 +- .../apache/poi/ss/formula/ptg/DividePtg.java | 2 +- .../apache/poi/ss/formula/ptg/EqualPtg.java | 2 +- .../poi/ss/formula/ptg/GreaterEqualPtg.java | 2 +- .../poi/ss/formula/ptg/GreaterThanPtg.java | 2 +- .../org/apache/poi/ss/formula/ptg/IntPtg.java | 104 +- .../poi/ss/formula/ptg/IntersectionPtg.java | 62 +- .../poi/ss/formula/ptg/LessEqualPtg.java | 2 +- .../poi/ss/formula/ptg/LessThanPtg.java | 2 +- .../apache/poi/ss/formula/ptg/MemAreaPtg.java | 86 +- .../apache/poi/ss/formula/ptg/MemErrPtg.java | 84 +- .../apache/poi/ss/formula/ptg/MemFuncPtg.java | 88 +- .../poi/ss/formula/ptg/MissingArgPtg.java | 54 +- .../poi/ss/formula/ptg/MultiplyPtg.java | 2 +- .../apache/poi/ss/formula/ptg/NamePtg.java | 122 +- .../apache/poi/ss/formula/ptg/NameXPtg.java | 128 +- .../poi/ss/formula/ptg/NotEqualPtg.java | 2 +- .../apache/poi/ss/formula/ptg/NumberPtg.java | 94 +- .../apache/poi/ss/formula/ptg/OperandPtg.java | 24 +- .../poi/ss/formula/ptg/ParenthesisPtg.java | 60 +- .../apache/poi/ss/formula/ptg/PercentPtg.java | 2 +- .../apache/poi/ss/formula/ptg/PowerPtg.java | 2 +- .../org/apache/poi/ss/formula/ptg/Ptg.java | 500 ++++---- .../apache/poi/ss/formula/ptg/RangePtg.java | 2 +- .../poi/ss/formula/ptg/Ref2DPtgBase.java | 52 +- .../apache/poi/ss/formula/ptg/RefNPtg.java | 10 +- .../org/apache/poi/ss/formula/ptg/RefPtg.java | 56 +- .../apache/poi/ss/formula/ptg/RefPtgBase.java | 162 +-- .../poi/ss/formula/ptg/ScalarConstantPtg.java | 14 +- .../apache/poi/ss/formula/ptg/StringPtg.java | 20 +- .../poi/ss/formula/ptg/SubtractPtg.java | 2 +- .../poi/ss/formula/ptg/UnaryMinusPtg.java | 2 +- .../poi/ss/formula/ptg/UnaryPlusPtg.java | 2 +- .../apache/poi/ss/formula/ptg/UnionPtg.java | 2 +- .../poi/ss/formula/ptg/ValueOperatorPtg.java | 48 +- .../poi/ss/formula/udf/IndexedUDFFinder.java | 2 +- .../poi/ss/usermodel/BuiltinFormats.java | 86 +- .../org/apache/poi/ss/usermodel/CellBase.java | 2 +- .../apache/poi/ss/usermodel/CellValue.java | 158 +-- .../poi/ss/usermodel/DataFormatter.java | 6 +- .../poi/ss/usermodel/DataValidation.java | 220 ++-- .../usermodel/DataValidationConstraint.java | 188 +-- .../ss/usermodel/DataValidationHelper.java | 20 +- .../org/apache/poi/ss/usermodel/DateUtil.java | 6 +- .../org/apache/poi/ss/usermodel/Drawing.java | 64 +- .../poi/ss/usermodel/FormulaEvaluator.java | 20 +- .../org/apache/poi/ss/usermodel/Name.java | 2 +- .../usermodel/SheetConditionalFormatting.java | 20 +- .../org/apache/poi/ss/usermodel/Workbook.java | 28 +- .../apache/poi/ss/util/CellRangeAddress.java | 78 +- .../poi/ss/util/CellRangeAddressBase.java | 546 ++++----- .../poi/ss/util/CellRangeAddressList.java | 226 ++-- .../org/apache/poi/ss/util/CellReference.java | 30 +- .../poi/ss/util/DateFormatConverter.java | 326 ++--- .../apache/poi/ss/util/ExpandedDouble.java | 96 +- .../org/apache/poi/ss/util/IEEEDouble.java | 32 +- .../apache/poi/ss/util/MutableFPNumber.java | 322 ++--- .../apache/poi/ss/util/NormalisedDecimal.java | 368 +++--- .../apache/poi/ss/util/NumberComparer.java | 254 ++-- .../poi/ss/util/NumberToTextConverter.java | 270 ++--- .../apache/poi/ss/util/PaneInformation.java | 136 +-- .../org/apache/poi/ss/util/SSCellRange.java | 154 +-- .../org/apache/poi/ss/util/WorkbookUtil.java | 44 +- .../java/org/apache/poi/util/ArrayUtil.java | 78 +- .../java/org/apache/poi/util/ByteField.java | 10 +- .../poi/util/DelayableLittleEndianOutput.java | 8 +- .../LittleEndianByteArrayInputStream.java | 202 ++-- .../LittleEndianByteArrayOutputStream.java | 172 +-- .../apache/poi/util/LittleEndianInput.java | 38 +- .../poi/util/LittleEndianInputStream.java | 268 ++--- .../apache/poi/util/LittleEndianOutput.java | 14 +- .../poi/util/LittleEndianOutputStream.java | 174 +-- .../java/org/apache/poi/POIDataSamples.java | 4 +- .../test/java/org/apache/poi/POITestCase.java | 32 +- .../poi/ddf/TestEscherContainerRecord.java | 348 +++--- .../apache/poi/ddf/TestEscherOptRecord.java | 138 +-- .../poi/ddf/TestUnknownEscherRecord.java | 40 +- .../poi/hpsf/basic/TestEmptyProperties.java | 6 +- .../poi/hpsf/basic/TestMetaDataIPI.java | 848 ++++++------- .../apache/poi/hssf/HSSFTestDataSamples.java | 64 +- .../poi/hssf/dev/BaseTestIteratingXLS.java | 6 +- .../poi/hssf/dev/TestBiffDrawingToXml.java | 6 +- .../apache/poi/hssf/dev/TestEFBiffViewer.java | 40 +- .../poi/hssf/dev/TestFormulaViewer.java | 34 +- .../org/apache/poi/hssf/dev/TestReSave.java | 48 +- .../apache/poi/hssf/dev/TestRecordLister.java | 30 +- .../eventmodel/TestAbortableListener.java | 100 +- .../eventmodel/TestEventRecordFactory.java | 4 +- .../TestFormatTrackingHSSFListener.java | 128 +- .../TestMissingRecordAwareHSSFListener.java | 314 ++--- .../hssf/extractor/TestExcelExtractor.java | 504 ++++---- .../hssf/extractor/TestOldExcelExtractor.java | 32 +- .../poi/hssf/model/TestFormulaParserEval.java | 88 +- .../poi/hssf/model/TestFormulaParserIf.java | 320 ++--- .../apache/poi/hssf/model/TestLinkTable.java | 180 +-- .../org/apache/poi/hssf/model/TestRVA.java | 96 +- .../poi/hssf/model/TestRowBlocksReader.java | 42 +- .../org/apache/poi/hssf/model/TestSheet.java | 984 +++++++-------- .../poi/hssf/model/TestSheetAdditional.java | 72 +- .../apache/poi/hssf/model/TestWorkbook.java | 84 +- .../poi/hssf/record/TestBoolErrRecord.java | 84 +- .../poi/hssf/record/TestBoundSheetRecord.java | 148 +-- .../poi/hssf/record/TestCFHeaderRecord.java | 216 ++-- .../poi/hssf/record/TestColumnInfoRecord.java | 86 +- .../record/TestCommonObjectDataSubRecord.java | 70 +- .../TestEmbeddedObjectRefSubRecord.java | 202 ++-- .../hssf/record/TestExtendedFormatRecord.java | 112 +- .../hssf/record/TestExternalNameRecord.java | 194 +-- .../poi/hssf/record/TestFeatRecord.java | 254 ++-- .../poi/hssf/record/TestFormulaRecord.java | 282 ++--- .../poi/hssf/record/TestHyperlinkRecord.java | 134 +-- .../poi/hssf/record/TestLabelRecord.java | 26 +- .../poi/hssf/record/TestMergeCellsRecord.java | 62 +- .../hssf/record/TestNameCommentRecord.java | 26 +- .../poi/hssf/record/TestNameRecord.java | 122 +- .../poi/hssf/record/TestRecalcIdRecord.java | 64 +- .../poi/hssf/record/TestRecordFactory.java | 346 +++--- .../record/TestRecordFactoryInputStream.java | 164 +-- .../hssf/record/TestRecordInputStream.java | 128 +- .../poi/hssf/record/TestSSTDeserializer.java | 2 +- .../record/TestSSTRecordSizeCalculator.java | 176 +-- .../poi/hssf/record/TestStringRecord.java | 104 +- .../poi/hssf/record/TestStyleRecord.java | 22 +- .../apache/poi/hssf/record/TestSubRecord.java | 204 ++-- .../poi/hssf/record/TestSupBookRecord.java | 58 +- .../poi/hssf/record/TestTableRecord.java | 112 +- .../hssf/record/TestTextObjectBaseRecord.java | 2 +- .../hssf/record/TestUnicodeNameRecord.java | 16 +- .../hssf/record/TestWriteAccessRecord.java | 112 +- .../record/TestcaseRecordInputStream.java | 112 +- .../TestColumnInfoRecordsAggregate.java | 158 +-- .../TestFormulaRecordAggregate.java | 100 +- .../aggregates/TestPageSettingsBlock.java | 396 +++--- .../aggregates/TestRowRecordsAggregate.java | 182 +-- .../aggregates/TestSharedValueManager.java | 186 +-- .../aggregates/TestValueRecordsAggregate.java | 588 ++++----- .../poi/hssf/record/cf/TestCellRange.java | 278 ++--- .../record/chart/TestChartFormatRecord.java | 44 +- .../chart/TestChartTitleFormatRecord.java | 66 +- .../hssf/record/chart/TestLegendRecord.java | 72 +- .../record/chart/TestLinkedDataRecord.java | 2 +- .../record/chart/TestObjectLinkRecord.java | 2 +- .../record/chart/TestSeriesIndexRecord.java | 2 +- .../record/chart/TestSeriesTextRecord.java | 104 +- ...estExtendedPivotTableViewFieldsRecord.java | 42 +- .../hssf/record/pivot/TestPageItemRecord.java | 48 +- .../record/pivot/TestViewFieldsRecord.java | 52 +- .../poi/hssf/usermodel/FormulaExtractor.java | 22 +- .../usermodel/HSSFEvaluationTestHelper.java | 6 +- .../poi/hssf/usermodel/HSSFTestHelper.java | 18 +- .../poi/hssf/usermodel/StreamUtility.java | 182 +-- .../poi/hssf/usermodel/TestBug42464.java | 90 +- .../poi/hssf/usermodel/TestCellStyle.java | 4 +- .../hssf/usermodel/TestDataValidation.java | 176 +-- .../hssf/usermodel/TestEscherGraphics.java | 296 ++--- .../hssf/usermodel/TestEscherGraphics2d.java | 162 +-- .../TestExternalReferenceChange.java | 50 +- .../usermodel/TestFormulaEvaluatorDocs.java | 150 +-- .../poi/hssf/usermodel/TestHSSFCell.java | 574 ++++----- .../poi/hssf/usermodel/TestHSSFChart.java | 160 +-- .../usermodel/TestHSSFExternalFunctions.java | 6 +- .../usermodel/TestHSSFFormulaEvaluator.java | 194 +-- .../hssf/usermodel/TestHSSFHeaderFooter.java | 276 ++--- .../poi/hssf/usermodel/TestHSSFPalette.java | 24 +- .../poi/hssf/usermodel/TestHSSFPatriarch.java | 56 +- .../poi/hssf/usermodel/TestHSSFPicture.java | 2 +- .../hssf/usermodel/TestHSSFPictureData.java | 12 +- .../poi/hssf/usermodel/TestHSSFWorkbook.java | 168 +-- .../TestNonStandardWorkbookStreamNames.java | 62 +- .../poi/hssf/usermodel/TestOLE2Embeding.java | 10 +- .../poi/hssf/usermodel/TestSanityChecker.java | 154 +-- .../poi/hssf/usermodel/TestWorkbook.java | 4 +- .../apache/poi/hssf/util/TestHSSFColor.java | 44 +- .../org/apache/poi/hssf/util/TestRKUtil.java | 36 +- .../crypt/TestBiff8DecryptingStream.java | 258 ++-- .../poifs/filesystem/TestEmptyDocument.java | 124 +- .../filesystem/TestNotOLE2Exception.java | 12 +- .../poifs/filesystem/TestPOIFSFileSystem.java | 518 ++++---- .../poifs/property/TestPropertyFactory.java | 226 ++-- .../poi/poifs/property/TestPropertyTable.java | 240 ++-- .../poi/poifs/property/TestRootProperty.java | 146 +-- .../apache/poi/poifs/storage/RawDataUtil.java | 18 +- .../poifs/storage/TestHeaderBlockReading.java | 70 +- .../ss/formula/BaseTestMissingWorkbook.java | 138 +-- .../poi/ss/formula/EvaluationListener.java | 56 +- .../poi/ss/formula/TestCellCacheEntry.java | 20 +- .../poi/ss/formula/TestEvaluationCache.java | 1064 ++++++++--------- .../poi/ss/formula/TestFunctionRegistry.java | 6 +- .../ss/formula/TestSheetNameFormatter.java | 258 ++-- .../formula/WorkbookEvaluatorTestHelper.java | 12 +- .../apache/poi/ss/formula/atp/TestMRound.java | 8 +- .../poi/ss/formula/atp/TestRandBetween.java | 274 ++--- .../ss/formula/atp/TestWorkdayCalculator.java | 34 +- .../ss/formula/atp/TestWorkdayFunction.java | 6 +- .../formula/atp/TestYearFracCalculator.java | 56 +- ...TestYearFracCalculatorFromSpreadsheet.java | 106 +- .../constant/TestConstantValueParser.java | 78 +- .../poi/ss/formula/eval/EvalInstances.java | 38 +- .../poi/ss/formula/eval/TestAreaEval.java | 52 +- .../poi/ss/formula/eval/TestDivideEval.java | 58 +- .../poi/ss/formula/eval/TestEqualEval.java | 226 ++-- .../ss/formula/eval/TestExternalFunction.java | 74 +- .../poi/ss/formula/eval/TestFormulaBugs.java | 350 +++--- .../eval/TestFormulasFromSpreadsheet.java | 92 +- .../eval/TestHSSFCircularReferences.java | 2 +- .../ss/formula/eval/TestMinusZeroResult.java | 184 +-- .../ss/formula/eval/TestMissingArgEval.java | 122 +- .../ss/formula/eval/TestMultiSheetEval.java | 242 ++-- .../ss/formula/eval/TestOperandResolver.java | 116 +- .../poi/ss/formula/eval/TestPercentEval.java | 70 +- .../poi/ss/formula/eval/TestRangeEval.java | 188 +-- .../ss/formula/eval/TestUnaryPlusEval.java | 46 +- .../eval/forked/BaseTestForkedEvaluator.java | 134 +-- .../function/ExcelCetabFunctionExtractor.java | 584 ++++----- .../ExcelFileFormatDocFunctionExtractor.java | 976 +++++++-------- .../TestFunctionMetadataRegistry.java | 28 +- .../TestParseMissingBuiltInFuncs.java | 110 +- .../function/TestReadMissingBuiltInFuncs.java | 182 +-- .../poi/ss/formula/functions/EvalFactory.java | 262 ++-- .../functions/NumericFunctionInvoker.java | 130 +- .../poi/ss/formula/functions/TestAddress.java | 2 +- .../poi/ss/formula/functions/TestAverage.java | 112 +- .../poi/ss/formula/functions/TestBin2Dec.java | 24 +- .../functions/TestCalendarFieldFunction.java | 20 +- .../ss/formula/functions/TestCountFuncs.java | 748 ++++++------ .../poi/ss/formula/functions/TestDec2Bin.java | 24 +- .../poi/ss/formula/functions/TestDec2Hex.java | 54 +- .../poi/ss/formula/functions/TestDelta.java | 30 +- .../poi/ss/formula/functions/TestFind.java | 72 +- .../poi/ss/formula/functions/TestHex2Dec.java | 24 +- .../poi/ss/formula/functions/TestIndex.java | 476 ++++---- .../ss/formula/functions/TestIntercept.java | 188 +-- .../ss/formula/functions/TestLeftRight.java | 40 +- .../poi/ss/formula/functions/TestLen.java | 66 +- .../poi/ss/formula/functions/TestMatch.java | 294 ++--- .../poi/ss/formula/functions/TestMid.java | 120 +- .../poi/ss/formula/functions/TestNper.java | 50 +- .../poi/ss/formula/functions/TestOct2Dec.java | 32 +- .../poi/ss/formula/functions/TestOffset.java | 104 +- .../poi/ss/formula/functions/TestPmt.java | 88 +- .../poi/ss/formula/functions/TestPoisson.java | 2 +- .../ss/formula/functions/TestRoundFuncs.java | 68 +- .../poi/ss/formula/functions/TestRowCol.java | 116 +- .../poi/ss/formula/functions/TestSlope.java | 186 +-- .../ss/formula/functions/TestStatsLib.java | 26 +- .../ss/formula/functions/TestSubtotal.java | 68 +- .../poi/ss/formula/functions/TestSumif.java | 122 +- .../poi/ss/formula/functions/TestSumifs.java | 34 +- .../ss/formula/functions/TestSumproduct.java | 142 +-- .../poi/ss/formula/functions/TestTFunc.java | 162 +-- .../poi/ss/formula/functions/TestTime.java | 144 +-- .../poi/ss/formula/functions/TestTrim.java | 76 +- .../poi/ss/formula/functions/TestValue.java | 114 +- .../functions/TestXYNumericFunction.java | 184 +-- .../poi/ss/formula/ptg/TestArea3DPtg.java | 32 +- .../poi/ss/formula/ptg/TestAreaPtg.java | 142 +-- .../poi/ss/formula/ptg/TestArrayPtg.java | 194 +-- .../poi/ss/formula/ptg/TestAttrPtg.java | 26 +- .../ptg/TestExternalFunctionFormulas.java | 96 +- .../ptg/TestExternalNameReference.java | 182 +-- .../poi/ss/formula/ptg/TestFuncPtg.java | 2 +- .../poi/ss/formula/ptg/TestFuncVarPtg.java | 52 +- .../poi/ss/formula/ptg/TestRef3DPtg.java | 24 +- .../poi/ss/formula/ptg/TestReferencePtg.java | 4 +- .../poi/ss/formula/udf/TestUDFFinder.java | 2 +- .../ss/usermodel/BaseTestDataValidation.java | 4 +- .../usermodel/BaseTestFormulaEvaluator.java | 28 +- .../poi/ss/usermodel/BaseTestSheetHiding.java | 30 +- .../poi/ss/usermodel/BaseTestWorkbook.java | 20 +- .../NumberRenderingSpreadsheetGenerator.java | 326 ++--- .../util/NumberToTextConversionExamples.java | 420 +++---- .../poi/ss/util/TestExpandedDouble.java | 164 +-- .../poi/ss/util/TestNumberComparer.java | 104 +- .../ss/util/TestNumberToTextConverter.java | 114 +- .../org/apache/poi/ss/util/TestSheetUtil.java | 4 +- .../apache/poi/ss/util/TestWorkbookUtil.java | 84 +- .../poi/ss/util/cellwalk/TestCellWalk.java | 10 +- .../apache/poi/util/MemoryLeakVerifier.java | 112 +- .../org/apache/poi/util/TestArrayUtil.java | 108 +- .../java/org/apache/poi/util/TestHexDump.java | 2 +- .../java/org/apache/poi/util/TestIOUtils.java | 2 +- .../org/apache/poi/util/TestLittleEndian.java | 4 +- .../poi/util/TestLittleEndianStreams.java | 136 +-- 620 files changed, 37423 insertions(+), 37423 deletions(-) diff --git a/poi/src/main/java/org/apache/poi/EmptyFileException.java b/poi/src/main/java/org/apache/poi/EmptyFileException.java index 5abbcd0fe6..837bea7fb7 100644 --- a/poi/src/main/java/org/apache/poi/EmptyFileException.java +++ b/poi/src/main/java/org/apache/poi/EmptyFileException.java @@ -25,12 +25,12 @@ public class EmptyFileException extends IllegalArgumentException { private static final long serialVersionUID = 1536449292174360166L; public EmptyFileException() { - super("The supplied file was empty (zero bytes long)"); - } + super("The supplied file was empty (zero bytes long)"); + } public EmptyFileException(File file) { - super(file.exists() ? - "The supplied file '" + file.getAbsolutePath() + "' was empty (zero bytes long)" : - "The file '" + file.getAbsolutePath() + "' does not exist"); - } + super(file.exists() ? + "The supplied file '" + file.getAbsolutePath() + "' was empty (zero bytes long)" : + "The file '" + file.getAbsolutePath() + "' does not exist"); + } } \ No newline at end of file diff --git a/poi/src/main/java/org/apache/poi/EncryptedDocumentException.java b/poi/src/main/java/org/apache/poi/EncryptedDocumentException.java index 4ac6123e4b..24110fb3ec 100644 --- a/poi/src/main/java/org/apache/poi/EncryptedDocumentException.java +++ b/poi/src/main/java/org/apache/poi/EncryptedDocumentException.java @@ -20,9 +20,9 @@ public class EncryptedDocumentException extends IllegalStateException { private static final long serialVersionUID = 7276950444540469193L; - public EncryptedDocumentException(String s) { - super(s); - } + public EncryptedDocumentException(String s) { + super(s); + } public EncryptedDocumentException(String message, Throwable cause) { super(message, cause); diff --git a/poi/src/main/java/org/apache/poi/OldFileFormatException.java b/poi/src/main/java/org/apache/poi/OldFileFormatException.java index 3c01f5459e..b84fe64602 100644 --- a/poi/src/main/java/org/apache/poi/OldFileFormatException.java +++ b/poi/src/main/java/org/apache/poi/OldFileFormatException.java @@ -24,6 +24,6 @@ public abstract class OldFileFormatException extends UnsupportedFileFormatExcept private static final long serialVersionUID = 7849681804154571175L; public OldFileFormatException(String s) { - super(s); - } + super(s); + } } \ No newline at end of file diff --git a/poi/src/main/java/org/apache/poi/POIDocument.java b/poi/src/main/java/org/apache/poi/POIDocument.java index e1405f9977..6c6aacd6e1 100644 --- a/poi/src/main/java/org/apache/poi/POIDocument.java +++ b/poi/src/main/java/org/apache/poi/POIDocument.java @@ -58,7 +58,7 @@ public abstract class POIDocument implements Closeable { private SummaryInformation sInf; /** Holds further metadata on our document */ private DocumentSummaryInformation dsInf; - /** The directory that our document lives in */ + /** The directory that our document lives in */ private DirectoryNode directory; /** For our own logging use */ @@ -73,7 +73,7 @@ public abstract class POIDocument implements Closeable { * @param dir The {@link DirectoryNode} where information is read from. */ protected POIDocument(DirectoryNode dir) { - this.directory = dir; + this.directory = dir; } /** diff --git a/poi/src/main/java/org/apache/poi/UnsupportedFileFormatException.java b/poi/src/main/java/org/apache/poi/UnsupportedFileFormatException.java index b893639514..84448b2dda 100644 --- a/poi/src/main/java/org/apache/poi/UnsupportedFileFormatException.java +++ b/poi/src/main/java/org/apache/poi/UnsupportedFileFormatException.java @@ -24,8 +24,8 @@ public abstract class UnsupportedFileFormatException extends IllegalArgumentExce private static final long serialVersionUID = -8281969197282030046L; protected UnsupportedFileFormatException(String s) { - super(s); - } + super(s); + } protected UnsupportedFileFormatException(String message, Throwable cause) { super(message, cause); diff --git a/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java b/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java index 75062a7005..77aff5febc 100644 --- a/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java +++ b/poi/src/main/java/org/apache/poi/ddf/EscherMetafileBlip.java @@ -388,7 +388,7 @@ public final class EscherMetafileBlip extends EscherBlipRecord { @Override public void setPictureData(byte[] pictureData) { - super.setPictureData(pictureData); + super.setPictureData(pictureData); setUncompressedSize(pictureData.length); // info of chicago project: @@ -396,12 +396,12 @@ public final class EscherMetafileBlip extends EscherBlipRecord { // not sure what to do, when lookup tables exceed 32k ... try (UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream()) { - try (DeflaterOutputStream dos = new DeflaterOutputStream(bos)) { + try (DeflaterOutputStream dos = new DeflaterOutputStream(bos)) { dos.write(pictureData); } - raw_pictureData = bos.toByteArray(); + raw_pictureData = bos.toByteArray(); } catch (IOException e) { - throw new RuntimeException("Can't compress metafile picture data", e); + throw new RuntimeException("Can't compress metafile picture data", e); } setCompressedSize(raw_pictureData.length); diff --git a/poi/src/main/java/org/apache/poi/ddf/UnknownEscherRecord.java b/poi/src/main/java/org/apache/poi/ddf/UnknownEscherRecord.java index 83de70c836..e3b2b8c5c0 100644 --- a/poi/src/main/java/org/apache/poi/ddf/UnknownEscherRecord.java +++ b/poi/src/main/java/org/apache/poi/ddf/UnknownEscherRecord.java @@ -52,14 +52,14 @@ public final class UnknownEscherRecord extends EscherRecord { @Override public int fillFields(byte[] data, int offset, EscherRecordFactory recordFactory) { int bytesRemaining = readHeader( data, offset ); - /* - * Have a check between available bytes and bytesRemaining, - * take the available length if the bytesRemaining out of range. - */ - int available = data.length - (offset + 8); - if (bytesRemaining > available) { - bytesRemaining = available; - } + /* + * Have a check between available bytes and bytesRemaining, + * take the available length if the bytesRemaining out of range. + */ + int available = data.length - (offset + 8); + if (bytesRemaining > available) { + bytesRemaining = available; + } if (isContainerRecord()) { int bytesWritten = 0; diff --git a/poi/src/main/java/org/apache/poi/extractor/POIOLE2TextExtractor.java b/poi/src/main/java/org/apache/poi/extractor/POIOLE2TextExtractor.java index a389b71d0c..d483c9d7a2 100644 --- a/poi/src/main/java/org/apache/poi/extractor/POIOLE2TextExtractor.java +++ b/poi/src/main/java/org/apache/poi/extractor/POIOLE2TextExtractor.java @@ -34,42 +34,42 @@ import org.apache.poi.poifs.filesystem.DirectoryEntry; * @see org.apache.poi.hwpf.extractor.WordExtractor */ public interface POIOLE2TextExtractor extends POITextExtractor { - /** - * Returns the document information metadata for the document - * + /** + * Returns the document information metadata for the document + * * @return The Document Summary Information or null * if it could not be read for this document. - */ - default DocumentSummaryInformation getDocSummaryInformation() { - return getDocument().getDocumentSummaryInformation(); - } + */ + default DocumentSummaryInformation getDocSummaryInformation() { + return getDocument().getDocumentSummaryInformation(); + } - /** - * Returns the summary information metadata for the document. - * + /** + * Returns the summary information metadata for the document. + * * @return The Summary information for the document or null * if it could not be read for this document. - */ - default SummaryInformation getSummaryInformation() { - return getDocument().getSummaryInformation(); - } + */ + default SummaryInformation getSummaryInformation() { + return getDocument().getSummaryInformation(); + } - /** - * Returns an HPSF powered text extractor for the - * document properties metadata, such as title and author. - * - * @return an instance of POIExtractor that can extract meta-data. - */ - @Override + /** + * Returns an HPSF powered text extractor for the + * document properties metadata, such as title and author. + * + * @return an instance of POIExtractor that can extract meta-data. + */ + @Override default POITextExtractor getMetadataTextExtractor() { - return new HPSFPropertiesExtractor(this); - } + return new HPSFPropertiesExtractor(this); + } - /** - * Return the underlying DirectoryEntry of this document. - * - * @return the DirectoryEntry that is associated with the POIDocument of this extractor. - */ + /** + * Return the underlying DirectoryEntry of this document. + * + * @return the DirectoryEntry that is associated with the POIDocument of this extractor. + */ default DirectoryEntry getRoot() { return getDocument().getDirectory(); } diff --git a/poi/src/main/java/org/apache/poi/extractor/POITextExtractor.java b/poi/src/main/java/org/apache/poi/extractor/POITextExtractor.java index cf88c57bae..4c36c37fc8 100644 --- a/poi/src/main/java/org/apache/poi/extractor/POITextExtractor.java +++ b/poi/src/main/java/org/apache/poi/extractor/POITextExtractor.java @@ -31,57 +31,57 @@ import java.io.IOException; * @see org.apache.poi.hwpf.extractor.WordExtractor */ public interface POITextExtractor extends Closeable { - /** - * Retrieves all the text from the document. - * How cells, paragraphs etc are separated in the text - * is implementation specific - see the javadocs for - * a specific project for details. - * @return All the text from the document - */ - String getText(); + /** + * Retrieves all the text from the document. + * How cells, paragraphs etc are separated in the text + * is implementation specific - see the javadocs for + * a specific project for details. + * @return All the text from the document + */ + String getText(); - /** - * Returns another text extractor, which is able to - * output the textual content of the document - * metadata / properties, such as author and title. - * - * @return the metadata and text extractor - */ - POITextExtractor getMetadataTextExtractor(); + /** + * Returns another text extractor, which is able to + * output the textual content of the document + * metadata / properties, such as author and title. + * + * @return the metadata and text extractor + */ + POITextExtractor getMetadataTextExtractor(); - /** - * @param doCloseFilesystem {@code true} (default), if underlying resources/filesystem should be - * closed on {@link #close()} - */ - void setCloseFilesystem(boolean doCloseFilesystem); + /** + * @param doCloseFilesystem {@code true} (default), if underlying resources/filesystem should be + * closed on {@link #close()} + */ + void setCloseFilesystem(boolean doCloseFilesystem); - /** - * @return {@code true}, if resources/filesystem should be closed on {@link #close()} - */ - boolean isCloseFilesystem(); + /** + * @return {@code true}, if resources/filesystem should be closed on {@link #close()} + */ + boolean isCloseFilesystem(); - /** - * @return The underlying resources/filesystem - */ - Closeable getFilesystem(); + /** + * @return The underlying resources/filesystem + */ + Closeable getFilesystem(); - /** - * Allows to free resources of the Extractor as soon as - * it is not needed any more. This may include closing - * open file handles and freeing memory. - * - * The Extractor cannot be used after close has been called. - */ - @Override + /** + * Allows to free resources of the Extractor as soon as + * it is not needed any more. This may include closing + * open file handles and freeing memory. + * + * The Extractor cannot be used after close has been called. + */ + @Override default void close() throws IOException { - Closeable fs = getFilesystem(); - if (isCloseFilesystem() && fs != null) { - fs.close(); - } - } + Closeable fs = getFilesystem(); + if (isCloseFilesystem() && fs != null) { + fs.close(); + } + } - /** - * @return the processed document - */ - Object getDocument(); + /** + * @return the processed document + */ + Object getDocument(); } diff --git a/poi/src/main/java/org/apache/poi/hpsf/ClassID.java b/poi/src/main/java/org/apache/poi/hpsf/ClassID.java index 42a960a4c7..f2c76c6c1d 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/ClassID.java +++ b/poi/src/main/java/org/apache/poi/hpsf/ClassID.java @@ -83,7 +83,7 @@ public class ClassID implements Duplicatable, GenericRecord { public ClassID(String externalForm) { String clsStr = externalForm.replaceAll("[{}-]", ""); for (int i=0; iThe underlying reason for this exception - may be + private static final long serialVersionUID = -7804271670232727159L; + /**

The underlying reason for this exception - may be * null.

*/ private Throwable reason; diff --git a/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java b/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java index 564146a94a..6b3bc861ff 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java +++ b/poi/src/main/java/org/apache/poi/hpsf/SummaryInformation.java @@ -46,7 +46,7 @@ public final class SummaryInformation extends PropertySet { @Override public PropertyIDMap getPropertySetIDMap() { - return PropertyIDMap.getSummaryInformationProperties(); + return PropertyIDMap.getSummaryInformationProperties(); } /** diff --git a/poi/src/main/java/org/apache/poi/hpsf/VariantSupport.java b/poi/src/main/java/org/apache/poi/hpsf/VariantSupport.java index 5d49c8a28e..43f59357c7 100644 --- a/poi/src/main/java/org/apache/poi/hpsf/VariantSupport.java +++ b/poi/src/main/java/org/apache/poi/hpsf/VariantSupport.java @@ -114,7 +114,7 @@ public class VariantSupport extends Variant { Long vt = Long.valueOf(ex.getVariantType()); if (!unsupportedMessage.contains(vt)) { - LOG.atError().withThrowable(ex).log("Unsupported type"); + LOG.atError().withThrowable(ex).log("Unsupported type"); unsupportedMessage.add(vt); } } diff --git a/poi/src/main/java/org/apache/poi/hssf/OldExcelFormatException.java b/poi/src/main/java/org/apache/poi/hssf/OldExcelFormatException.java index e42e613d84..fb5e3ea7a7 100644 --- a/poi/src/main/java/org/apache/poi/hssf/OldExcelFormatException.java +++ b/poi/src/main/java/org/apache/poi/hssf/OldExcelFormatException.java @@ -19,7 +19,7 @@ package org.apache.poi.hssf; import org.apache.poi.OldFileFormatException; public class OldExcelFormatException extends OldFileFormatException { - public OldExcelFormatException(String s) { - super(s); - } + public OldExcelFormatException(String s) { + super(s); + } } \ No newline at end of file diff --git a/poi/src/main/java/org/apache/poi/hssf/dev/BiffViewer.java b/poi/src/main/java/org/apache/poi/hssf/dev/BiffViewer.java index 1f15da7578..006194d0be 100644 --- a/poi/src/main/java/org/apache/poi/hssf/dev/BiffViewer.java +++ b/poi/src/main/java/org/apache/poi/hssf/dev/BiffViewer.java @@ -371,33 +371,33 @@ public final class BiffViewer { } } - /** - * Method main with 1 argument just run straight biffview against given - * file

- * - * Usage:

- * - * BiffViewer [--biffhex] [--noint] [--noescher] [--out] <fileName>

- * BiffViewer --rawhex [--out] <fileName> - * - * + /** + * Method main with 1 argument just run straight biffview against given + * file

+ * + * Usage:

+ * + * BiffViewer [--biffhex] [--noint] [--noescher] [--out] <fileName>

+ * BiffViewer --rawhex [--out] <fileName> + * + *

* - * - * - * - * - * - * - *
BiffViewer options
--biffhexshow hex dump of each BIFF record
--nointdo not output interpretation of BIFF records
--outsend output to <fileName>.out
--rawhexoutput raw hex dump of whole workbook stream
--escherturn on deserialization of escher records (default is off)
--noheaderdo not print record header (default is on)
- * - * @param args the command line arguments - * - * @throws IOException if the file doesn't exist or contained errors - * @throws CommandParseException if the command line contained errors - */ - public static void main(String[] args) throws IOException, CommandParseException { - // args = new String[] { "--out", "", }; - CommandArgs cmdArgs = CommandArgs.parse(args); + * --biffhexshow hex dump of each BIFF record + * --nointdo not output interpretation of BIFF records + * --outsend output to <fileName>.out + * --rawhexoutput raw hex dump of whole workbook stream + * --escherturn on deserialization of escher records (default is off) + * --noheaderdo not print record header (default is on) + * + * + * @param args the command line arguments + * + * @throws IOException if the file doesn't exist or contained errors + * @throws CommandParseException if the command line contained errors + */ + public static void main(String[] args) throws IOException, CommandParseException { + // args = new String[] { "--out", "", }; + CommandArgs cmdArgs = CommandArgs.parse(args); try (POIFSFileSystem fs = new POIFSFileSystem(cmdArgs.getFile(), true); InputStream is = getPOIFSInputStream(fs); @@ -413,9 +413,9 @@ public final class BiffViewer { cmdArgs.suppressHeader()); } } - } + } - static PrintWriter getOutputStream(String outputPath) throws FileNotFoundException { + static PrintWriter getOutputStream(String outputPath) throws FileNotFoundException { // Use the system default encoding when sending to System Out OutputStream os = System.out; Charset cs = Charset.defaultCharset(); @@ -427,287 +427,287 @@ public final class BiffViewer { } - static InputStream getPOIFSInputStream(POIFSFileSystem fs) throws IOException { - String workbookName = HSSFWorkbook.getWorkbookDirEntryName(fs.getRoot()); - return fs.createDocumentInputStream(workbookName); - } + static InputStream getPOIFSInputStream(POIFSFileSystem fs) throws IOException { + String workbookName = HSSFWorkbook.getWorkbookDirEntryName(fs.getRoot()); + return fs.createDocumentInputStream(workbookName); + } - static void runBiffViewer(PrintWriter pw, InputStream is, - boolean dumpInterpretedRecords, boolean dumpHex, boolean zeroAlignHexDump, - boolean suppressHeader) { - BiffRecordListener recListener = new BiffRecordListener(dumpHex ? pw : null, zeroAlignHexDump, suppressHeader); - is = new BiffDumpingStream(is, recListener); - createRecords(is, pw, recListener, dumpInterpretedRecords); - } + static void runBiffViewer(PrintWriter pw, InputStream is, + boolean dumpInterpretedRecords, boolean dumpHex, boolean zeroAlignHexDump, + boolean suppressHeader) { + BiffRecordListener recListener = new BiffRecordListener(dumpHex ? pw : null, zeroAlignHexDump, suppressHeader); + is = new BiffDumpingStream(is, recListener); + createRecords(is, pw, recListener, dumpInterpretedRecords); + } - private static final class BiffRecordListener implements IBiffRecordListener { - private final Writer _hexDumpWriter; - private List _headers; - private final boolean _zeroAlignEachRecord; - private final boolean _noHeader; - private BiffRecordListener(Writer hexDumpWriter, boolean zeroAlignEachRecord, boolean noHeader) { - _hexDumpWriter = hexDumpWriter; - _zeroAlignEachRecord = zeroAlignEachRecord; - _noHeader = noHeader; - _headers = new ArrayList<>(); - } + private static final class BiffRecordListener implements IBiffRecordListener { + private final Writer _hexDumpWriter; + private List _headers; + private final boolean _zeroAlignEachRecord; + private final boolean _noHeader; + private BiffRecordListener(Writer hexDumpWriter, boolean zeroAlignEachRecord, boolean noHeader) { + _hexDumpWriter = hexDumpWriter; + _zeroAlignEachRecord = zeroAlignEachRecord; + _noHeader = noHeader; + _headers = new ArrayList<>(); + } - @Override + @Override public void processRecord(int globalOffset, int recordCounter, int sid, int dataSize, - byte[] data) { - String header = formatRecordDetails(globalOffset, sid, dataSize, recordCounter); - if(!_noHeader) { - _headers.add(header); - } - Writer w = _hexDumpWriter; - if (w != null) { - try { - w.write(header); - w.write(NEW_LINE_CHARS); - hexDumpAligned(w, data, dataSize+4, globalOffset, _zeroAlignEachRecord); - w.flush(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - private List getRecentHeaders() { - List result = _headers; - _headers = new ArrayList<>(); - return result; - } - private static String formatRecordDetails(int globalOffset, int sid, int size, int recordCounter) { + byte[] data) { + String header = formatRecordDetails(globalOffset, sid, dataSize, recordCounter); + if(!_noHeader) { + _headers.add(header); + } + Writer w = _hexDumpWriter; + if (w != null) { + try { + w.write(header); + w.write(NEW_LINE_CHARS); + hexDumpAligned(w, data, dataSize+4, globalOffset, _zeroAlignEachRecord); + w.flush(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + } + private List getRecentHeaders() { + List result = _headers; + _headers = new ArrayList<>(); + return result; + } + private static String formatRecordDetails(int globalOffset, int sid, int size, int recordCounter) { return "Offset=" + HexDump.intToHex(globalOffset) + "(" + globalOffset + ")" + " recno=" + recordCounter + " sid=" + HexDump.shortToHex(sid) + " size=" + HexDump.shortToHex(size) + "(" + size + ")"; - } - } + } + } - private interface IBiffRecordListener { + private interface IBiffRecordListener { - void processRecord(int globalOffset, int recordCounter, int sid, int dataSize, byte[] data); + void processRecord(int globalOffset, int recordCounter, int sid, int dataSize, byte[] data); - } + } - /** - * Wraps a plain {@link InputStream} and allows BIFF record information to be tapped off - * - */ - private static final class BiffDumpingStream extends InputStream { - private final DataInputStream _is; - private final IBiffRecordListener _listener; - private final byte[] _data; - private int _recordCounter; - private int _overallStreamPos; - private int _currentPos; - private int _currentSize; - private boolean _innerHasReachedEOF; + /** + * Wraps a plain {@link InputStream} and allows BIFF record information to be tapped off + * + */ + private static final class BiffDumpingStream extends InputStream { + private final DataInputStream _is; + private final IBiffRecordListener _listener; + private final byte[] _data; + private int _recordCounter; + private int _overallStreamPos; + private int _currentPos; + private int _currentSize; + private boolean _innerHasReachedEOF; - private BiffDumpingStream(InputStream is, IBiffRecordListener listener) { - _is = new DataInputStream(is); - _listener = listener; - _data = new byte[RecordInputStream.MAX_RECORD_DATA_SIZE + 4]; - _recordCounter = 0; - _overallStreamPos = 0; - _currentSize = 0; - _currentPos = 0; - } + private BiffDumpingStream(InputStream is, IBiffRecordListener listener) { + _is = new DataInputStream(is); + _listener = listener; + _data = new byte[RecordInputStream.MAX_RECORD_DATA_SIZE + 4]; + _recordCounter = 0; + _overallStreamPos = 0; + _currentSize = 0; + _currentPos = 0; + } - @Override - public int read() throws IOException { - if (_currentPos >= _currentSize) { - fillNextBuffer(); - } - if (_currentPos >= _currentSize) { - return -1; - } - int result = _data[_currentPos] & 0x00FF; - _currentPos ++; - _overallStreamPos ++; - formatBufferIfAtEndOfRec(); - return result; - } - @Override - public int read(byte[] b, int off, int len) throws IOException { + @Override + public int read() throws IOException { + if (_currentPos >= _currentSize) { + fillNextBuffer(); + } + if (_currentPos >= _currentSize) { + return -1; + } + int result = _data[_currentPos] & 0x00FF; + _currentPos ++; + _overallStreamPos ++; + formatBufferIfAtEndOfRec(); + return result; + } + @Override + public int read(byte[] b, int off, int len) throws IOException { if (b == null || off < 0 || len < 0 || b.length < off+len) { throw new IllegalArgumentException(); } - if (_currentPos >= _currentSize) { - fillNextBuffer(); - } - if (_currentPos >= _currentSize) { - return -1; - } - final int result = Math.min(len, _currentSize - _currentPos); - System.arraycopy(_data, _currentPos, b, off, result); - _currentPos += result; - _overallStreamPos += result; - formatBufferIfAtEndOfRec(); - return result; - } + if (_currentPos >= _currentSize) { + fillNextBuffer(); + } + if (_currentPos >= _currentSize) { + return -1; + } + final int result = Math.min(len, _currentSize - _currentPos); + System.arraycopy(_data, _currentPos, b, off, result); + _currentPos += result; + _overallStreamPos += result; + formatBufferIfAtEndOfRec(); + return result; + } - @Override - @SuppressForbidden("just delegating the call") - public int available() throws IOException { - return _currentSize - _currentPos + _is.available(); - } - private void fillNextBuffer() throws IOException { - if (_innerHasReachedEOF) { - return; - } - int b0 = _is.read(); - if (b0 == -1) { - _innerHasReachedEOF = true; - return; - } - _data[0] = (byte) b0; - _is.readFully(_data, 1, 3); - int len = LittleEndian.getShort(_data, 2); - _is.readFully(_data, 4, len); - _currentPos = 0; - _currentSize = len + 4; - _recordCounter++; - } - private void formatBufferIfAtEndOfRec() { - if (_currentPos != _currentSize) { - return; - } - int dataSize = _currentSize-4; - int sid = LittleEndian.getShort(_data, 0); - int globalOffset = _overallStreamPos-_currentSize; - _listener.processRecord(globalOffset, _recordCounter, sid, dataSize, _data); - } - @Override - public void close() throws IOException { - _is.close(); - } - } + @Override + @SuppressForbidden("just delegating the call") + public int available() throws IOException { + return _currentSize - _currentPos + _is.available(); + } + private void fillNextBuffer() throws IOException { + if (_innerHasReachedEOF) { + return; + } + int b0 = _is.read(); + if (b0 == -1) { + _innerHasReachedEOF = true; + return; + } + _data[0] = (byte) b0; + _is.readFully(_data, 1, 3); + int len = LittleEndian.getShort(_data, 2); + _is.readFully(_data, 4, len); + _currentPos = 0; + _currentSize = len + 4; + _recordCounter++; + } + private void formatBufferIfAtEndOfRec() { + if (_currentPos != _currentSize) { + return; + } + int dataSize = _currentSize-4; + int sid = LittleEndian.getShort(_data, 0); + int globalOffset = _overallStreamPos-_currentSize; + _listener.processRecord(globalOffset, _recordCounter, sid, dataSize, _data); + } + @Override + public void close() throws IOException { + _is.close(); + } + } - private static final int DUMP_LINE_LEN = 16; - private static final char[] COLUMN_SEPARATOR = " | ".toCharArray(); - /** - * Hex-dumps a portion of a byte array in typical format, also preserving dump-line alignment - * @param globalOffset (somewhat arbitrary) used to calculate the addresses printed at the - * start of each line - */ - private static void hexDumpAligned(Writer w, byte[] data, int dumpLen, int globalOffset, - boolean zeroAlignEachRecord) { - int baseDataOffset = 0; + private static final int DUMP_LINE_LEN = 16; + private static final char[] COLUMN_SEPARATOR = " | ".toCharArray(); + /** + * Hex-dumps a portion of a byte array in typical format, also preserving dump-line alignment + * @param globalOffset (somewhat arbitrary) used to calculate the addresses printed at the + * start of each line + */ + private static void hexDumpAligned(Writer w, byte[] data, int dumpLen, int globalOffset, + boolean zeroAlignEachRecord) { + int baseDataOffset = 0; - // perhaps this code should be moved to HexDump - int globalStart = globalOffset + baseDataOffset; - int globalEnd = globalOffset + baseDataOffset + dumpLen; - int startDelta = globalStart % DUMP_LINE_LEN; - int endDelta = globalEnd % DUMP_LINE_LEN; - if (zeroAlignEachRecord) { - endDelta -= startDelta; - if (endDelta < 0) { - endDelta += DUMP_LINE_LEN; - } - startDelta = 0; - } - int startLineAddr; - int endLineAddr; - if (zeroAlignEachRecord) { - endLineAddr = globalEnd - endDelta - (globalStart - startDelta); - startLineAddr = 0; - } else { - startLineAddr = globalStart - startDelta; - endLineAddr = globalEnd - endDelta; - } + // perhaps this code should be moved to HexDump + int globalStart = globalOffset + baseDataOffset; + int globalEnd = globalOffset + baseDataOffset + dumpLen; + int startDelta = globalStart % DUMP_LINE_LEN; + int endDelta = globalEnd % DUMP_LINE_LEN; + if (zeroAlignEachRecord) { + endDelta -= startDelta; + if (endDelta < 0) { + endDelta += DUMP_LINE_LEN; + } + startDelta = 0; + } + int startLineAddr; + int endLineAddr; + if (zeroAlignEachRecord) { + endLineAddr = globalEnd - endDelta - (globalStart - startDelta); + startLineAddr = 0; + } else { + startLineAddr = globalStart - startDelta; + endLineAddr = globalEnd - endDelta; + } - int lineDataOffset = baseDataOffset - startDelta; - int lineAddr = startLineAddr; + int lineDataOffset = baseDataOffset - startDelta; + int lineAddr = startLineAddr; - // output (possibly incomplete) first line - if (startLineAddr == endLineAddr) { - hexDumpLine(w, data, lineAddr, lineDataOffset, startDelta, endDelta); - return; - } - hexDumpLine(w, data, lineAddr, lineDataOffset, startDelta, DUMP_LINE_LEN); + // output (possibly incomplete) first line + if (startLineAddr == endLineAddr) { + hexDumpLine(w, data, lineAddr, lineDataOffset, startDelta, endDelta); + return; + } + hexDumpLine(w, data, lineAddr, lineDataOffset, startDelta, DUMP_LINE_LEN); - // output all full lines in the middle - while (true) { - lineAddr += DUMP_LINE_LEN; - lineDataOffset += DUMP_LINE_LEN; - if (lineAddr >= endLineAddr) { - break; - } - hexDumpLine(w, data, lineAddr, lineDataOffset, 0, DUMP_LINE_LEN); - } + // output all full lines in the middle + while (true) { + lineAddr += DUMP_LINE_LEN; + lineDataOffset += DUMP_LINE_LEN; + if (lineAddr >= endLineAddr) { + break; + } + hexDumpLine(w, data, lineAddr, lineDataOffset, 0, DUMP_LINE_LEN); + } - // output (possibly incomplete) last line - if (endDelta != 0) { - hexDumpLine(w, data, lineAddr, lineDataOffset, 0, endDelta); - } - } + // output (possibly incomplete) last line + if (endDelta != 0) { + hexDumpLine(w, data, lineAddr, lineDataOffset, 0, endDelta); + } + } - private static void hexDumpLine(Writer w, byte[] data, int lineStartAddress, int lineDataOffset, int startDelta, int endDelta) { - final char[] buf = new char[8+2*COLUMN_SEPARATOR.length+DUMP_LINE_LEN*3-1+DUMP_LINE_LEN+NEW_LINE_CHARS.length]; + private static void hexDumpLine(Writer w, byte[] data, int lineStartAddress, int lineDataOffset, int startDelta, int endDelta) { + final char[] buf = new char[8+2*COLUMN_SEPARATOR.length+DUMP_LINE_LEN*3-1+DUMP_LINE_LEN+NEW_LINE_CHARS.length]; - if (startDelta >= endDelta) { - throw new IllegalArgumentException("Bad start/end delta"); - } - int idx=0; - try { - writeHex(buf, idx, lineStartAddress, 8); - idx = arraycopy(COLUMN_SEPARATOR, buf, idx+8); - // raw hex data - for (int i=0; i< DUMP_LINE_LEN; i++) { - if (i>0) { - buf[idx++] = ' '; - } - if (i >= startDelta && i < endDelta) { - writeHex(buf, idx, data[lineDataOffset+i], 2); - } else { - buf[idx] = ' '; - buf[idx+1] = ' '; - } - idx += 2; - } - idx = arraycopy(COLUMN_SEPARATOR, buf, idx); + if (startDelta >= endDelta) { + throw new IllegalArgumentException("Bad start/end delta"); + } + int idx=0; + try { + writeHex(buf, idx, lineStartAddress, 8); + idx = arraycopy(COLUMN_SEPARATOR, buf, idx+8); + // raw hex data + for (int i=0; i< DUMP_LINE_LEN; i++) { + if (i>0) { + buf[idx++] = ' '; + } + if (i >= startDelta && i < endDelta) { + writeHex(buf, idx, data[lineDataOffset+i], 2); + } else { + buf[idx] = ' '; + buf[idx+1] = ' '; + } + idx += 2; + } + idx = arraycopy(COLUMN_SEPARATOR, buf, idx); - // interpreted ascii - for (int i=0; i< DUMP_LINE_LEN; i++) { - char ch = ' '; - if (i >= startDelta && i < endDelta) { - ch = getPrintableChar(data[lineDataOffset+i]); - } - buf[idx++] = ch; - } + // interpreted ascii + for (int i=0; i< DUMP_LINE_LEN; i++) { + char ch = ' '; + if (i >= startDelta && i < endDelta) { + ch = getPrintableChar(data[lineDataOffset+i]); + } + buf[idx++] = ch; + } - idx = arraycopy(NEW_LINE_CHARS, buf, idx); + idx = arraycopy(NEW_LINE_CHARS, buf, idx); - w.write(buf, 0, idx); - } catch (IOException e) { - throw new RuntimeException(e); - } - } + w.write(buf, 0, idx); + } catch (IOException e) { + throw new RuntimeException(e); + } + } - private static int arraycopy(char[] in, char[] out, int pos) { - int idx = pos; - for (char c : in) { - out[idx++] = c; - } - return idx; - } + private static int arraycopy(char[] in, char[] out, int pos) { + int idx = pos; + for (char c : in) { + out[idx++] = c; + } + return idx; + } - private static char getPrintableChar(byte b) { - char ib = (char) (b & 0x00FF); - if (ib < 32 || ib > 126) { - return '.'; - } - return ib; - } + private static char getPrintableChar(byte b) { + char ib = (char) (b & 0x00FF); + if (ib < 32 || ib > 126) { + return '.'; + } + return ib; + } - private static void writeHex(char[] buf, int startInBuf, int value, int nDigits) { - int acc = value; - for(int i=nDigits-1; i>=0; i--) { - int digit = acc & 0x0F; - buf[startInBuf+i] = (char) (digit < 10 ? ('0' + digit) : ('A' + digit - 10)); - acc >>>= 4; - } - } + private static void writeHex(char[] buf, int startInBuf, int value, int nDigits) { + int acc = value; + for(int i=nDigits-1; i>=0; i--) { + int digit = acc & 0x0F; + buf[startInBuf+i] = (char) (digit < 10 ? ('0' + digit) : ('A' + digit - 10)); + acc >>>= 4; + } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/dev/FormulaViewer.java b/poi/src/main/java/org/apache/poi/hssf/dev/FormulaViewer.java index 2301330343..20aa00f63b 100644 --- a/poi/src/main/java/org/apache/poi/hssf/dev/FormulaViewer.java +++ b/poi/src/main/java/org/apache/poi/hssf/dev/FormulaViewer.java @@ -121,9 +121,9 @@ public class FormulaViewer private String formulaString(FormulaRecord record) { StringBuilder buf = new StringBuilder(); - Ptg[] tokens = record.getParsedExpression(); - for (Ptg token : tokens) { - buf.append( token.toFormulaString()); + Ptg[] tokens = record.getParsedExpression(); + for (Ptg token : tokens) { + buf.append( token.toFormulaString()); switch (token.getPtgClass()) { case Ptg.CLASS_REF : buf.append("(R)"); diff --git a/poi/src/main/java/org/apache/poi/hssf/eventmodel/EventRecordFactory.java b/poi/src/main/java/org/apache/poi/hssf/eventmodel/EventRecordFactory.java index 9cc6791c5f..234206a1ae 100644 --- a/poi/src/main/java/org/apache/poi/hssf/eventmodel/EventRecordFactory.java +++ b/poi/src/main/java/org/apache/poi/hssf/eventmodel/EventRecordFactory.java @@ -34,89 +34,89 @@ import org.apache.poi.util.RecordFormatException; */ public final class EventRecordFactory { - private final ERFListener _listener; - private final short[] _sids; + private final ERFListener _listener; + private final short[] _sids; - /** - * Create an EventRecordFactory - * - * @param listener the listener to be informed about events - * @param sids an array of Record.sid values identifying the records - * the listener will work with. Alternatively if this is "null" then - * all records are passed. For all 'known' record types use {@link RecordFactory#getAllKnownRecordSIDs()} - */ - public EventRecordFactory(ERFListener listener, short[] sids) { - _listener = listener; - if (sids == null) { - _sids = null; - } else { - _sids = sids.clone(); - Arrays.sort(_sids); // for faster binary search - } - } - private boolean isSidIncluded(short sid) { - if (_sids == null) { - return true; - } - return Arrays.binarySearch(_sids, sid) >= 0; - } + /** + * Create an EventRecordFactory + * + * @param listener the listener to be informed about events + * @param sids an array of Record.sid values identifying the records + * the listener will work with. Alternatively if this is "null" then + * all records are passed. For all 'known' record types use {@link RecordFactory#getAllKnownRecordSIDs()} + */ + public EventRecordFactory(ERFListener listener, short[] sids) { + _listener = listener; + if (sids == null) { + _sids = null; + } else { + _sids = sids.clone(); + Arrays.sort(_sids); // for faster binary search + } + } + private boolean isSidIncluded(short sid) { + if (_sids == null) { + return true; + } + return Arrays.binarySearch(_sids, sid) >= 0; + } - /** - * sends the record event to all registered listeners. - * @param record the record to be thrown. - * @return false to abort. This aborts - * out of the event loop should the listener return false - */ - private boolean processRecord(org.apache.poi.hssf.record.Record record) { - if (!isSidIncluded(record.getSid())) { - return true; - } - return _listener.processRecord(record); - } + /** + * sends the record event to all registered listeners. + * @param record the record to be thrown. + * @return false to abort. This aborts + * out of the event loop should the listener return false + */ + private boolean processRecord(org.apache.poi.hssf.record.Record record) { + if (!isSidIncluded(record.getSid())) { + return true; + } + return _listener.processRecord(record); + } - /** - * Create an array of records from an input stream - * - * @param in the InputStream from which the records will be - * obtained - * - * @exception RecordFormatException on error processing the - * InputStream - */ - public void processRecords(InputStream in) throws RecordFormatException { - Record last_record = null; + /** + * Create an array of records from an input stream + * + * @param in the InputStream from which the records will be + * obtained + * + * @exception RecordFormatException on error processing the + * InputStream + */ + public void processRecords(InputStream in) throws RecordFormatException { + Record last_record = null; - RecordInputStream recStream = new RecordInputStream(in); + RecordInputStream recStream = new RecordInputStream(in); - while (recStream.hasNextRecord()) { - recStream.nextRecord(); - Record[] recs = RecordFactory.createRecord(recStream); // handle MulRK records - if (recs.length > 1) { - for (org.apache.poi.hssf.record.Record rec : recs) { - if ( last_record != null ) { - if (!processRecord(last_record)) { - return; - } - } - last_record = rec; // do to keep the algorithm homogeneous...you can't - } // actually continue a number record anyhow. - } else { - Record record = recs[ 0 ]; + while (recStream.hasNextRecord()) { + recStream.nextRecord(); + Record[] recs = RecordFactory.createRecord(recStream); // handle MulRK records + if (recs.length > 1) { + for (org.apache.poi.hssf.record.Record rec : recs) { + if ( last_record != null ) { + if (!processRecord(last_record)) { + return; + } + } + last_record = rec; // do to keep the algorithm homogeneous...you can't + } // actually continue a number record anyhow. + } else { + Record record = recs[ 0 ]; - if (record != null) { - if (last_record != null) { - if (!processRecord(last_record)) { - return; - } - } - last_record = record; - } - } - } + if (record != null) { + if (last_record != null) { + if (!processRecord(last_record)) { + return; + } + } + last_record = record; + } + } + } - if (last_record != null) { - processRecord(last_record); - } - } + if (last_record != null) { + processRecord(last_record); + } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/AbortableHSSFListener.java b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/AbortableHSSFListener.java index 08e9c4f72a..b030effac6 100644 --- a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/AbortableHSSFListener.java +++ b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/AbortableHSSFListener.java @@ -41,31 +41,31 @@ public abstract class AbortableHSSFListener implements HSSFListener * It is never called by HSSFEventFactory or HSSFRequest. * You should implement #abortableProcessRecord instead */ - @Override + @Override public void processRecord(org.apache.poi.hssf.record.Record record) - { - } + { + } /** - * Process an HSSF Record. Called when a record occurs in an HSSF file. - * Provides two options for halting the processing of the HSSF file. - * - * The return value provides a means of non-error termination with a - * user-defined result code. A value of zero must be returned to - * continue processing, any other value will halt processing by - * HSSFEventFactory with the code being passed back by - * its abortable process events methods. - * - * Error termination can be done by throwing the HSSFUserException. - * - * Note that HSSFEventFactory will not call the inherited process - * - * @param record the record to be processed - * + * Process an HSSF Record. Called when a record occurs in an HSSF file. + * Provides two options for halting the processing of the HSSF file. + * + * The return value provides a means of non-error termination with a + * user-defined result code. A value of zero must be returned to + * continue processing, any other value will halt processing by + * HSSFEventFactory with the code being passed back by + * its abortable process events methods. + * + * Error termination can be done by throwing the HSSFUserException. + * + * Note that HSSFEventFactory will not call the inherited process + * + * @param record the record to be processed + * * @return result code of zero for continued processing. * - * @throws HSSFUserException User code can throw this to abort - * file processing by HSSFEventFactory and return diagnostic information. + * @throws HSSFUserException User code can throw this to abort + * file processing by HSSFEventFactory and return diagnostic information. */ public abstract short abortableProcessRecord(org.apache.poi.hssf.record.Record record) throws HSSFUserException; } diff --git a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/EventWorkbookBuilder.java b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/EventWorkbookBuilder.java index 0ef80530c0..3a6a54e133 100644 --- a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/EventWorkbookBuilder.java +++ b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/EventWorkbookBuilder.java @@ -56,131 +56,131 @@ import org.apache.poi.hssf.usermodel.HSSFWorkbook; public class EventWorkbookBuilder { - /** - * Creates a stub Workbook from the supplied records, - * suitable for use with the {@link HSSFFormulaParser} - * @param externs The ExternSheetRecords in your file - * @param bounds The BoundSheetRecords in your file - * @param sst The SSTRecord in your file. - * @return A stub Workbook suitable for use with {@link HSSFFormulaParser} - */ - public static InternalWorkbook createStubWorkbook(ExternSheetRecord[] externs, - BoundSheetRecord[] bounds, SSTRecord sst) { - List wbRecords = new ArrayList<>(); + /** + * Creates a stub Workbook from the supplied records, + * suitable for use with the {@link HSSFFormulaParser} + * @param externs The ExternSheetRecords in your file + * @param bounds The BoundSheetRecords in your file + * @param sst The SSTRecord in your file. + * @return A stub Workbook suitable for use with {@link HSSFFormulaParser} + */ + public static InternalWorkbook createStubWorkbook(ExternSheetRecord[] externs, + BoundSheetRecord[] bounds, SSTRecord sst) { + List wbRecords = new ArrayList<>(); - // Core Workbook records go first - if(bounds != null) { - Collections.addAll(wbRecords, bounds); - } - if(sst != null) { - wbRecords.add(sst); - } + // Core Workbook records go first + if(bounds != null) { + Collections.addAll(wbRecords, bounds); + } + if(sst != null) { + wbRecords.add(sst); + } - // Now we can have the ExternSheetRecords, - // preceded by a SupBookRecord - if(externs != null) { - wbRecords.add(SupBookRecord.createInternalReferences( - (short)externs.length)); - Collections.addAll(wbRecords, externs); - } + // Now we can have the ExternSheetRecords, + // preceded by a SupBookRecord + if(externs != null) { + wbRecords.add(SupBookRecord.createInternalReferences( + (short)externs.length)); + Collections.addAll(wbRecords, externs); + } - // Finally we need an EoF record - wbRecords.add(EOFRecord.instance); + // Finally we need an EoF record + wbRecords.add(EOFRecord.instance); - return InternalWorkbook.createWorkbook(wbRecords); - } + return InternalWorkbook.createWorkbook(wbRecords); + } - /** - * Creates a stub workbook from the supplied records, - * suitable for use with the {@link HSSFFormulaParser} - * @param externs The ExternSheetRecords in your file - * @param bounds The BoundSheetRecords in your file - * @return A stub Workbook suitable for use with {@link HSSFFormulaParser} - */ - public static InternalWorkbook createStubWorkbook(ExternSheetRecord[] externs, - BoundSheetRecord[] bounds) { - return createStubWorkbook(externs, bounds, null); - } + /** + * Creates a stub workbook from the supplied records, + * suitable for use with the {@link HSSFFormulaParser} + * @param externs The ExternSheetRecords in your file + * @param bounds The BoundSheetRecords in your file + * @return A stub Workbook suitable for use with {@link HSSFFormulaParser} + */ + public static InternalWorkbook createStubWorkbook(ExternSheetRecord[] externs, + BoundSheetRecord[] bounds) { + return createStubWorkbook(externs, bounds, null); + } - /** - * A wrapping HSSFListener which will collect - * {@link BoundSheetRecord}s and {@link ExternSheetRecord}s as - * they go past, so you can create a Stub {@link InternalWorkbook} from - * them once required. - */ - public static class SheetRecordCollectingListener implements HSSFListener { - private final HSSFListener childListener; - private final List boundSheetRecords = new ArrayList<>(); - private final List externSheetRecords = new ArrayList<>(); - private SSTRecord sstRecord; + /** + * A wrapping HSSFListener which will collect + * {@link BoundSheetRecord}s and {@link ExternSheetRecord}s as + * they go past, so you can create a Stub {@link InternalWorkbook} from + * them once required. + */ + public static class SheetRecordCollectingListener implements HSSFListener { + private final HSSFListener childListener; + private final List boundSheetRecords = new ArrayList<>(); + private final List externSheetRecords = new ArrayList<>(); + private SSTRecord sstRecord; - public SheetRecordCollectingListener(HSSFListener childListener) { - this.childListener = childListener; - } + public SheetRecordCollectingListener(HSSFListener childListener) { + this.childListener = childListener; + } - public BoundSheetRecord[] getBoundSheetRecords() { - return boundSheetRecords.toArray( - new BoundSheetRecord[0] - ); - } - public ExternSheetRecord[] getExternSheetRecords() { - return externSheetRecords.toArray( - new ExternSheetRecord[0] - ); - } - public SSTRecord getSSTRecord() { - return sstRecord; - } + public BoundSheetRecord[] getBoundSheetRecords() { + return boundSheetRecords.toArray( + new BoundSheetRecord[0] + ); + } + public ExternSheetRecord[] getExternSheetRecords() { + return externSheetRecords.toArray( + new ExternSheetRecord[0] + ); + } + public SSTRecord getSSTRecord() { + return sstRecord; + } - public HSSFWorkbook getStubHSSFWorkbook() { - // Create a base workbook - HSSFWorkbook wb = HSSFWorkbook.create(getStubWorkbook()); - // Stub the sheets, so sheet name lookups work - for (BoundSheetRecord bsr : boundSheetRecords) { - wb.createSheet(bsr.getSheetname()); - } - // Ready for Formula use! - return wb; - } - public InternalWorkbook getStubWorkbook() { - return createStubWorkbook( - getExternSheetRecords(), getBoundSheetRecords(), - getSSTRecord() - ); - } + public HSSFWorkbook getStubHSSFWorkbook() { + // Create a base workbook + HSSFWorkbook wb = HSSFWorkbook.create(getStubWorkbook()); + // Stub the sheets, so sheet name lookups work + for (BoundSheetRecord bsr : boundSheetRecords) { + wb.createSheet(bsr.getSheetname()); + } + // Ready for Formula use! + return wb; + } + public InternalWorkbook getStubWorkbook() { + return createStubWorkbook( + getExternSheetRecords(), getBoundSheetRecords(), + getSSTRecord() + ); + } - /** - * Process this record ourselves, and then - * pass it on to our child listener - */ - @Override + /** + * Process this record ourselves, and then + * pass it on to our child listener + */ + @Override public void processRecord(org.apache.poi.hssf.record.Record record) { - // Handle it ourselves - processRecordInternally(record); + // Handle it ourselves + processRecordInternally(record); - // Now pass on to our child - childListener.processRecord(record); - } + // Now pass on to our child + childListener.processRecord(record); + } - /** - * Process the record ourselves, but do not - * pass it on to the child Listener. - * - * @param record the record to be processed - */ - public void processRecordInternally(org.apache.poi.hssf.record.Record record) { - if(record instanceof BoundSheetRecord) { - boundSheetRecords.add((BoundSheetRecord)record); - } - else if(record instanceof ExternSheetRecord) { - externSheetRecords.add((ExternSheetRecord)record); - } - else if(record instanceof SSTRecord) { - sstRecord = (SSTRecord)record; - } - } - } + /** + * Process the record ourselves, but do not + * pass it on to the child Listener. + * + * @param record the record to be processed + */ + public void processRecordInternally(org.apache.poi.hssf.record.Record record) { + if(record instanceof BoundSheetRecord) { + boundSheetRecords.add((BoundSheetRecord)record); + } + else if(record instanceof ExternSheetRecord) { + externSheetRecords.add((ExternSheetRecord)record); + } + else if(record instanceof SSTRecord) { + sstRecord = (SSTRecord)record; + } + } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/FormatTrackingHSSFListener.java b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/FormatTrackingHSSFListener.java index fcd4cdd2a3..a465a274d9 100644 --- a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/FormatTrackingHSSFListener.java +++ b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/FormatTrackingHSSFListener.java @@ -43,159 +43,159 @@ import static org.apache.logging.log4j.util.Unbox.box; * ids. */ public class FormatTrackingHSSFListener implements HSSFListener { - private static final Logger LOG = LogManager.getLogger(FormatTrackingHSSFListener.class); - private final HSSFListener _childListener; - private final HSSFDataFormatter _formatter; - private final NumberFormat _defaultFormat; - private final Map _customFormatRecords = new HashMap<>(); - private final List _xfRecords = new ArrayList<>(); + private static final Logger LOG = LogManager.getLogger(FormatTrackingHSSFListener.class); + private final HSSFListener _childListener; + private final HSSFDataFormatter _formatter; + private final NumberFormat _defaultFormat; + private final Map _customFormatRecords = new HashMap<>(); + private final List _xfRecords = new ArrayList<>(); - /** - * Creates a format tracking wrapper around the given listener, using - * the {@link Locale#getDefault() default locale} for the formats. - * - * @param childListener the listener to be wrapped - */ - public FormatTrackingHSSFListener(HSSFListener childListener) { - this(childListener, LocaleUtil.getUserLocale()); - } + /** + * Creates a format tracking wrapper around the given listener, using + * the {@link Locale#getDefault() default locale} for the formats. + * + * @param childListener the listener to be wrapped + */ + public FormatTrackingHSSFListener(HSSFListener childListener) { + this(childListener, LocaleUtil.getUserLocale()); + } - /** - * Creates a format tracking wrapper around the given listener, using - * the given locale for the formats. + /** + * Creates a format tracking wrapper around the given listener, using + * the given locale for the formats. * * @param childListener the listener to be wrapped * @param locale the locale for the formats - */ - public FormatTrackingHSSFListener( - HSSFListener childListener, Locale locale) { - _childListener = childListener; - _formatter = new HSSFDataFormatter(locale); - _defaultFormat = NumberFormat.getInstance(locale); - } + */ + public FormatTrackingHSSFListener( + HSSFListener childListener, Locale locale) { + _childListener = childListener; + _formatter = new HSSFDataFormatter(locale); + _defaultFormat = NumberFormat.getInstance(locale); + } - protected int getNumberOfCustomFormats() { - return _customFormatRecords.size(); - } + protected int getNumberOfCustomFormats() { + return _customFormatRecords.size(); + } - protected int getNumberOfExtendedFormats() { - return _xfRecords.size(); - } + protected int getNumberOfExtendedFormats() { + return _xfRecords.size(); + } - /** - * Process this record ourselves, and then pass it on to our child listener - */ - @Override + /** + * Process this record ourselves, and then pass it on to our child listener + */ + @Override public void processRecord(Record record) { - // Handle it ourselves - processRecordInternally(record); + // Handle it ourselves + processRecordInternally(record); - // Now pass on to our child - _childListener.processRecord(record); - } + // Now pass on to our child + _childListener.processRecord(record); + } - /** - * Process the record ourselves, but do not pass it on to the child - * Listener. - * - * @param record the record to be processed - */ - public void processRecordInternally(Record record) { - if (record instanceof FormatRecord) { - FormatRecord fr = (FormatRecord) record; - _customFormatRecords.put(Integer.valueOf(fr.getIndexCode()), fr); - } - if (record instanceof ExtendedFormatRecord) { - ExtendedFormatRecord xr = (ExtendedFormatRecord) record; - _xfRecords.add(xr); - } - } + /** + * Process the record ourselves, but do not pass it on to the child + * Listener. + * + * @param record the record to be processed + */ + public void processRecordInternally(Record record) { + if (record instanceof FormatRecord) { + FormatRecord fr = (FormatRecord) record; + _customFormatRecords.put(Integer.valueOf(fr.getIndexCode()), fr); + } + if (record instanceof ExtendedFormatRecord) { + ExtendedFormatRecord xr = (ExtendedFormatRecord) record; + _xfRecords.add(xr); + } + } - /** - * Formats the given numeric of date cells contents as a String, in as - * close as we can to the way that Excel would do so. Uses the various - * format records to manage this. - * - * TODO - move this to a central class in such a way that hssf.usermodel can - * make use of it too - * - * @param cell the cell - * - * @return the given numeric of date cells contents as a String - */ - public String formatNumberDateCell(CellValueRecordInterface cell) { - double value; - if (cell instanceof NumberRecord) { - value = ((NumberRecord) cell).getValue(); - } else if (cell instanceof FormulaRecord) { - value = ((FormulaRecord) cell).getValue(); - } else { - throw new IllegalArgumentException("Unsupported CellValue Record passed in " + cell); - } + /** + * Formats the given numeric of date cells contents as a String, in as + * close as we can to the way that Excel would do so. Uses the various + * format records to manage this. + * + * TODO - move this to a central class in such a way that hssf.usermodel can + * make use of it too + * + * @param cell the cell + * + * @return the given numeric of date cells contents as a String + */ + public String formatNumberDateCell(CellValueRecordInterface cell) { + double value; + if (cell instanceof NumberRecord) { + value = ((NumberRecord) cell).getValue(); + } else if (cell instanceof FormulaRecord) { + value = ((FormulaRecord) cell).getValue(); + } else { + throw new IllegalArgumentException("Unsupported CellValue Record passed in " + cell); + } - // Get the built in format, if there is one - int formatIndex = getFormatIndex(cell); - String formatString = getFormatString(cell); + // Get the built in format, if there is one + int formatIndex = getFormatIndex(cell); + String formatString = getFormatString(cell); - if (formatString == null) { - return _defaultFormat.format(value); - } - // Format, using the nice new - // HSSFDataFormatter to do the work for us - return _formatter.formatRawCellContents(value, formatIndex, formatString); - } + if (formatString == null) { + return _defaultFormat.format(value); + } + // Format, using the nice new + // HSSFDataFormatter to do the work for us + return _formatter.formatRawCellContents(value, formatIndex, formatString); + } - /** - * Returns the format string, eg $##.##, for the given number format index. - * - * @param formatIndex the format index - * - * @return the format string - */ - public String getFormatString(int formatIndex) { - String format = null; - if (formatIndex >= HSSFDataFormat.getNumberOfBuiltinBuiltinFormats()) { - FormatRecord tfr = _customFormatRecords.get(Integer.valueOf(formatIndex)); - if (tfr == null) { - LOG.atError().log("Requested format at index {}, but it wasn't found", box(formatIndex)); - } else { - format = tfr.getFormatString(); - } - } else { - format = HSSFDataFormat.getBuiltinFormat((short) formatIndex); - } - return format; - } + /** + * Returns the format string, eg $##.##, for the given number format index. + * + * @param formatIndex the format index + * + * @return the format string + */ + public String getFormatString(int formatIndex) { + String format = null; + if (formatIndex >= HSSFDataFormat.getNumberOfBuiltinBuiltinFormats()) { + FormatRecord tfr = _customFormatRecords.get(Integer.valueOf(formatIndex)); + if (tfr == null) { + LOG.atError().log("Requested format at index {}, but it wasn't found", box(formatIndex)); + } else { + format = tfr.getFormatString(); + } + } else { + format = HSSFDataFormat.getBuiltinFormat((short) formatIndex); + } + return format; + } - /** - * Returns the format string, eg $##.##, used by your cell - * - * @param cell the cell - * - * @return the format string - */ - public String getFormatString(CellValueRecordInterface cell) { - int formatIndex = getFormatIndex(cell); - if (formatIndex == -1) { - // Not found - return null; - } - return getFormatString(formatIndex); - } + /** + * Returns the format string, eg $##.##, used by your cell + * + * @param cell the cell + * + * @return the format string + */ + public String getFormatString(CellValueRecordInterface cell) { + int formatIndex = getFormatIndex(cell); + if (formatIndex == -1) { + // Not found + return null; + } + return getFormatString(formatIndex); + } - /** - * Returns the index of the format string, used by your cell, or -1 if none found - * - * @param cell the cell - * - * @return the index of the format string - */ - public int getFormatIndex(CellValueRecordInterface cell) { - ExtendedFormatRecord xfr = _xfRecords.get(cell.getXFIndex()); - if (xfr == null) { - LOG.atError().log("Cell {},{} uses XF with index {}, but we don't have that", box(cell.getRow()),box(cell.getColumn()),box(cell.getXFIndex())); - return -1; - } - return xfr.getFormatIndex(); - } + /** + * Returns the index of the format string, used by your cell, or -1 if none found + * + * @param cell the cell + * + * @return the index of the format string + */ + public int getFormatIndex(CellValueRecordInterface cell) { + ExtendedFormatRecord xfr = _xfRecords.get(cell.getXFIndex()); + if (xfr == null) { + LOG.atError().log("Cell {},{} uses XF with index {}, but we don't have that", box(cell.getRow()),box(cell.getColumn()),box(cell.getXFIndex())); + return -1; + } + return xfr.getFormatIndex(); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/HSSFEventFactory.java b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/HSSFEventFactory.java index 65c0c83115..bf4d737ab1 100644 --- a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/HSSFEventFactory.java +++ b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/HSSFEventFactory.java @@ -36,22 +36,22 @@ import static org.apache.poi.hssf.model.InternalWorkbook.WORKBOOK_DIR_ENTRY_NAME * to your associated HSSFListener. */ public class HSSFEventFactory { - /** Creates a new instance of HSSFEventFactory */ - public HSSFEventFactory() { - // no instance fields - } + /** Creates a new instance of HSSFEventFactory */ + public HSSFEventFactory() { + // no instance fields + } - /** - * Processes a file into essentially record events. - * - * @param req an Instance of HSSFRequest which has your registered listeners - * @param fs a POIFS filesystem containing your workbook + /** + * Processes a file into essentially record events. + * + * @param req an Instance of HSSFRequest which has your registered listeners + * @param fs a POIFS filesystem containing your workbook * * @throws IOException if the workbook contained errors - */ - public void processWorkbookEvents(HSSFRequest req, POIFSFileSystem fs) throws IOException { - processWorkbookEvents(req, fs.getRoot()); - } + */ + public void processWorkbookEvents(HSSFRequest req, POIFSFileSystem fs) throws IOException { + processWorkbookEvents(req, fs.getRoot()); + } /** * Processes a file into essentially record events. @@ -96,86 +96,86 @@ public class HSSFEventFactory { return abortableProcessWorkbookEvents(req, fs.getRoot()); } - /** - * Processes a file into essentially record events. - * - * @param req an Instance of HSSFRequest which has your registered listeners - * @param dir a DirectoryNode containing your workbook - * @return numeric user-specified result code. - * - * @throws HSSFUserException if the processing should be aborted - * @throws IOException if the workbook contained errors - */ - public short abortableProcessWorkbookEvents(HSSFRequest req, DirectoryNode dir) - throws IOException, HSSFUserException { + /** + * Processes a file into essentially record events. + * + * @param req an Instance of HSSFRequest which has your registered listeners + * @param dir a DirectoryNode containing your workbook + * @return numeric user-specified result code. + * + * @throws HSSFUserException if the processing should be aborted + * @throws IOException if the workbook contained errors + */ + public short abortableProcessWorkbookEvents(HSSFRequest req, DirectoryNode dir) + throws IOException, HSSFUserException { try (InputStream in = dir.createDocumentInputStream("Workbook")) { return abortableProcessEvents(req, in); } - } + } - /** - * Processes a DocumentInputStream into essentially Record events. - * - * If an AbortableHSSFListener causes a halt to processing during this call - * the method will return just as with abortableProcessEvents, but no - * user code or HSSFUserException will be passed back. - * - * @see org.apache.poi.poifs.filesystem.POIFSFileSystem#createDocumentInputStream(String) - * @param req an Instance of HSSFRequest which has your registered listeners - * @param in a DocumentInputStream obtained from POIFS's POIFSFileSystem object - */ - public void processEvents(HSSFRequest req, InputStream in) { - try { - genericProcessEvents(req, in); - } catch (HSSFUserException hue) { - /*If an HSSFUserException user exception is thrown, ignore it.*/ - } - } + /** + * Processes a DocumentInputStream into essentially Record events. + * + * If an AbortableHSSFListener causes a halt to processing during this call + * the method will return just as with abortableProcessEvents, but no + * user code or HSSFUserException will be passed back. + * + * @see org.apache.poi.poifs.filesystem.POIFSFileSystem#createDocumentInputStream(String) + * @param req an Instance of HSSFRequest which has your registered listeners + * @param in a DocumentInputStream obtained from POIFS's POIFSFileSystem object + */ + public void processEvents(HSSFRequest req, InputStream in) { + try { + genericProcessEvents(req, in); + } catch (HSSFUserException hue) { + /*If an HSSFUserException user exception is thrown, ignore it.*/ + } + } - /** - * Processes a DocumentInputStream into essentially Record events. - * - * @see org.apache.poi.poifs.filesystem.POIFSFileSystem#createDocumentInputStream(String) - * @param req an Instance of HSSFRequest which has your registered listeners - * @param in a DocumentInputStream obtained from POIFS's POIFSFileSystem object - * @return numeric user-specified result code. - * - * @throws HSSFUserException if the processing should be aborted - */ - public short abortableProcessEvents(HSSFRequest req, InputStream in) - throws HSSFUserException { - return genericProcessEvents(req, in); - } + /** + * Processes a DocumentInputStream into essentially Record events. + * + * @see org.apache.poi.poifs.filesystem.POIFSFileSystem#createDocumentInputStream(String) + * @param req an Instance of HSSFRequest which has your registered listeners + * @param in a DocumentInputStream obtained from POIFS's POIFSFileSystem object + * @return numeric user-specified result code. + * + * @throws HSSFUserException if the processing should be aborted + */ + public short abortableProcessEvents(HSSFRequest req, InputStream in) + throws HSSFUserException { + return genericProcessEvents(req, in); + } - /** - * Processes a DocumentInputStream into essentially Record events. - * - * @see org.apache.poi.poifs.filesystem.POIFSFileSystem#createDocumentInputStream(String) - * @param req an Instance of HSSFRequest which has your registered listeners - * @param in a DocumentInputStream obtained from POIFS's POIFSFileSystem object - * @return numeric user-specified result code. - */ - private short genericProcessEvents(HSSFRequest req, InputStream in) - throws HSSFUserException { - short userCode = 0; + /** + * Processes a DocumentInputStream into essentially Record events. + * + * @see org.apache.poi.poifs.filesystem.POIFSFileSystem#createDocumentInputStream(String) + * @param req an Instance of HSSFRequest which has your registered listeners + * @param in a DocumentInputStream obtained from POIFS's POIFSFileSystem object + * @return numeric user-specified result code. + */ + private short genericProcessEvents(HSSFRequest req, InputStream in) + throws HSSFUserException { + short userCode = 0; - // Create a new RecordStream and use that - RecordFactoryInputStream recordStream = new RecordFactoryInputStream(in, false); + // Create a new RecordStream and use that + RecordFactoryInputStream recordStream = new RecordFactoryInputStream(in, false); - // Process each record as they come in - while(true) { - org.apache.poi.hssf.record.Record r = recordStream.nextRecord(); - if(r == null) { - break; - } - userCode = req.processRecord(r); - if (userCode != 0) { - break; - } - } + // Process each record as they come in + while(true) { + org.apache.poi.hssf.record.Record r = recordStream.nextRecord(); + if(r == null) { + break; + } + userCode = req.processRecord(r); + if (userCode != 0) { + break; + } + } - // All done, return our last code - return userCode; - } + // All done, return our last code + return userCode; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/HSSFRequest.java b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/HSSFRequest.java index 50cc728e95..ce6b93af72 100644 --- a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/HSSFRequest.java +++ b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/HSSFRequest.java @@ -34,79 +34,79 @@ import org.apache.poi.hssf.record.RecordFactory; * @see org.apache.poi.hssf.eventusermodel.HSSFUserException */ public class HSSFRequest { - private final Map> _records; + private final Map> _records; - /** Creates a new instance of HSSFRequest */ - public HSSFRequest() { - _records = new HashMap<>(50); // most folks won't listen for too many of these - } + /** Creates a new instance of HSSFRequest */ + public HSSFRequest() { + _records = new HashMap<>(50); // most folks won't listen for too many of these + } - /** - * add an event listener for a particular record type. The trick is you have to know - * what the records are for or just start with our examples and build on them. Alternatively, - * you CAN call addListenerForAllRecords and you'll receive ALL record events in one listener, - * but if you like to squeeze every last byte of efficiency out of life you my not like this. - * (its sure as heck what I plan to do) - * - * @see #addListenerForAllRecords(HSSFListener) - * - * @param lsnr for the event - * @param sid identifier for the record type this is the .sid static member on the individual records - * for example req.addListener(myListener, BOFRecord.sid) - */ - public void addListener(HSSFListener lsnr, short sid) { - List list = _records.computeIfAbsent(Short.valueOf(sid), k -> new ArrayList<>(1)); + /** + * add an event listener for a particular record type. The trick is you have to know + * what the records are for or just start with our examples and build on them. Alternatively, + * you CAN call addListenerForAllRecords and you'll receive ALL record events in one listener, + * but if you like to squeeze every last byte of efficiency out of life you my not like this. + * (its sure as heck what I plan to do) + * + * @see #addListenerForAllRecords(HSSFListener) + * + * @param lsnr for the event + * @param sid identifier for the record type this is the .sid static member on the individual records + * for example req.addListener(myListener, BOFRecord.sid) + */ + public void addListener(HSSFListener lsnr, short sid) { + List list = _records.computeIfAbsent(Short.valueOf(sid), k -> new ArrayList<>(1)); - // probably most people will use one listener - list.add(lsnr); - } + // probably most people will use one listener + list.add(lsnr); + } - /** - * This is the equivalent of calling addListener(myListener, sid) for EVERY - * record in the org.apache.poi.hssf.record package. This is for lazy - * people like me. You can call this more than once with more than one listener, but - * that seems like a bad thing to do from a practice-perspective unless you have a - * compelling reason to do so (like maybe you send the event two places or log it or - * something?). - * - * @param lsnr a single listener to associate with ALL records - */ - public void addListenerForAllRecords(HSSFListener lsnr) { - short[] rectypes = RecordFactory.getAllKnownRecordSIDs(); + /** + * This is the equivalent of calling addListener(myListener, sid) for EVERY + * record in the org.apache.poi.hssf.record package. This is for lazy + * people like me. You can call this more than once with more than one listener, but + * that seems like a bad thing to do from a practice-perspective unless you have a + * compelling reason to do so (like maybe you send the event two places or log it or + * something?). + * + * @param lsnr a single listener to associate with ALL records + */ + public void addListenerForAllRecords(HSSFListener lsnr) { + short[] rectypes = RecordFactory.getAllKnownRecordSIDs(); - for (short rectype : rectypes) { - addListener(lsnr, rectype); - } - } + for (short rectype : rectypes) { + addListener(lsnr, rectype); + } + } - /** - * Called by HSSFEventFactory, passes the Record to each listener associated with - * a record.sid. - * - * @param rec the record to be processed - * - * @return numeric user-specified result code. If zero continue processing. - * @throws HSSFUserException User exception condition - */ - protected short processRecord(org.apache.poi.hssf.record.Record rec) throws HSSFUserException { - List listeners = _records.get(Short.valueOf(rec.getSid())); - short userCode = 0; + /** + * Called by HSSFEventFactory, passes the Record to each listener associated with + * a record.sid. + * + * @param rec the record to be processed + * + * @return numeric user-specified result code. If zero continue processing. + * @throws HSSFUserException User exception condition + */ + protected short processRecord(org.apache.poi.hssf.record.Record rec) throws HSSFUserException { + List listeners = _records.get(Short.valueOf(rec.getSid())); + short userCode = 0; - if (listeners != null) { + if (listeners != null) { - for (int k = 0; k < listeners.size(); k++) { - Object listenObj = listeners.get(k); - if (listenObj instanceof AbortableHSSFListener) { - AbortableHSSFListener listener = (AbortableHSSFListener) listenObj; - userCode = listener.abortableProcessRecord(rec); - if (userCode != 0) - break; - } else { - HSSFListener listener = (HSSFListener) listenObj; - listener.processRecord(rec); - } - } - } - return userCode; - } + for (int k = 0; k < listeners.size(); k++) { + Object listenObj = listeners.get(k); + if (listenObj instanceof AbortableHSSFListener) { + AbortableHSSFListener listener = (AbortableHSSFListener) listenObj; + userCode = listener.abortableProcessRecord(rec); + if (userCode != 0) + break; + } else { + HSSFListener listener = (HSSFListener) listenObj; + listener.processRecord(rec); + } + } + } + return userCode; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/MissingRecordAwareHSSFListener.java b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/MissingRecordAwareHSSFListener.java index 83c7a18cac..ed87510c70 100644 --- a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/MissingRecordAwareHSSFListener.java +++ b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/MissingRecordAwareHSSFListener.java @@ -42,169 +42,169 @@ import org.apache.poi.hssf.record.StringRecord; * blank. */ public final class MissingRecordAwareHSSFListener implements HSSFListener { - private HSSFListener childListener; + private HSSFListener childListener; - // Need to have different counters for cell rows and - // row rows, as you sometimes get a RowRecord in the - // middle of some cells, and that'd break everything - private int lastRowRow; + // Need to have different counters for cell rows and + // row rows, as you sometimes get a RowRecord in the + // middle of some cells, and that'd break everything + private int lastRowRow; - private int lastCellRow; - private int lastCellColumn; + private int lastCellRow; + private int lastCellColumn; - /** - * Constructs a new MissingRecordAwareHSSFListener, which - * will fire processRecord on the supplied child - * HSSFListener for all Records, and missing records. - * @param listener The HSSFListener to pass records on to - */ - public MissingRecordAwareHSSFListener(HSSFListener listener) { - resetCounts(); - childListener = listener; - } + /** + * Constructs a new MissingRecordAwareHSSFListener, which + * will fire processRecord on the supplied child + * HSSFListener for all Records, and missing records. + * @param listener The HSSFListener to pass records on to + */ + public MissingRecordAwareHSSFListener(HSSFListener listener) { + resetCounts(); + childListener = listener; + } - public void processRecord(org.apache.poi.hssf.record.Record record) { - int thisRow; - int thisColumn; - CellValueRecordInterface[] expandedRecords = null; + public void processRecord(org.apache.poi.hssf.record.Record record) { + int thisRow; + int thisColumn; + CellValueRecordInterface[] expandedRecords = null; - if (record instanceof CellValueRecordInterface) { - CellValueRecordInterface valueRec = (CellValueRecordInterface) record; - thisRow = valueRec.getRow(); - thisColumn = valueRec.getColumn(); - } else { + if (record instanceof CellValueRecordInterface) { + CellValueRecordInterface valueRec = (CellValueRecordInterface) record; + thisRow = valueRec.getRow(); + thisColumn = valueRec.getColumn(); + } else { if (record instanceof StringRecord){ //it contains only cashed result of the previous FormulaRecord evaluation childListener.processRecord(record); return; } - thisRow = -1; - thisColumn = -1; + thisRow = -1; + thisColumn = -1; - switch (record.getSid()) { - // the BOFRecord can represent either the beginning of a sheet or - // the workbook - case BOFRecord.sid: - BOFRecord bof = (BOFRecord) record; - if (bof.getType() == BOFRecord.TYPE_WORKBOOK || - bof.getType() == BOFRecord.TYPE_WORKSHEET) { - // Reset the row and column counts - new workbook / worksheet - resetCounts(); - } - break; - case RowRecord.sid: - RowRecord rowrec = (RowRecord) record; + switch (record.getSid()) { + // the BOFRecord can represent either the beginning of a sheet or + // the workbook + case BOFRecord.sid: + BOFRecord bof = (BOFRecord) record; + if (bof.getType() == BOFRecord.TYPE_WORKBOOK || + bof.getType() == BOFRecord.TYPE_WORKSHEET) { + // Reset the row and column counts - new workbook / worksheet + resetCounts(); + } + break; + case RowRecord.sid: + RowRecord rowrec = (RowRecord) record; - // If there's a jump in rows, fire off missing row records - if (lastRowRow + 1 < rowrec.getRowNumber()) { - for (int i = (lastRowRow + 1); i < rowrec.getRowNumber(); i++) { - MissingRowDummyRecord dr = new MissingRowDummyRecord(i); - childListener.processRecord(dr); - } - } + // If there's a jump in rows, fire off missing row records + if (lastRowRow + 1 < rowrec.getRowNumber()) { + for (int i = (lastRowRow + 1); i < rowrec.getRowNumber(); i++) { + MissingRowDummyRecord dr = new MissingRowDummyRecord(i); + childListener.processRecord(dr); + } + } - // Record this as the last row we saw - lastRowRow = rowrec.getRowNumber(); - lastCellColumn = -1; - break; + // Record this as the last row we saw + lastRowRow = rowrec.getRowNumber(); + lastCellColumn = -1; + break; - case SharedFormulaRecord.sid: - // SharedFormulaRecord occurs after the first FormulaRecord of the cell range. - // There are probably (but not always) more cell records after this - // - so don't fire off the LastCellOfRowDummyRecord yet - childListener.processRecord(record); - return; - case MulBlankRecord.sid: - // These appear in the middle of the cell records, to - // specify that the next bunch are empty but styled - // Expand this out into multiple blank cells - MulBlankRecord mbr = (MulBlankRecord)record; - expandedRecords = RecordFactory.convertBlankRecords(mbr); - break; - case MulRKRecord.sid: - // This is multiple consecutive number cells in one record - // Exand this out into multiple regular number cells - MulRKRecord mrk = (MulRKRecord)record; - expandedRecords = RecordFactory.convertRKRecords(mrk); - break; - case NoteRecord.sid: - NoteRecord nrec = (NoteRecord) record; - thisRow = nrec.getRow(); - thisColumn = nrec.getColumn(); - break; - default: - break; - } - } + case SharedFormulaRecord.sid: + // SharedFormulaRecord occurs after the first FormulaRecord of the cell range. + // There are probably (but not always) more cell records after this + // - so don't fire off the LastCellOfRowDummyRecord yet + childListener.processRecord(record); + return; + case MulBlankRecord.sid: + // These appear in the middle of the cell records, to + // specify that the next bunch are empty but styled + // Expand this out into multiple blank cells + MulBlankRecord mbr = (MulBlankRecord)record; + expandedRecords = RecordFactory.convertBlankRecords(mbr); + break; + case MulRKRecord.sid: + // This is multiple consecutive number cells in one record + // Exand this out into multiple regular number cells + MulRKRecord mrk = (MulRKRecord)record; + expandedRecords = RecordFactory.convertRKRecords(mrk); + break; + case NoteRecord.sid: + NoteRecord nrec = (NoteRecord) record; + thisRow = nrec.getRow(); + thisColumn = nrec.getColumn(); + break; + default: + break; + } + } - // First part of expanded record handling - if(expandedRecords != null && expandedRecords.length > 0) { - thisRow = expandedRecords[0].getRow(); - thisColumn = expandedRecords[0].getColumn(); - } + // First part of expanded record handling + if(expandedRecords != null && expandedRecords.length > 0) { + thisRow = expandedRecords[0].getRow(); + thisColumn = expandedRecords[0].getColumn(); + } - // If we're on cells, and this cell isn't in the same - // row as the last one, then fire the - // dummy end-of-row records - if(thisRow != lastCellRow && thisRow > 0) { - if (lastCellRow == -1) lastCellRow = 0; - for(int i=lastCellRow; i 0) { + if (lastCellRow == -1) lastCellRow = 0; + for(int i=lastCellRow; i 0) { - thisColumn = expandedRecords[expandedRecords.length-1].getColumn(); - } + // Next part of expanded record handling + if(expandedRecords != null && expandedRecords.length > 0) { + thisColumn = expandedRecords[expandedRecords.length-1].getColumn(); + } - // Update cell and row counts as needed - if(thisColumn != -1) { - lastCellColumn = thisColumn; - lastCellRow = thisRow; - } + // Update cell and row counts as needed + if(thisColumn != -1) { + lastCellColumn = thisColumn; + lastCellRow = thisRow; + } - // Pass along the record(s) - if(expandedRecords != null && expandedRecords.length > 0) { - for(CellValueRecordInterface r : expandedRecords) { - childListener.processRecord((org.apache.poi.hssf.record.Record)r); - } - } else { - childListener.processRecord(record); - } - } + // Pass along the record(s) + if(expandedRecords != null && expandedRecords.length > 0) { + for(CellValueRecordInterface r : expandedRecords) { + childListener.processRecord((org.apache.poi.hssf.record.Record)r); + } + } else { + childListener.processRecord(record); + } + } - private void resetCounts() { - lastRowRow = -1; - lastCellRow = -1; - lastCellColumn = -1; - } + private void resetCounts() { + lastRowRow = -1; + lastCellRow = -1; + lastCellColumn = -1; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/DummyRecordBase.java b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/DummyRecordBase.java index 008decd122..8ec94b40c1 100644 --- a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/DummyRecordBase.java +++ b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/DummyRecordBase.java @@ -24,17 +24,17 @@ import org.apache.poi.util.RecordFormatException; */ abstract class DummyRecordBase extends Record { - protected DummyRecordBase() {} + protected DummyRecordBase() {} - public final short getSid() { - return -1; - } - public int serialize(int offset, byte[] data) { - throw new RecordFormatException("Cannot serialize a dummy record"); - } - public final int getRecordSize() { - throw new RecordFormatException("Cannot serialize a dummy record"); - } + public final short getSid() { + return -1; + } + public int serialize(int offset, byte[] data) { + throw new RecordFormatException("Cannot serialize a dummy record"); + } + public final int getRecordSize() { + throw new RecordFormatException("Cannot serialize a dummy record"); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/LastCellOfRowDummyRecord.java b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/LastCellOfRowDummyRecord.java index b22dfd7cc7..a8a9e13b87 100644 --- a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/LastCellOfRowDummyRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/LastCellOfRowDummyRecord.java @@ -29,52 +29,52 @@ import org.apache.poi.util.GenericRecordUtil; * cell record for this row. */ public final class LastCellOfRowDummyRecord extends DummyRecordBase { - private final int row; - private final int lastColumnNumber; + private final int row; + private final int lastColumnNumber; - public LastCellOfRowDummyRecord(int row, int lastColumnNumber) { - this.row = row; - this.lastColumnNumber = lastColumnNumber; - } - - /** - * Returns the (0 based) number of the row we are - * currently working on. - * - * @return the (0 based) number of the row - */ - public int getRow() { - return row; + public LastCellOfRowDummyRecord(int row, int lastColumnNumber) { + this.row = row; + this.lastColumnNumber = lastColumnNumber; } - /** - * Returns the (0 based) number of the last column - * seen for this row. You should have already been - * called with that record. - * This is -1 in the case of there being no columns - * for the row. - * - * @return the (0 based) number of the last column - */ - public int getLastColumnNumber() { - return lastColumnNumber; + /** + * Returns the (0 based) number of the row we are + * currently working on. + * + * @return the (0 based) number of the row + */ + public int getRow() { + return row; } - @Override - public LastCellOfRowDummyRecord copy() { - return this; - } + /** + * Returns the (0 based) number of the last column + * seen for this row. You should have already been + * called with that record. + * This is -1 in the case of there being no columns + * for the row. + * + * @return the (0 based) number of the last column + */ + public int getLastColumnNumber() { + return lastColumnNumber; + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return null; - } + @Override + public LastCellOfRowDummyRecord copy() { + return this; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "row", this::getRow, - "lastColumnNumber", this::getLastColumnNumber - ); - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return null; + } + + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "row", this::getRow, + "lastColumnNumber", this::getLastColumnNumber + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/MissingCellDummyRecord.java b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/MissingCellDummyRecord.java index 5b799855c2..c534d80f04 100644 --- a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/MissingCellDummyRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/MissingCellDummyRecord.java @@ -29,31 +29,31 @@ import org.apache.poi.util.GenericRecordUtil; * but still want to trigger something */ public final class MissingCellDummyRecord extends DummyRecordBase { - private final int row; - private final int column; + private final int row; + private final int column; - public MissingCellDummyRecord(int row, int column) { - this.row = row; - this.column = column; - } - public int getRow() { return row; } - public int getColumn() { return column; } + public MissingCellDummyRecord(int row, int column) { + this.row = row; + this.column = column; + } + public int getRow() { return row; } + public int getColumn() { return column; } - @Override - public MissingCellDummyRecord copy() { - return this; - } + @Override + public MissingCellDummyRecord copy() { + return this; + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return null; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return null; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "row", this::getRow, - "column", this::getColumn - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "row", this::getRow, + "column", this::getColumn + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/MissingRowDummyRecord.java b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/MissingRowDummyRecord.java index 7c13c48093..5f353327db 100644 --- a/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/MissingRowDummyRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/eventusermodel/dummyrecord/MissingRowDummyRecord.java @@ -29,29 +29,29 @@ import org.apache.poi.util.GenericRecordUtil; * want to trigger something */ public final class MissingRowDummyRecord extends DummyRecordBase { - private final int rowNumber; + private final int rowNumber; - public MissingRowDummyRecord(int rowNumber) { - this.rowNumber = rowNumber; - } - public int getRowNumber() { - return rowNumber; - } + public MissingRowDummyRecord(int rowNumber) { + this.rowNumber = rowNumber; + } + public int getRowNumber() { + return rowNumber; + } - @Override - public MissingRowDummyRecord copy() { - return this; - } + @Override + public MissingRowDummyRecord copy() { + return this; + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return null; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return null; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "rowNumber", this::getRowNumber - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "rowNumber", this::getRowNumber + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/extractor/ExcelExtractor.java b/poi/src/main/java/org/apache/poi/hssf/extractor/ExcelExtractor.java index 93fdb46093..9f8664c503 100644 --- a/poi/src/main/java/org/apache/poi/hssf/extractor/ExcelExtractor.java +++ b/poi/src/main/java/org/apache/poi/hssf/extractor/ExcelExtractor.java @@ -54,383 +54,383 @@ import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; * @see XLS2CSVmra */ public class ExcelExtractor implements POIOLE2TextExtractor, org.apache.poi.ss.extractor.ExcelExtractor { - private final HSSFWorkbook _wb; - private final HSSFDataFormatter _formatter; - private boolean doCloseFilesystem = true; - private boolean _includeSheetNames = true; - private boolean _shouldEvaluateFormulas = true; - private boolean _includeCellComments; - private boolean _includeBlankCells; - private boolean _includeHeadersFooters = true; + private final HSSFWorkbook _wb; + private final HSSFDataFormatter _formatter; + private boolean doCloseFilesystem = true; + private boolean _includeSheetNames = true; + private boolean _shouldEvaluateFormulas = true; + private boolean _includeCellComments; + private boolean _includeBlankCells; + private boolean _includeHeadersFooters = true; - public ExcelExtractor(HSSFWorkbook wb) { - _wb = wb; - _formatter = new HSSFDataFormatter(); - } + public ExcelExtractor(HSSFWorkbook wb) { + _wb = wb; + _formatter = new HSSFDataFormatter(); + } - public ExcelExtractor(POIFSFileSystem fs) throws IOException { - this(fs.getRoot()); - } + public ExcelExtractor(POIFSFileSystem fs) throws IOException { + this(fs.getRoot()); + } - public ExcelExtractor(DirectoryNode dir) throws IOException { - this(new HSSFWorkbook(dir, true)); - } + public ExcelExtractor(DirectoryNode dir) throws IOException { + this(new HSSFWorkbook(dir, true)); + } - private static final class CommandParseException extends Exception { - public CommandParseException(String msg) { - super(msg); - } - } - private static final class CommandArgs { - private final boolean _requestHelp; - private final File _inputFile; - private final boolean _showSheetNames; - private final boolean _evaluateFormulas; - private final boolean _showCellComments; - private final boolean _showBlankCells; - private final boolean _headersFooters; - public CommandArgs(String[] args) throws CommandParseException { - int nArgs = args.length; - File inputFile = null; - boolean requestHelp = false; - boolean showSheetNames = true; - boolean evaluateFormulas = true; - boolean showCellComments = false; - boolean showBlankCells = false; - boolean headersFooters = true; - for (int i=0; i= nArgs) { - throw new CommandParseException("Expected filename after '-i'"); - } - arg = args[i]; - if (inputFile != null) { - throw new CommandParseException("Only one input file can be supplied"); - } - inputFile = new File(arg); - if (!inputFile.exists()) { - throw new CommandParseException("Specified input file '" + arg + "' does not exist"); - } - if (inputFile.isDirectory()) { - throw new CommandParseException("Specified input file '" + arg + "' is a directory"); - } - continue; - } - if ("--show-sheet-names".equals(arg)) { - showSheetNames = parseBoolArg(args, ++i); - continue; - } - if ("--evaluate-formulas".equals(arg)) { - evaluateFormulas = parseBoolArg(args, ++i); - continue; - } - if ("--show-comments".equals(arg)) { - showCellComments = parseBoolArg(args, ++i); - continue; - } - if ("--show-blanks".equals(arg)) { - showBlankCells = parseBoolArg(args, ++i); - continue; - } - if ("--headers-footers".equals(arg)) { - headersFooters = parseBoolArg(args, ++i); - continue; - } - throw new CommandParseException("Invalid argument '" + arg + "'"); - } - _requestHelp = requestHelp; - _inputFile = inputFile; - _showSheetNames = showSheetNames; - _evaluateFormulas = evaluateFormulas; - _showCellComments = showCellComments; - _showBlankCells = showBlankCells; - _headersFooters = headersFooters; - } - private static boolean parseBoolArg(String[] args, int i) throws CommandParseException { - if (i >= args.length) { - throw new CommandParseException("Expected value after '" + args[i-1] + "'"); - } - String value = args[i].toUpperCase(Locale.ROOT); - if ("Y".equals(value) || "YES".equals(value) || "ON".equals(value) || "TRUE".equals(value)) { - return true; - } - if ("N".equals(value) || "NO".equals(value) || "OFF".equals(value) || "FALSE".equals(value)) { - return false; - } - throw new CommandParseException("Invalid value '" + args[i] + "' for '" + args[i-1] + "'. Expected 'Y' or 'N'"); - } - public boolean isRequestHelp() { - return _requestHelp; - } - public File getInputFile() { - return _inputFile; - } - public boolean shouldShowSheetNames() { - return _showSheetNames; - } - public boolean shouldEvaluateFormulas() { - return _evaluateFormulas; - } - public boolean shouldShowCellComments() { - return _showCellComments; - } - public boolean shouldShowBlankCells() { - return _showBlankCells; - } - public boolean shouldIncludeHeadersFooters() { - return _headersFooters; - } - } + private static final class CommandParseException extends Exception { + public CommandParseException(String msg) { + super(msg); + } + } + private static final class CommandArgs { + private final boolean _requestHelp; + private final File _inputFile; + private final boolean _showSheetNames; + private final boolean _evaluateFormulas; + private final boolean _showCellComments; + private final boolean _showBlankCells; + private final boolean _headersFooters; + public CommandArgs(String[] args) throws CommandParseException { + int nArgs = args.length; + File inputFile = null; + boolean requestHelp = false; + boolean showSheetNames = true; + boolean evaluateFormulas = true; + boolean showCellComments = false; + boolean showBlankCells = false; + boolean headersFooters = true; + for (int i=0; i= nArgs) { + throw new CommandParseException("Expected filename after '-i'"); + } + arg = args[i]; + if (inputFile != null) { + throw new CommandParseException("Only one input file can be supplied"); + } + inputFile = new File(arg); + if (!inputFile.exists()) { + throw new CommandParseException("Specified input file '" + arg + "' does not exist"); + } + if (inputFile.isDirectory()) { + throw new CommandParseException("Specified input file '" + arg + "' is a directory"); + } + continue; + } + if ("--show-sheet-names".equals(arg)) { + showSheetNames = parseBoolArg(args, ++i); + continue; + } + if ("--evaluate-formulas".equals(arg)) { + evaluateFormulas = parseBoolArg(args, ++i); + continue; + } + if ("--show-comments".equals(arg)) { + showCellComments = parseBoolArg(args, ++i); + continue; + } + if ("--show-blanks".equals(arg)) { + showBlankCells = parseBoolArg(args, ++i); + continue; + } + if ("--headers-footers".equals(arg)) { + headersFooters = parseBoolArg(args, ++i); + continue; + } + throw new CommandParseException("Invalid argument '" + arg + "'"); + } + _requestHelp = requestHelp; + _inputFile = inputFile; + _showSheetNames = showSheetNames; + _evaluateFormulas = evaluateFormulas; + _showCellComments = showCellComments; + _showBlankCells = showBlankCells; + _headersFooters = headersFooters; + } + private static boolean parseBoolArg(String[] args, int i) throws CommandParseException { + if (i >= args.length) { + throw new CommandParseException("Expected value after '" + args[i-1] + "'"); + } + String value = args[i].toUpperCase(Locale.ROOT); + if ("Y".equals(value) || "YES".equals(value) || "ON".equals(value) || "TRUE".equals(value)) { + return true; + } + if ("N".equals(value) || "NO".equals(value) || "OFF".equals(value) || "FALSE".equals(value)) { + return false; + } + throw new CommandParseException("Invalid value '" + args[i] + "' for '" + args[i-1] + "'. Expected 'Y' or 'N'"); + } + public boolean isRequestHelp() { + return _requestHelp; + } + public File getInputFile() { + return _inputFile; + } + public boolean shouldShowSheetNames() { + return _showSheetNames; + } + public boolean shouldEvaluateFormulas() { + return _evaluateFormulas; + } + public boolean shouldShowCellComments() { + return _showCellComments; + } + public boolean shouldShowBlankCells() { + return _showBlankCells; + } + public boolean shouldIncludeHeadersFooters() { + return _headersFooters; + } + } - private static void printUsageMessage(PrintStream ps) { - ps.println("Use:"); - ps.println(" " + ExcelExtractor.class.getName() + " [ [ [...]]] [-i ]"); - ps.println(" -i specifies input file (default is to use stdin)"); - ps.println(" Flags can be set on or off by using the values 'Y' or 'N'."); - ps.println(" Following are available flags and their default values:"); - ps.println(" --show-sheet-names Y"); - ps.println(" --evaluate-formulas Y"); - ps.println(" --show-comments N"); - ps.println(" --show-blanks Y"); - ps.println(" --headers-footers Y"); - } + private static void printUsageMessage(PrintStream ps) { + ps.println("Use:"); + ps.println(" " + ExcelExtractor.class.getName() + " [ [ [...]]] [-i ]"); + ps.println(" -i specifies input file (default is to use stdin)"); + ps.println(" Flags can be set on or off by using the values 'Y' or 'N'."); + ps.println(" Following are available flags and their default values:"); + ps.println(" --show-sheet-names Y"); + ps.println(" --evaluate-formulas Y"); + ps.println(" --show-comments N"); + ps.println(" --show-blanks Y"); + ps.println(" --headers-footers Y"); + } - /** - * Command line extractor. - * - * @param args the command line parameters - * - * @throws IOException if the file can't be read or contains errors - */ - public static void main(String[] args) throws IOException { + /** + * Command line extractor. + * + * @param args the command line parameters + * + * @throws IOException if the file can't be read or contains errors + */ + public static void main(String[] args) throws IOException { - CommandArgs cmdArgs; - try { - cmdArgs = new CommandArgs(args); - } catch (CommandParseException e) { - System.err.println(e.getMessage()); - printUsageMessage(System.err); - System.exit(1); - return; // suppress compiler error - } + CommandArgs cmdArgs; + try { + cmdArgs = new CommandArgs(args); + } catch (CommandParseException e) { + System.err.println(e.getMessage()); + printUsageMessage(System.err); + System.exit(1); + return; // suppress compiler error + } - if (cmdArgs.isRequestHelp()) { - printUsageMessage(System.out); - return; - } + if (cmdArgs.isRequestHelp()) { + printUsageMessage(System.out); + return; + } - try (InputStream is = cmdArgs.getInputFile() == null ? System.in : new FileInputStream(cmdArgs.getInputFile()); - HSSFWorkbook wb = new HSSFWorkbook(is); - ExcelExtractor extractor = new ExcelExtractor(wb) - ) { - extractor.setIncludeSheetNames(cmdArgs.shouldShowSheetNames()); - extractor.setFormulasNotResults(!cmdArgs.shouldEvaluateFormulas()); - extractor.setIncludeCellComments(cmdArgs.shouldShowCellComments()); - extractor.setIncludeBlankCells(cmdArgs.shouldShowBlankCells()); - extractor.setIncludeHeadersFooters(cmdArgs.shouldIncludeHeadersFooters()); - System.out.println(extractor.getText()); - } - } + try (InputStream is = cmdArgs.getInputFile() == null ? System.in : new FileInputStream(cmdArgs.getInputFile()); + HSSFWorkbook wb = new HSSFWorkbook(is); + ExcelExtractor extractor = new ExcelExtractor(wb) + ) { + extractor.setIncludeSheetNames(cmdArgs.shouldShowSheetNames()); + extractor.setFormulasNotResults(!cmdArgs.shouldEvaluateFormulas()); + extractor.setIncludeCellComments(cmdArgs.shouldShowCellComments()); + extractor.setIncludeBlankCells(cmdArgs.shouldShowBlankCells()); + extractor.setIncludeHeadersFooters(cmdArgs.shouldIncludeHeadersFooters()); + System.out.println(extractor.getText()); + } + } - @Override + @Override public void setIncludeSheetNames(boolean includeSheetNames) { - _includeSheetNames = includeSheetNames; - } + _includeSheetNames = includeSheetNames; + } - @Override + @Override public void setFormulasNotResults(boolean formulasNotResults) { - _shouldEvaluateFormulas = !formulasNotResults; - } + _shouldEvaluateFormulas = !formulasNotResults; + } - @Override + @Override public void setIncludeCellComments(boolean includeCellComments) { - _includeCellComments = includeCellComments; - } + _includeCellComments = includeCellComments; + } - /** - * Should blank cells be output? Default is to only - * output cells that are present in the file and are - * non-blank. - * - * @param includeBlankCells {@code true} if blank cells should be included - */ - public void setIncludeBlankCells(boolean includeBlankCells) { - _includeBlankCells = includeBlankCells; - } + /** + * Should blank cells be output? Default is to only + * output cells that are present in the file and are + * non-blank. + * + * @param includeBlankCells {@code true} if blank cells should be included + */ + public void setIncludeBlankCells(boolean includeBlankCells) { + _includeBlankCells = includeBlankCells; + } - @Override + @Override public void setIncludeHeadersFooters(boolean includeHeadersFooters) { - _includeHeadersFooters = includeHeadersFooters; - } + _includeHeadersFooters = includeHeadersFooters; + } - @Override + @Override public String getText() { - StringBuilder text = new StringBuilder(); + StringBuilder text = new StringBuilder(); - // We don't care about the difference between - // null (missing) and blank cells - _wb.setMissingCellPolicy(MissingCellPolicy.RETURN_BLANK_AS_NULL); + // We don't care about the difference between + // null (missing) and blank cells + _wb.setMissingCellPolicy(MissingCellPolicy.RETURN_BLANK_AS_NULL); - // Process each sheet in turn - for(int i=0;i<_wb.getNumberOfSheets();i++) { - HSSFSheet sheet = _wb.getSheetAt(i); - if(sheet == null) { continue; } + // Process each sheet in turn + for(int i=0;i<_wb.getNumberOfSheets();i++) { + HSSFSheet sheet = _wb.getSheetAt(i); + if(sheet == null) { continue; } - if(_includeSheetNames) { - String name = _wb.getSheetName(i); - if(name != null) { - text.append(name); - text.append("\n"); - } - } + if(_includeSheetNames) { + String name = _wb.getSheetName(i); + if(name != null) { + text.append(name); + text.append("\n"); + } + } - // Header text, if there is any - if(_includeHeadersFooters) { - text.append(_extractHeaderFooter(sheet.getHeader())); - } + // Header text, if there is any + if(_includeHeadersFooters) { + text.append(_extractHeaderFooter(sheet.getHeader())); + } - int firstRow = sheet.getFirstRowNum(); - int lastRow = sheet.getLastRowNum(); - for(int j=firstRow;j<=lastRow;j++) { - HSSFRow row = sheet.getRow(j); - if(row == null) { continue; } + int firstRow = sheet.getFirstRowNum(); + int lastRow = sheet.getLastRowNum(); + for(int j=firstRow;j<=lastRow;j++) { + HSSFRow row = sheet.getRow(j); + if(row == null) { continue; } - // Check each cell in turn - int firstCell = row.getFirstCellNum(); - int lastCell = row.getLastCellNum(); - if(_includeBlankCells) { - firstCell = 0; - } + // Check each cell in turn + int firstCell = row.getFirstCellNum(); + int lastCell = row.getLastCellNum(); + if(_includeBlankCells) { + firstCell = 0; + } - for(int k=firstCell;k 0) { - text.append(str); - } - break; - case NUMERIC: - HSSFCellStyle style = cell.getCellStyle(); - double nVal = cell.getNumericCellValue(); - short df = style.getDataFormat(); - String dfs = style.getDataFormatString(); - text.append(_formatter.formatRawCellContents(nVal, df, dfs)); - break; - case BOOLEAN: - text.append(cell.getBooleanCellValue()); - break; - case ERROR: - text.append(ErrorEval.getText(cell.getErrorCellValue())); - break; - default: - throw new IllegalStateException("Unexpected cell cached formula result type: " + cell.getCachedFormulaResultType()); + if(cell == null) { + // Only output if requested + outputContents = _includeBlankCells; + } else { + switch(cell.getCellType()) { + case STRING: + text.append(cell.getRichStringCellValue().getString()); + break; + case NUMERIC: + text.append(_formatter.formatCellValue(cell)); + break; + case BOOLEAN: + text.append(cell.getBooleanCellValue()); + break; + case ERROR: + text.append(ErrorEval.getText(cell.getErrorCellValue())); + break; + case FORMULA: + if(!_shouldEvaluateFormulas) { + text.append(cell.getCellFormula()); + } else { + switch(cell.getCachedFormulaResultType()) { + case STRING: + HSSFRichTextString str = cell.getRichStringCellValue(); + if(str != null && str.length() > 0) { + text.append(str); + } + break; + case NUMERIC: + HSSFCellStyle style = cell.getCellStyle(); + double nVal = cell.getNumericCellValue(); + short df = style.getDataFormat(); + String dfs = style.getDataFormatString(); + text.append(_formatter.formatRawCellContents(nVal, df, dfs)); + break; + case BOOLEAN: + text.append(cell.getBooleanCellValue()); + break; + case ERROR: + text.append(ErrorEval.getText(cell.getErrorCellValue())); + break; + default: + throw new IllegalStateException("Unexpected cell cached formula result type: " + cell.getCachedFormulaResultType()); - } - } - break; - default: - throw new RuntimeException("Unexpected cell type (" + cell.getCellType() + ")"); - } + } + } + break; + default: + throw new RuntimeException("Unexpected cell type (" + cell.getCellType() + ")"); + } - // Output the comment, if requested and exists - HSSFComment comment = cell.getCellComment(); - if(_includeCellComments && comment != null) { - // Replace any newlines with spaces, otherwise it - // breaks the output - String commentText = comment.getString().getString().replace('\n', ' '); - text.append(" Comment by ").append(comment.getAuthor()).append(": ").append(commentText); - } - } + // Output the comment, if requested and exists + HSSFComment comment = cell.getCellComment(); + if(_includeCellComments && comment != null) { + // Replace any newlines with spaces, otherwise it + // breaks the output + String commentText = comment.getString().getString().replace('\n', ' '); + text.append(" Comment by ").append(comment.getAuthor()).append(": ").append(commentText); + } + } - // Output a tab if we're not on the last cell - if(outputContents && k < (lastCell-1)) { - text.append("\t"); - } - } + // Output a tab if we're not on the last cell + if(outputContents && k < (lastCell-1)) { + text.append("\t"); + } + } - // Finish off the row - text.append("\n"); - } + // Finish off the row + text.append("\n"); + } - // Finally Footer text, if there is any - if(_includeHeadersFooters) { - text.append(_extractHeaderFooter(sheet.getFooter())); - } - } + // Finally Footer text, if there is any + if(_includeHeadersFooters) { + text.append(_extractHeaderFooter(sheet.getFooter())); + } + } - return text.toString(); - } + return text.toString(); + } - public static String _extractHeaderFooter(HeaderFooter hf) { - StringBuilder text = new StringBuilder(); + public static String _extractHeaderFooter(HeaderFooter hf) { + StringBuilder text = new StringBuilder(); - if(hf.getLeft() != null) { - text.append(hf.getLeft()); - } - if(hf.getCenter() != null) { - if(text.length() > 0) - text.append("\t"); - text.append(hf.getCenter()); - } - if(hf.getRight() != null) { - if(text.length() > 0) - text.append("\t"); - text.append(hf.getRight()); - } - if(text.length() > 0) - text.append("\n"); + if(hf.getLeft() != null) { + text.append(hf.getLeft()); + } + if(hf.getCenter() != null) { + if(text.length() > 0) + text.append("\t"); + text.append(hf.getCenter()); + } + if(hf.getRight() != null) { + if(text.length() > 0) + text.append("\t"); + text.append(hf.getRight()); + } + if(text.length() > 0) + text.append("\n"); - return text.toString(); - } + return text.toString(); + } - @Override - public HSSFWorkbook getDocument() { - return _wb; - } + @Override + public HSSFWorkbook getDocument() { + return _wb; + } - @Override - public void setCloseFilesystem(boolean doCloseFilesystem) { - this.doCloseFilesystem = doCloseFilesystem; - } + @Override + public void setCloseFilesystem(boolean doCloseFilesystem) { + this.doCloseFilesystem = doCloseFilesystem; + } - @Override - public boolean isCloseFilesystem() { - return doCloseFilesystem; - } + @Override + public boolean isCloseFilesystem() { + return doCloseFilesystem; + } - @Override - public HSSFWorkbook getFilesystem() { - return _wb; - } + @Override + public HSSFWorkbook getFilesystem() { + return _wb; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/extractor/OldExcelExtractor.java b/poi/src/main/java/org/apache/poi/hssf/extractor/OldExcelExtractor.java index d5ef5142e7..867950f39a 100644 --- a/poi/src/main/java/org/apache/poi/hssf/extractor/OldExcelExtractor.java +++ b/poi/src/main/java/org/apache/poi/hssf/extractor/OldExcelExtractor.java @@ -316,38 +316,38 @@ public class OldExcelExtractor implements POITextExtractor { @Override public POITextExtractor getMetadataTextExtractor() { - return new POITextExtractor() { + return new POITextExtractor() { - @Override - public String getText() { - return ""; - } + @Override + public String getText() { + return ""; + } - @Override - public POITextExtractor getMetadataTextExtractor() { - throw new IllegalStateException("You already have the Metadata Text Extractor, not recursing!"); - } + @Override + public POITextExtractor getMetadataTextExtractor() { + throw new IllegalStateException("You already have the Metadata Text Extractor, not recursing!"); + } - @Override - public void setCloseFilesystem(boolean doCloseFilesystem) { + @Override + public void setCloseFilesystem(boolean doCloseFilesystem) { - } + } - @Override - public boolean isCloseFilesystem() { - return toClose != null; - } + @Override + public boolean isCloseFilesystem() { + return toClose != null; + } - @Override - public Closeable getFilesystem() { - return toClose; - } + @Override + public Closeable getFilesystem() { + return toClose; + } - @Override - public Object getDocument() { - return ris; - } - }; + @Override + public Object getDocument() { + return ris; + } + }; } @Override diff --git a/poi/src/main/java/org/apache/poi/hssf/model/DrawingManager2.java b/poi/src/main/java/org/apache/poi/hssf/model/DrawingManager2.java index 7502b4aee9..599a1ae7c4 100644 --- a/poi/src/main/java/org/apache/poi/hssf/model/DrawingManager2.java +++ b/poi/src/main/java/org/apache/poi/hssf/model/DrawingManager2.java @@ -40,7 +40,7 @@ public class DrawingManager2 { * Clears the cached list of drawing groups */ public void clearDrawingGroups() { - drawingGroups.clear(); + drawingGroups.clear(); } /** diff --git a/poi/src/main/java/org/apache/poi/hssf/model/InternalSheet.java b/poi/src/main/java/org/apache/poi/hssf/model/InternalSheet.java index 2ec71a52fa..4821047f7c 100644 --- a/poi/src/main/java/org/apache/poi/hssf/model/InternalSheet.java +++ b/poi/src/main/java/org/apache/poi/hssf/model/InternalSheet.java @@ -249,7 +249,7 @@ public final class InternalSheet { } if (recSid == FeatRecord.sid || - recSid == FeatHdrRecord.sid) { + recSid == FeatHdrRecord.sid) { records.add(rec); continue; } @@ -737,7 +737,7 @@ public final class InternalSheet { * @return Iterator of CellValueRecordInterface representing the value records */ public Iterator getCellValueIterator(){ - return _rowsAggregate.getCellValueIterator(); + return _rowsAggregate.getCellValueIterator(); } /** diff --git a/poi/src/main/java/org/apache/poi/hssf/model/InternalWorkbook.java b/poi/src/main/java/org/apache/poi/hssf/model/InternalWorkbook.java index 95e156618b..c811f5eff1 100644 --- a/poi/src/main/java/org/apache/poi/hssf/model/InternalWorkbook.java +++ b/poi/src/main/java/org/apache/poi/hssf/model/InternalWorkbook.java @@ -136,11 +136,11 @@ public final class InternalWorkbook { private final List hyperlinks; /** the number of extended format records */ - private int numxfs; + private int numxfs; /** the number of font records */ - private int numfonts; + private int numfonts; /** holds the max format id */ - private int maxformatid; + private int maxformatid; /** whether 1904 date windowing is being used */ private boolean uses1904datewindowing; private DrawingManager2 drawingManager; @@ -156,17 +156,17 @@ public final class InternalWorkbook { private final Map commentRecords; private InternalWorkbook() { - records = new WorkbookRecordList(); + records = new WorkbookRecordList(); - boundsheets = new ArrayList<>(); - formats = new ArrayList<>(); - hyperlinks = new ArrayList<>(); - numxfs = 0; - numfonts = 0; - maxformatid = -1; - uses1904datewindowing = false; - escherBSERecords = new ArrayList<>(); - commentRecords = new LinkedHashMap<>(); + boundsheets = new ArrayList<>(); + formats = new ArrayList<>(); + hyperlinks = new ArrayList<>(); + numxfs = 0; + numfonts = 0; + maxformatid = -1; + uses1904datewindowing = false; + escherBSERecords = new ArrayList<>(); + commentRecords = new LinkedHashMap<>(); } /** @@ -609,7 +609,7 @@ public final class InternalWorkbook { int pos0 = initialBspos - (boundsheets.size() - 1); Record removed = records.get(pos0 + sheetNumber); records.remove(pos0 + sheetNumber); - records.add(pos0 + pos, removed); + records.add(pos0 + pos, removed); records.setBspos(initialBspos); } @@ -2224,17 +2224,17 @@ public final class InternalWorkbook { } - /** - * Changes an external referenced file to another file. - * A formular in Excel which refers a cell in another file is saved in two parts: - * The referenced file is stored in an reference table. the row/cell information is saved separate. - * This method invokation will only change the reference in the lookup-table itself. - * @param oldUrl The old URL to search for and which is to be replaced - * @param newUrl The URL replacement - * @return true if the oldUrl was found and replaced with newUrl. Otherwise false - */ + /** + * Changes an external referenced file to another file. + * A formular in Excel which refers a cell in another file is saved in two parts: + * The referenced file is stored in an reference table. the row/cell information is saved separate. + * This method invokation will only change the reference in the lookup-table itself. + * @param oldUrl The old URL to search for and which is to be replaced + * @param newUrl The URL replacement + * @return true if the oldUrl was found and replaced with newUrl. Otherwise false + */ public boolean changeExternalReference(String oldUrl, String newUrl) { - return linkTable.changeExternalReference(oldUrl, newUrl); + return linkTable.changeExternalReference(oldUrl, newUrl); } /** diff --git a/poi/src/main/java/org/apache/poi/hssf/model/RecordOrderer.java b/poi/src/main/java/org/apache/poi/hssf/model/RecordOrderer.java index f1dd369a91..3d9eaa2669 100644 --- a/poi/src/main/java/org/apache/poi/hssf/model/RecordOrderer.java +++ b/poi/src/main/java/org/apache/poi/hssf/model/RecordOrderer.java @@ -80,379 +80,379 @@ import org.apache.poi.hssf.record.pivottable.ViewDefinitionRecord; */ final class RecordOrderer { - // TODO - simplify logic using a generalised record ordering + // TODO - simplify logic using a generalised record ordering - private RecordOrderer() { - // no instances of this class - } - /** - * Adds the specified new record in the correct place in sheet records list - */ - public static void addNewSheetRecord(List sheetRecords, RecordBase newRecord) { - int index = findSheetInsertPos(sheetRecords, newRecord.getClass()); - sheetRecords.add(index, newRecord); - } + private RecordOrderer() { + // no instances of this class + } + /** + * Adds the specified new record in the correct place in sheet records list + */ + public static void addNewSheetRecord(List sheetRecords, RecordBase newRecord) { + int index = findSheetInsertPos(sheetRecords, newRecord.getClass()); + sheetRecords.add(index, newRecord); + } - private static int findSheetInsertPos(List records, Class recClass) { - if (recClass == DataValidityTable.class) { - return findDataValidationTableInsertPos(records); - } - if (recClass == MergedCellsTable.class) { - return findInsertPosForNewMergedRecordTable(records); - } - if (recClass == ConditionalFormattingTable.class) { - return findInsertPosForNewCondFormatTable(records); - } - if (recClass == GutsRecord.class) { - return getGutsRecordInsertPos(records); - } - if (recClass == PageSettingsBlock.class) { - return getPageBreakRecordInsertPos(records); - } - if (recClass == WorksheetProtectionBlock.class) { - return getWorksheetProtectionBlockInsertPos(records); - } - throw new RuntimeException("Unexpected record class (" + recClass.getName() + ")"); - } + private static int findSheetInsertPos(List records, Class recClass) { + if (recClass == DataValidityTable.class) { + return findDataValidationTableInsertPos(records); + } + if (recClass == MergedCellsTable.class) { + return findInsertPosForNewMergedRecordTable(records); + } + if (recClass == ConditionalFormattingTable.class) { + return findInsertPosForNewCondFormatTable(records); + } + if (recClass == GutsRecord.class) { + return getGutsRecordInsertPos(records); + } + if (recClass == PageSettingsBlock.class) { + return getPageBreakRecordInsertPos(records); + } + if (recClass == WorksheetProtectionBlock.class) { + return getWorksheetProtectionBlockInsertPos(records); + } + throw new RuntimeException("Unexpected record class (" + recClass.getName() + ")"); + } - /** - * Finds the index where the protection block should be inserted - * @param records the records for this sheet - *

-	 * + BOF
-	 * o INDEX
-	 * o Calculation Settings Block
-	 * o PRINTHEADERS
-	 * o PRINTGRIDLINES
-	 * o GRIDSET
-	 * o GUTS
-	 * o DEFAULTROWHEIGHT
-	 * o SHEETPR
-	 * o Page Settings Block
-	 * o Worksheet Protection Block
-	 * o DEFCOLWIDTH
-	 * oo COLINFO
-	 * o SORT
-	 * + DIMENSION
-	 * 
- */ - private static int getWorksheetProtectionBlockInsertPos(List records) { - int i = getDimensionsIndex(records); - while (i > 0) { - i--; - Object rb = records.get(i); - if (!isProtectionSubsequentRecord(rb)) { - return i+1; - } - } - throw new IllegalStateException("did not find insert pos for protection block"); - } + /** + * Finds the index where the protection block should be inserted + * @param records the records for this sheet + *
+     * + BOF
+     * o INDEX
+     * o Calculation Settings Block
+     * o PRINTHEADERS
+     * o PRINTGRIDLINES
+     * o GRIDSET
+     * o GUTS
+     * o DEFAULTROWHEIGHT
+     * o SHEETPR
+     * o Page Settings Block
+     * o Worksheet Protection Block
+     * o DEFCOLWIDTH
+     * oo COLINFO
+     * o SORT
+     * + DIMENSION
+     * 
+ */ + private static int getWorksheetProtectionBlockInsertPos(List records) { + int i = getDimensionsIndex(records); + while (i > 0) { + i--; + Object rb = records.get(i); + if (!isProtectionSubsequentRecord(rb)) { + return i+1; + } + } + throw new IllegalStateException("did not find insert pos for protection block"); + } - /** - * These records may occur between the 'Worksheet Protection Block' and DIMENSION: - *
-	 * o DEFCOLWIDTH
-	 * oo COLINFO
-	 * o SORT
-	 * 
- */ - private static boolean isProtectionSubsequentRecord(Object rb) { - if (rb instanceof ColumnInfoRecordsAggregate) { - return true; // oo COLINFO - } - if (rb instanceof Record) { - Record record = (org.apache.poi.hssf.record.Record) rb; - switch (record.getSid()) { - case DefaultColWidthRecord.sid: - case UnknownRecord.SORT_0090: - return true; - } - } - return false; - } + /** + * These records may occur between the 'Worksheet Protection Block' and DIMENSION: + *
+     * o DEFCOLWIDTH
+     * oo COLINFO
+     * o SORT
+     * 
+ */ + private static boolean isProtectionSubsequentRecord(Object rb) { + if (rb instanceof ColumnInfoRecordsAggregate) { + return true; // oo COLINFO + } + if (rb instanceof Record) { + Record record = (org.apache.poi.hssf.record.Record) rb; + switch (record.getSid()) { + case DefaultColWidthRecord.sid: + case UnknownRecord.SORT_0090: + return true; + } + } + return false; + } - private static int getPageBreakRecordInsertPos(List records) { - int dimensionsIndex = getDimensionsIndex(records); - int i = dimensionsIndex-1; - while (i > 0) { - i--; - Object rb = records.get(i); - if (isPageBreakPriorRecord(rb)) { - return i+1; - } - } - throw new RuntimeException("Did not find insert point for GUTS"); - } - private static boolean isPageBreakPriorRecord(Object rb) { - if (rb instanceof Record) { - Record record = (org.apache.poi.hssf.record.Record) rb; - switch (record.getSid()) { - case BOFRecord.sid: - case IndexRecord.sid: - // calc settings block - case UncalcedRecord.sid: - case CalcCountRecord.sid: - case CalcModeRecord.sid: - case PrecisionRecord.sid: - case RefModeRecord.sid: - case DeltaRecord.sid: - case IterationRecord.sid: - case DateWindow1904Record.sid: - case SaveRecalcRecord.sid: - // end calc settings - case PrintHeadersRecord.sid: - case PrintGridlinesRecord.sid: - case GridsetRecord.sid: - case DefaultRowHeightRecord.sid: - case UnknownRecord.SHEETPR_0081: - return true; - // next is the 'Worksheet Protection Block' - } - } - return false; - } - /** - * Find correct position to add new CFHeader record - */ - private static int findInsertPosForNewCondFormatTable(List records) { + private static int getPageBreakRecordInsertPos(List records) { + int dimensionsIndex = getDimensionsIndex(records); + int i = dimensionsIndex-1; + while (i > 0) { + i--; + Object rb = records.get(i); + if (isPageBreakPriorRecord(rb)) { + return i+1; + } + } + throw new RuntimeException("Did not find insert point for GUTS"); + } + private static boolean isPageBreakPriorRecord(Object rb) { + if (rb instanceof Record) { + Record record = (org.apache.poi.hssf.record.Record) rb; + switch (record.getSid()) { + case BOFRecord.sid: + case IndexRecord.sid: + // calc settings block + case UncalcedRecord.sid: + case CalcCountRecord.sid: + case CalcModeRecord.sid: + case PrecisionRecord.sid: + case RefModeRecord.sid: + case DeltaRecord.sid: + case IterationRecord.sid: + case DateWindow1904Record.sid: + case SaveRecalcRecord.sid: + // end calc settings + case PrintHeadersRecord.sid: + case PrintGridlinesRecord.sid: + case GridsetRecord.sid: + case DefaultRowHeightRecord.sid: + case UnknownRecord.SHEETPR_0081: + return true; + // next is the 'Worksheet Protection Block' + } + } + return false; + } + /** + * Find correct position to add new CFHeader record + */ + private static int findInsertPosForNewCondFormatTable(List records) { - for (int i = records.size() - 2; i >= 0; i--) { // -2 to skip EOF record - Object rb = records.get(i); - if (rb instanceof MergedCellsTable) { - return i + 1; - } - if (rb instanceof DataValidityTable) { - continue; - } + for (int i = records.size() - 2; i >= 0; i--) { // -2 to skip EOF record + Object rb = records.get(i); + if (rb instanceof MergedCellsTable) { + return i + 1; + } + if (rb instanceof DataValidityTable) { + continue; + } - Record rec = (org.apache.poi.hssf.record.Record) rb; - switch (rec.getSid()) { - case WindowTwoRecord.sid: - case SCLRecord.sid: - case PaneRecord.sid: - case SelectionRecord.sid: - case UnknownRecord.STANDARDWIDTH_0099: - // MergedCellsTable usually here - case UnknownRecord.LABELRANGES_015F: - case UnknownRecord.PHONETICPR_00EF: - // ConditionalFormattingTable goes here - return i + 1; - // HyperlinkTable (not aggregated by POI yet) - // DataValidityTable - } - } - throw new RuntimeException("Did not find Window2 record"); - } + Record rec = (org.apache.poi.hssf.record.Record) rb; + switch (rec.getSid()) { + case WindowTwoRecord.sid: + case SCLRecord.sid: + case PaneRecord.sid: + case SelectionRecord.sid: + case UnknownRecord.STANDARDWIDTH_0099: + // MergedCellsTable usually here + case UnknownRecord.LABELRANGES_015F: + case UnknownRecord.PHONETICPR_00EF: + // ConditionalFormattingTable goes here + return i + 1; + // HyperlinkTable (not aggregated by POI yet) + // DataValidityTable + } + } + throw new RuntimeException("Did not find Window2 record"); + } - private static int findInsertPosForNewMergedRecordTable(List records) { - for (int i = records.size() - 2; i >= 0; i--) { // -2 to skip EOF record - Object rb = records.get(i); - if (!(rb instanceof Record)) { - // DataValidityTable, ConditionalFormattingTable, - // even PageSettingsBlock (which doesn't normally appear after 'View Settings') - continue; - } - Record rec = (org.apache.poi.hssf.record.Record) rb; - switch (rec.getSid()) { - // 'View Settings' (4 records) - case WindowTwoRecord.sid: - case SCLRecord.sid: - case PaneRecord.sid: - case SelectionRecord.sid: + private static int findInsertPosForNewMergedRecordTable(List records) { + for (int i = records.size() - 2; i >= 0; i--) { // -2 to skip EOF record + Object rb = records.get(i); + if (!(rb instanceof Record)) { + // DataValidityTable, ConditionalFormattingTable, + // even PageSettingsBlock (which doesn't normally appear after 'View Settings') + continue; + } + Record rec = (org.apache.poi.hssf.record.Record) rb; + switch (rec.getSid()) { + // 'View Settings' (4 records) + case WindowTwoRecord.sid: + case SCLRecord.sid: + case PaneRecord.sid: + case SelectionRecord.sid: - case UnknownRecord.STANDARDWIDTH_0099: - return i + 1; - } - } - throw new RuntimeException("Did not find Window2 record"); - } + case UnknownRecord.STANDARDWIDTH_0099: + return i + 1; + } + } + throw new RuntimeException("Did not find Window2 record"); + } - /** - * Finds the index where the sheet validations header record should be inserted - * @param records the records for this sheet - * - * + WINDOW2 - * o SCL - * o PANE - * oo SELECTION - * o STANDARDWIDTH - * oo MERGEDCELLS - * o LABELRANGES - * o PHONETICPR - * o Conditional Formatting Table - * o Hyperlink Table - * o Data Validity Table - * o SHEETLAYOUT - * o SHEETPROTECTION - * o RANGEPROTECTION - * + EOF - */ - private static int findDataValidationTableInsertPos(List records) { - int i = records.size() - 1; - if (!(records.get(i) instanceof EOFRecord)) { - throw new IllegalStateException("Last sheet record should be EOFRecord"); - } - while (i > 0) { - i--; - RecordBase rb = records.get(i); - if (isDVTPriorRecord(rb)) { - Record nextRec = (org.apache.poi.hssf.record.Record) records.get(i + 1); - if (!isDVTSubsequentRecord(nextRec.getSid())) { - throw new IllegalStateException("Unexpected (" + nextRec.getClass().getName() - + ") found after (" + rb.getClass().getName() + ")"); - } - return i+1; - } - Record rec = (org.apache.poi.hssf.record.Record) rb; - if (!isDVTSubsequentRecord(rec.getSid())) { - throw new IllegalStateException("Unexpected (" + rec.getClass().getName() - + ") while looking for DV Table insert pos"); - } - } - return 0; - } + /** + * Finds the index where the sheet validations header record should be inserted + * @param records the records for this sheet + * + * + WINDOW2 + * o SCL + * o PANE + * oo SELECTION + * o STANDARDWIDTH + * oo MERGEDCELLS + * o LABELRANGES + * o PHONETICPR + * o Conditional Formatting Table + * o Hyperlink Table + * o Data Validity Table + * o SHEETLAYOUT + * o SHEETPROTECTION + * o RANGEPROTECTION + * + EOF + */ + private static int findDataValidationTableInsertPos(List records) { + int i = records.size() - 1; + if (!(records.get(i) instanceof EOFRecord)) { + throw new IllegalStateException("Last sheet record should be EOFRecord"); + } + while (i > 0) { + i--; + RecordBase rb = records.get(i); + if (isDVTPriorRecord(rb)) { + Record nextRec = (org.apache.poi.hssf.record.Record) records.get(i + 1); + if (!isDVTSubsequentRecord(nextRec.getSid())) { + throw new IllegalStateException("Unexpected (" + nextRec.getClass().getName() + + ") found after (" + rb.getClass().getName() + ")"); + } + return i+1; + } + Record rec = (org.apache.poi.hssf.record.Record) rb; + if (!isDVTSubsequentRecord(rec.getSid())) { + throw new IllegalStateException("Unexpected (" + rec.getClass().getName() + + ") while looking for DV Table insert pos"); + } + } + return 0; + } - private static boolean isDVTPriorRecord(RecordBase rb) { - if (rb instanceof MergedCellsTable || rb instanceof ConditionalFormattingTable) { - return true; - } - short sid = ((org.apache.poi.hssf.record.Record)rb).getSid(); - switch(sid) { - case WindowTwoRecord.sid: - case UnknownRecord.SCL_00A0: - case PaneRecord.sid: - case SelectionRecord.sid: - case UnknownRecord.STANDARDWIDTH_0099: - // MergedCellsTable - case UnknownRecord.LABELRANGES_015F: - case UnknownRecord.PHONETICPR_00EF: - // ConditionalFormattingTable - case HyperlinkRecord.sid: - case UnknownRecord.QUICKTIP_0800: + private static boolean isDVTPriorRecord(RecordBase rb) { + if (rb instanceof MergedCellsTable || rb instanceof ConditionalFormattingTable) { + return true; + } + short sid = ((org.apache.poi.hssf.record.Record)rb).getSid(); + switch(sid) { + case WindowTwoRecord.sid: + case UnknownRecord.SCL_00A0: + case PaneRecord.sid: + case SelectionRecord.sid: + case UnknownRecord.STANDARDWIDTH_0099: + // MergedCellsTable + case UnknownRecord.LABELRANGES_015F: + case UnknownRecord.PHONETICPR_00EF: + // ConditionalFormattingTable + case HyperlinkRecord.sid: + case UnknownRecord.QUICKTIP_0800: // name of a VBA module case UnknownRecord.CODENAME_1BA: - return true; - } - return false; - } + return true; + } + return false; + } - private static boolean isDVTSubsequentRecord(short sid) { - switch(sid) { - case UnknownRecord.SHEETEXT_0862: - case UnknownRecord.SHEETPROTECTION_0867: - case UnknownRecord.PLV_MAC: - case FeatRecord.sid: - case EOFRecord.sid: - return true; - } - return false; - } - /** - * DIMENSIONS record is always present - */ - private static int getDimensionsIndex(List records) { - int nRecs = records.size(); - for(int i=0; i records) { + int nRecs = records.size(); + for(int i=0; i records) { - int dimensionsIndex = getDimensionsIndex(records); - int i = dimensionsIndex-1; - while (i > 0) { - i--; - RecordBase rb = records.get(i); - if (isGutsPriorRecord(rb)) { - return i+1; - } - } - throw new RuntimeException("Did not find insert point for GUTS"); - } + private static int getGutsRecordInsertPos(List records) { + int dimensionsIndex = getDimensionsIndex(records); + int i = dimensionsIndex-1; + while (i > 0) { + i--; + RecordBase rb = records.get(i); + if (isGutsPriorRecord(rb)) { + return i+1; + } + } + throw new RuntimeException("Did not find insert point for GUTS"); + } - private static boolean isGutsPriorRecord(RecordBase rb) { - if (rb instanceof Record) { - Record record = (org.apache.poi.hssf.record.Record) rb; - switch (record.getSid()) { - case BOFRecord.sid: - case IndexRecord.sid: - // calc settings block - case UncalcedRecord.sid: - case CalcCountRecord.sid: - case CalcModeRecord.sid: - case PrecisionRecord.sid: - case RefModeRecord.sid: - case DeltaRecord.sid: - case IterationRecord.sid: - case DateWindow1904Record.sid: - case SaveRecalcRecord.sid: - // end calc settings - case PrintHeadersRecord.sid: - case PrintGridlinesRecord.sid: - case GridsetRecord.sid: - return true; - // DefaultRowHeightRecord.sid is next - } - } - return false; - } - /** - * @return true if the specified record ID terminates a sequence of Row block records - * It is assumed that at least one row or cell value record has been found prior to the current - * record - */ - public static boolean isEndOfRowBlock(int sid) { - switch(sid) { - case ViewDefinitionRecord.sid: - // should have been prefixed with DrawingRecord (0x00EC), but bug 46280 seems to allow this - case DrawingRecord.sid: - case DrawingSelectionRecord.sid: - case ObjRecord.sid: - case TextObjectRecord.sid: + private static boolean isGutsPriorRecord(RecordBase rb) { + if (rb instanceof Record) { + Record record = (org.apache.poi.hssf.record.Record) rb; + switch (record.getSid()) { + case BOFRecord.sid: + case IndexRecord.sid: + // calc settings block + case UncalcedRecord.sid: + case CalcCountRecord.sid: + case CalcModeRecord.sid: + case PrecisionRecord.sid: + case RefModeRecord.sid: + case DeltaRecord.sid: + case IterationRecord.sid: + case DateWindow1904Record.sid: + case SaveRecalcRecord.sid: + // end calc settings + case PrintHeadersRecord.sid: + case PrintGridlinesRecord.sid: + case GridsetRecord.sid: + return true; + // DefaultRowHeightRecord.sid is next + } + } + return false; + } + /** + * @return true if the specified record ID terminates a sequence of Row block records + * It is assumed that at least one row or cell value record has been found prior to the current + * record + */ + public static boolean isEndOfRowBlock(int sid) { + switch(sid) { + case ViewDefinitionRecord.sid: + // should have been prefixed with DrawingRecord (0x00EC), but bug 46280 seems to allow this + case DrawingRecord.sid: + case DrawingSelectionRecord.sid: + case ObjRecord.sid: + case TextObjectRecord.sid: case ColumnInfoRecord.sid: // See Bugzilla 53984 case GutsRecord.sid: // see Bugzilla 50426 - case WindowOneRecord.sid: - // should really be part of workbook stream, but some apps seem to put this before WINDOW2 - case WindowTwoRecord.sid: - return true; + case WindowOneRecord.sid: + // should really be part of workbook stream, but some apps seem to put this before WINDOW2 + case WindowTwoRecord.sid: + return true; - case DVALRecord.sid: - return true; - case EOFRecord.sid: - // WINDOW2 should always be present, so shouldn't have got this far - throw new RuntimeException("Found EOFRecord before WindowTwoRecord was encountered"); - } - return PageSettingsBlock.isComponentRecord(sid); - } + case DVALRecord.sid: + return true; + case EOFRecord.sid: + // WINDOW2 should always be present, so shouldn't have got this far + throw new RuntimeException("Found EOFRecord before WindowTwoRecord was encountered"); + } + return PageSettingsBlock.isComponentRecord(sid); + } - /** - * @return true if the specified record id normally appears in the row blocks section - * of the sheet records - */ - public static boolean isRowBlockRecord(int sid) { - switch (sid) { - case RowRecord.sid: + /** + * @return true if the specified record id normally appears in the row blocks section + * of the sheet records + */ + public static boolean isRowBlockRecord(int sid) { + switch (sid) { + case RowRecord.sid: - case BlankRecord.sid: - case BoolErrRecord.sid: - case FormulaRecord.sid: - case LabelRecord.sid: - case LabelSSTRecord.sid: - case NumberRecord.sid: - case RKRecord.sid: + case BlankRecord.sid: + case BoolErrRecord.sid: + case FormulaRecord.sid: + case LabelRecord.sid: + case LabelSSTRecord.sid: + case NumberRecord.sid: + case RKRecord.sid: - case ArrayRecord.sid: - case SharedFormulaRecord.sid: - case TableRecord.sid: - return true; - } - return false; - } + case ArrayRecord.sid: + case SharedFormulaRecord.sid: + case TableRecord.sid: + return true; + } + return false; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/model/RecordStream.java b/poi/src/main/java/org/apache/poi/hssf/model/RecordStream.java index 1c548a02d1..e0a546cbbb 100644 --- a/poi/src/main/java/org/apache/poi/hssf/model/RecordStream.java +++ b/poi/src/main/java/org/apache/poi/hssf/model/RecordStream.java @@ -25,69 +25,69 @@ import org.apache.poi.hssf.record.Record; */ public final class RecordStream { - private final List _list; - private int _nextIndex; - private int _countRead; - private final int _endIx; + private final List _list; + private int _nextIndex; + private int _countRead; + private final int _endIx; - /** - * Creates a RecordStream bounded by startIndex and endIndex - * - * @param inputList the list to iterate over - * @param startIndex the start index within the list - * @param endIx the end index within the list, which is the index of the end element + 1 - */ - public RecordStream(List inputList, int startIndex, int endIx) { - _list = inputList; - _nextIndex = startIndex; - _endIx = endIx; - _countRead = 0; - } + /** + * Creates a RecordStream bounded by startIndex and endIndex + * + * @param inputList the list to iterate over + * @param startIndex the start index within the list + * @param endIx the end index within the list, which is the index of the end element + 1 + */ + public RecordStream(List inputList, int startIndex, int endIx) { + _list = inputList; + _nextIndex = startIndex; + _endIx = endIx; + _countRead = 0; + } - public RecordStream(List records, int startIx) { - this(records, startIx, records.size()); - } + public RecordStream(List records, int startIx) { + this(records, startIx, records.size()); + } - public boolean hasNext() { - return _nextIndex < _endIx; - } + public boolean hasNext() { + return _nextIndex < _endIx; + } - public Record getNext() { - if(!hasNext()) { - throw new RuntimeException("Attempt to read past end of record stream"); - } - _countRead ++; - return _list.get(_nextIndex++); - } + public Record getNext() { + if(!hasNext()) { + throw new RuntimeException("Attempt to read past end of record stream"); + } + _countRead ++; + return _list.get(_nextIndex++); + } - /** - * @return the {@link Class} of the next Record. {@code null} if this stream is exhausted. - */ - public Class peekNextClass() { - if(!hasNext()) { - return null; - } - return _list.get(_nextIndex).getClass(); - } + /** + * @return the {@link Class} of the next Record. {@code null} if this stream is exhausted. + */ + public Class peekNextClass() { + if(!hasNext()) { + return null; + } + return _list.get(_nextIndex).getClass(); + } - /** - * @return the next Record. {@code null} if this stream is exhausted. - */ - public Record peekNextRecord() { - return (hasNext()) ? _list.get(_nextIndex) : null; - } + /** + * @return the next Record. {@code null} if this stream is exhausted. + */ + public Record peekNextRecord() { + return (hasNext()) ? _list.get(_nextIndex) : null; + } - /** - * @return -1 if at end of records - */ - public int peekNextSid() { - if(!hasNext()) { - return -1; - } - return _list.get(_nextIndex).getSid(); - } + /** + * @return -1 if at end of records + */ + public int peekNextSid() { + if(!hasNext()) { + return -1; + } + return _list.get(_nextIndex).getSid(); + } - public int getCountRead() { - return _countRead; - } + public int getCountRead() { + return _countRead; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/model/RowBlocksReader.java b/poi/src/main/java/org/apache/poi/hssf/model/RowBlocksReader.java index b25b8fac2c..946d2c610f 100644 --- a/poi/src/main/java/org/apache/poi/hssf/model/RowBlocksReader.java +++ b/poi/src/main/java/org/apache/poi/hssf/model/RowBlocksReader.java @@ -36,84 +36,84 @@ import org.apache.poi.ss.util.CellReference; */ public final class RowBlocksReader { - private final List _plainRecords; - private final SharedValueManager _sfm; - private final MergeCellsRecord[] _mergedCellsRecords; + private final List _plainRecords; + private final SharedValueManager _sfm; + private final MergeCellsRecord[] _mergedCellsRecords; - /** - * Also collects any loose MergeCellRecords and puts them in the supplied - * mergedCellsTable - * - * @param rs the record stream - */ - public RowBlocksReader(RecordStream rs) { - List plainRecords = new ArrayList<>(); - List shFrmRecords = new ArrayList<>(); - List firstCellRefs = new ArrayList<>(); - List arrayRecords = new ArrayList<>(); - List tableRecords = new ArrayList<>(); - List mergeCellRecords = new ArrayList<>(); + /** + * Also collects any loose MergeCellRecords and puts them in the supplied + * mergedCellsTable + * + * @param rs the record stream + */ + public RowBlocksReader(RecordStream rs) { + List plainRecords = new ArrayList<>(); + List shFrmRecords = new ArrayList<>(); + List firstCellRefs = new ArrayList<>(); + List arrayRecords = new ArrayList<>(); + List tableRecords = new ArrayList<>(); + List mergeCellRecords = new ArrayList<>(); - Record prevRec = null; - while(!RecordOrderer.isEndOfRowBlock(rs.peekNextSid())) { - // End of row/cell records for the current sheet - // Note - It is important that this code does not inadvertently add any sheet - // records from a subsequent sheet. For example, if SharedFormulaRecords - // are taken from the wrong sheet, this could cause bug 44449. - if (!rs.hasNext()) { - throw new RuntimeException("Failed to find end of row/cell records"); + Record prevRec = null; + while(!RecordOrderer.isEndOfRowBlock(rs.peekNextSid())) { + // End of row/cell records for the current sheet + // Note - It is important that this code does not inadvertently add any sheet + // records from a subsequent sheet. For example, if SharedFormulaRecords + // are taken from the wrong sheet, this could cause bug 44449. + if (!rs.hasNext()) { + throw new RuntimeException("Failed to find end of row/cell records"); - } - Record rec = rs.getNext(); - List dest; - switch (rec.getSid()) { - case MergeCellsRecord.sid: dest = mergeCellRecords; break; - case SharedFormulaRecord.sid: dest = shFrmRecords; - if (!(prevRec instanceof FormulaRecord)) { - throw new RuntimeException("Shared formula record should follow a FormulaRecord"); - } - FormulaRecord fr = (FormulaRecord)prevRec; - firstCellRefs.add(new CellReference(fr.getRow(), fr.getColumn())); - break; - case ArrayRecord.sid: dest = arrayRecords; break; - case TableRecord.sid: dest = tableRecords; break; - default: dest = plainRecords; - } - dest.add(rec); - prevRec = rec; - } - SharedFormulaRecord[] sharedFormulaRecs = new SharedFormulaRecord[shFrmRecords.size()]; - CellReference[] firstCells = new CellReference[firstCellRefs.size()]; - ArrayRecord[] arrayRecs = new ArrayRecord[arrayRecords.size()]; - TableRecord[] tableRecs = new TableRecord[tableRecords.size()]; - shFrmRecords.toArray(sharedFormulaRecs); - firstCellRefs.toArray(firstCells); - arrayRecords.toArray(arrayRecs); - tableRecords.toArray(tableRecs); + } + Record rec = rs.getNext(); + List dest; + switch (rec.getSid()) { + case MergeCellsRecord.sid: dest = mergeCellRecords; break; + case SharedFormulaRecord.sid: dest = shFrmRecords; + if (!(prevRec instanceof FormulaRecord)) { + throw new RuntimeException("Shared formula record should follow a FormulaRecord"); + } + FormulaRecord fr = (FormulaRecord)prevRec; + firstCellRefs.add(new CellReference(fr.getRow(), fr.getColumn())); + break; + case ArrayRecord.sid: dest = arrayRecords; break; + case TableRecord.sid: dest = tableRecords; break; + default: dest = plainRecords; + } + dest.add(rec); + prevRec = rec; + } + SharedFormulaRecord[] sharedFormulaRecs = new SharedFormulaRecord[shFrmRecords.size()]; + CellReference[] firstCells = new CellReference[firstCellRefs.size()]; + ArrayRecord[] arrayRecs = new ArrayRecord[arrayRecords.size()]; + TableRecord[] tableRecs = new TableRecord[tableRecords.size()]; + shFrmRecords.toArray(sharedFormulaRecs); + firstCellRefs.toArray(firstCells); + arrayRecords.toArray(arrayRecs); + tableRecords.toArray(tableRecs); - _plainRecords = plainRecords; - _sfm = SharedValueManager.create(sharedFormulaRecs, firstCells, arrayRecs, tableRecs); - _mergedCellsRecords = new MergeCellsRecord[mergeCellRecords.size()]; - mergeCellRecords.toArray(_mergedCellsRecords); - } + _plainRecords = plainRecords; + _sfm = SharedValueManager.create(sharedFormulaRecs, firstCells, arrayRecs, tableRecs); + _mergedCellsRecords = new MergeCellsRecord[mergeCellRecords.size()]; + mergeCellRecords.toArray(_mergedCellsRecords); + } - /** - * Some unconventional apps place {@link MergeCellsRecord}s within the row block. They - * actually should be in the {@link MergedCellsTable} which is much later (see bug 45699). - * @return any loose {@code MergeCellsRecord}s found - */ - public MergeCellsRecord[] getLooseMergedCells() { - return _mergedCellsRecords; - } + /** + * Some unconventional apps place {@link MergeCellsRecord}s within the row block. They + * actually should be in the {@link MergedCellsTable} which is much later (see bug 45699). + * @return any loose {@code MergeCellsRecord}s found + */ + public MergeCellsRecord[] getLooseMergedCells() { + return _mergedCellsRecords; + } - public SharedValueManager getSharedFormulaManager() { - return _sfm; - } - /** - * @return a {@link RecordStream} containing all the non-{@link SharedFormulaRecord} - * non-{@link ArrayRecord} and non-{@link TableRecord} Records. - */ - public RecordStream getPlainRecordStream() { - return new RecordStream(_plainRecords, 0); - } + public SharedValueManager getSharedFormulaManager() { + return _sfm; + } + /** + * @return a {@link RecordStream} containing all the non-{@link SharedFormulaRecord} + * non-{@link ArrayRecord} and non-{@link TableRecord} Records. + */ + public RecordStream getPlainRecordStream() { + return new RecordStream(_plainRecords, 0); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/model/WorkbookRecordList.java b/poi/src/main/java/org/apache/poi/hssf/model/WorkbookRecordList.java index 2f97ed0163..6a760af19a 100644 --- a/poi/src/main/java/org/apache/poi/hssf/model/WorkbookRecordList.java +++ b/poi/src/main/java/org/apache/poi/hssf/model/WorkbookRecordList.java @@ -26,174 +26,174 @@ public final class WorkbookRecordList { private List records = new ArrayList<>(); /** holds the position of the protect record */ - private int protpos; + private int protpos; /** holds the position of the last bound sheet */ - private int bspos; + private int bspos; /** holds the position of the tabid record */ - private int tabpos = -1; + private int tabpos = -1; /** hold the position of the last font record */ - private int fontpos; + private int fontpos; /** hold the position of the last extended font record */ - private int xfpos; + private int xfpos; /** holds the position of the backup record */ - private int backuppos; + private int backuppos; /** holds the position of last name record */ - private int namepos; - /** holds the position of sup book */ - private int supbookpos; - /** holds the position of the extern sheet */ - private int externsheetPos; - /** hold the position of the palette, if applicable */ - private int palettepos = -1; + private int namepos; + /** holds the position of sup book */ + private int supbookpos; + /** holds the position of the extern sheet */ + private int externsheetPos; + /** hold the position of the palette, if applicable */ + private int palettepos = -1; - public void setRecords(List records) { - this.records = records; - } + public void setRecords(List records) { + this.records = records; + } - public int size() { - return records.size(); - } + public int size() { + return records.size(); + } - public Record get(int i) { - return records.get(i); - } + public Record get(int i) { + return records.get(i); + } - public void add(int pos, Record r) { - records.add(pos, r); - updateRecordPos(pos, true); - } + public void add(int pos, Record r) { + records.add(pos, r); + updateRecordPos(pos, true); + } - public List getRecords() { - return records; - } + public List getRecords() { + return records; + } - /** - * Find the given record in the record list by identity and removes it - * - * @param record the identical record to be searched for - */ - public void remove( Object record ) { - // can't use List.indexOf here because it checks the records for equality and not identity - int i = 0; - for (org.apache.poi.hssf.record.Record r : records) { - if (r == record) { - remove(i); - break; - } - i++; - } - } + /** + * Find the given record in the record list by identity and removes it + * + * @param record the identical record to be searched for + */ + public void remove( Object record ) { + // can't use List.indexOf here because it checks the records for equality and not identity + int i = 0; + for (org.apache.poi.hssf.record.Record r : records) { + if (r == record) { + remove(i); + break; + } + i++; + } + } - public void remove( int pos ) { - records.remove(pos); - updateRecordPos(pos, false); - } + public void remove( int pos ) { + records.remove(pos); + updateRecordPos(pos, false); + } - public int getProtpos() { - return protpos; - } + public int getProtpos() { + return protpos; + } - public void setProtpos(int protpos) { - this.protpos = protpos; - } + public void setProtpos(int protpos) { + this.protpos = protpos; + } - public int getBspos() { - return bspos; - } + public int getBspos() { + return bspos; + } - public void setBspos(int bspos) { - this.bspos = bspos; - } + public void setBspos(int bspos) { + this.bspos = bspos; + } - public int getTabpos() { - return tabpos; - } + public int getTabpos() { + return tabpos; + } - public void setTabpos(int tabpos) { - this.tabpos = tabpos; - } + public void setTabpos(int tabpos) { + this.tabpos = tabpos; + } - public int getFontpos() { - return fontpos; - } + public int getFontpos() { + return fontpos; + } - public void setFontpos(int fontpos) { - this.fontpos = fontpos; - } + public void setFontpos(int fontpos) { + this.fontpos = fontpos; + } - public int getXfpos() { - return xfpos; - } + public int getXfpos() { + return xfpos; + } - public void setXfpos(int xfpos) { - this.xfpos = xfpos; - } + public void setXfpos(int xfpos) { + this.xfpos = xfpos; + } - public int getBackuppos() { - return backuppos; - } + public int getBackuppos() { + return backuppos; + } - public void setBackuppos(int backuppos) { - this.backuppos = backuppos; - } + public void setBackuppos(int backuppos) { + this.backuppos = backuppos; + } - public int getPalettepos() { - return palettepos; - } + public int getPalettepos() { + return palettepos; + } - public void setPalettepos(int palettepos) { - this.palettepos = palettepos; - } + public void setPalettepos(int palettepos) { + this.palettepos = palettepos; + } - /** - * Returns the namepos. - * @return int - */ - public int getNamepos() { - return namepos; - } + /** + * Returns the namepos. + * @return int + */ + public int getNamepos() { + return namepos; + } - /** - * Returns the supbookpos. - * @return int - */ - public int getSupbookpos() { - return supbookpos; - } + /** + * Returns the supbookpos. + * @return int + */ + public int getSupbookpos() { + return supbookpos; + } - /** - * Sets the namepos. - * @param namepos The namepos to set - */ - public void setNamepos(int namepos) { - this.namepos = namepos; - } + /** + * Sets the namepos. + * @param namepos The namepos to set + */ + public void setNamepos(int namepos) { + this.namepos = namepos; + } - /** - * Sets the supbookpos. - * @param supbookpos The supbookpos to set - */ - public void setSupbookpos(int supbookpos) { - this.supbookpos = supbookpos; - } + /** + * Sets the supbookpos. + * @param supbookpos The supbookpos to set + */ + public void setSupbookpos(int supbookpos) { + this.supbookpos = supbookpos; + } - /** - * Returns the externsheetPos. - * @return int - */ - public int getExternsheetPos() { - return externsheetPos; - } + /** + * Returns the externsheetPos. + * @return int + */ + public int getExternsheetPos() { + return externsheetPos; + } - /** - * Sets the externsheetPos. - * @param externsheetPos The externsheetPos to set - */ - public void setExternsheetPos(int externsheetPos) { - this.externsheetPos = externsheetPos; - } + /** + * Sets the externsheetPos. + * @param externsheetPos The externsheetPos to set + */ + public void setExternsheetPos(int externsheetPos) { + this.externsheetPos = externsheetPos; + } private void updateRecordPos(int pos, boolean add) { int delta = (add) ? 1 : -1; diff --git a/poi/src/main/java/org/apache/poi/hssf/record/AbstractEscherHolderRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/AbstractEscherHolderRecord.java index 0132e276e3..5d022a2605 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/AbstractEscherHolderRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/AbstractEscherHolderRecord.java @@ -164,12 +164,12 @@ public abstract class AbstractEscherHolderRecord extends Record { * @return the EscherContainerRecord or {@code null} if no child is a container record */ public EscherContainerRecord getEscherContainer() { - for (EscherRecord er : escherRecords) { - if(er instanceof EscherContainerRecord) { - return (EscherContainerRecord)er; - } - } - return null; + for (EscherRecord er : escherRecords) { + if(er instanceof EscherContainerRecord) { + return (EscherContainerRecord)er; + } + } + return null; } /** @@ -182,29 +182,29 @@ public abstract class AbstractEscherHolderRecord extends Record { * @return the record or {@code null} if it can't be found */ public EscherRecord findFirstWithId(short id) { - return findFirstWithId(id, getEscherRecords()); + return findFirstWithId(id, getEscherRecords()); } private EscherRecord findFirstWithId(short id, List records) { - // Check at our level - for (EscherRecord r : records) { - if(r.getRecordId() == id) { - return r; - } - } + // Check at our level + for (EscherRecord r : records) { + if(r.getRecordId() == id) { + return r; + } + } - // Then check our children in turn - for (EscherRecord r : records) { - if(r.isContainerRecord()) { - EscherRecord found = findFirstWithId(id, r.getChildRecords()); - if(found != null) { - return found; - } - } - } + // Then check our children in turn + for (EscherRecord r : records) { + if(r.isContainerRecord()) { + EscherRecord found = findFirstWithId(id, r.getChildRecords()); + if(found != null) { + return found; + } + } + } - // Not found in this lot - return null; + // Not found in this lot + return null; } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/ArrayRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/ArrayRecord.java index b3e2d7f234..b03a4cd846 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/ArrayRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/ArrayRecord.java @@ -33,78 +33,78 @@ import org.apache.poi.util.LittleEndianOutput; */ public final class ArrayRecord extends SharedValueRecordBase { - public static final short sid = 0x0221; - private static final int OPT_ALWAYS_RECALCULATE = 0x0001; - private static final int OPT_CALCULATE_ON_OPEN = 0x0002; + public static final short sid = 0x0221; + private static final int OPT_ALWAYS_RECALCULATE = 0x0001; + private static final int OPT_CALCULATE_ON_OPEN = 0x0002; - private int _options; - private int _field3notUsed; - private Formula _formula; + private int _options; + private int _field3notUsed; + private Formula _formula; - public ArrayRecord(ArrayRecord other) { - super(other); - _options = other._options; - _field3notUsed = other._field3notUsed; - _formula = (other._formula == null) ? null : other._formula.copy(); - } + public ArrayRecord(ArrayRecord other) { + super(other); + _options = other._options; + _field3notUsed = other._field3notUsed; + _formula = (other._formula == null) ? null : other._formula.copy(); + } - public ArrayRecord(RecordInputStream in) { - super(in); - _options = in.readUShort(); - _field3notUsed = in.readInt(); - int formulaTokenLen = in.readUShort(); - int totalFormulaLen = in.available(); - _formula = Formula.read(formulaTokenLen, in, totalFormulaLen); - } + public ArrayRecord(RecordInputStream in) { + super(in); + _options = in.readUShort(); + _field3notUsed = in.readInt(); + int formulaTokenLen = in.readUShort(); + int totalFormulaLen = in.available(); + _formula = Formula.read(formulaTokenLen, in, totalFormulaLen); + } - public ArrayRecord(Formula formula, CellRangeAddress8Bit range) { - super(range); - _options = 0; //YK: Excel 2007 leaves this field unset - _field3notUsed = 0; - _formula = formula; - } + public ArrayRecord(Formula formula, CellRangeAddress8Bit range) { + super(range); + _options = 0; //YK: Excel 2007 leaves this field unset + _field3notUsed = 0; + _formula = formula; + } - public boolean isAlwaysRecalculate() { - return (_options & OPT_ALWAYS_RECALCULATE) != 0; - } - public boolean isCalculateOnOpen() { - return (_options & OPT_CALCULATE_ON_OPEN) != 0; - } + public boolean isAlwaysRecalculate() { + return (_options & OPT_ALWAYS_RECALCULATE) != 0; + } + public boolean isCalculateOnOpen() { + return (_options & OPT_CALCULATE_ON_OPEN) != 0; + } - public Ptg[] getFormulaTokens() { - return _formula.getTokens(); - } + public Ptg[] getFormulaTokens() { + return _formula.getTokens(); + } - protected int getExtraDataSize() { - return 2 + 4 + _formula.getEncodedSize(); - } - protected void serializeExtraData(LittleEndianOutput out) { - out.writeShort(_options); - out.writeInt(_field3notUsed); - _formula.serialize(out); - } + protected int getExtraDataSize() { + return 2 + 4 + _formula.getEncodedSize(); + } + protected void serializeExtraData(LittleEndianOutput out) { + out.writeShort(_options); + out.writeInt(_field3notUsed); + _formula.serialize(out); + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - @Override + @Override public ArrayRecord copy() { return new ArrayRecord(this); } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.ARRAY; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.ARRAY; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "range", this::getRange, - "options", () -> _options, - "notUsed", () -> _field3notUsed, - "formula", () -> _formula - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "range", this::getRange, + "options", () -> _options, + "notUsed", () -> _field3notUsed, + "formula", () -> _formula + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/BiffHeaderInput.java b/poi/src/main/java/org/apache/poi/hssf/record/BiffHeaderInput.java index 089dce6755..b9048d72b3 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/BiffHeaderInput.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/BiffHeaderInput.java @@ -18,23 +18,23 @@ package org.apache.poi.hssf.record; public interface BiffHeaderInput { - /** - * Read an unsigned short from the stream without decrypting - * - * @return the record sid - */ - int readRecordSID(); - - /** - * Read an unsigned short from the stream without decrypting - * - * @return the data size - */ - int readDataSize(); + /** + * Read an unsigned short from the stream without decrypting + * + * @return the record sid + */ + int readRecordSID(); + + /** + * Read an unsigned short from the stream without decrypting + * + * @return the data size + */ + int readDataSize(); - /** - * @return the available bytes - */ - int available(); + /** + * @return the available bytes + */ + int available(); } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/BoolErrRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/BoolErrRecord.java index 94266db621..0aadd91fdd 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/BoolErrRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/BoolErrRecord.java @@ -29,173 +29,173 @@ import org.apache.poi.util.RecordFormatException; * Creates new BoolErrRecord. (0x0205) */ public final class BoolErrRecord extends CellRecord { - public static final short sid = 0x0205; - private int _value; - /** - * If true, this record represents an error cell value, - * otherwise this record represents a boolean cell value - */ - private boolean _isError; + public static final short sid = 0x0205; + private int _value; + /** + * If true, this record represents an error cell value, + * otherwise this record represents a boolean cell value + */ + private boolean _isError; - /** Creates new BoolErrRecord */ - public BoolErrRecord() {} + /** Creates new BoolErrRecord */ + public BoolErrRecord() {} - public BoolErrRecord(BoolErrRecord other) { - super(other); - _value = other._value; - _isError = other._isError; - } + public BoolErrRecord(BoolErrRecord other) { + super(other); + _value = other._value; + _isError = other._isError; + } - /** - * @param in the RecordInputstream to read the record from - */ - public BoolErrRecord(RecordInputStream in) { - super(in); - switch (in.remaining()) { - case 2: - _value = in.readByte(); - break; - case 3: - _value = in.readUShort(); - break; - default: - throw new RecordFormatException("Unexpected size (" - + in.remaining() + ") for BOOLERR record."); - } - int flag = in.readUByte(); - switch (flag) { - case 0: - _isError = false; - break; - case 1: - _isError = true; - break; - default: - throw new RecordFormatException("Unexpected isError flag (" - + flag + ") for BOOLERR record."); - } - } + /** + * @param in the RecordInputstream to read the record from + */ + public BoolErrRecord(RecordInputStream in) { + super(in); + switch (in.remaining()) { + case 2: + _value = in.readByte(); + break; + case 3: + _value = in.readUShort(); + break; + default: + throw new RecordFormatException("Unexpected size (" + + in.remaining() + ") for BOOLERR record."); + } + int flag = in.readUByte(); + switch (flag) { + case 0: + _isError = false; + break; + case 1: + _isError = true; + break; + default: + throw new RecordFormatException("Unexpected isError flag (" + + flag + ") for BOOLERR record."); + } + } - /** - * set the boolean value for the cell - * - * @param value representing the boolean value - */ - public void setValue(boolean value) { - _value = value ? 1 : 0; - _isError = false; - } + /** + * set the boolean value for the cell + * + * @param value representing the boolean value + */ + public void setValue(boolean value) { + _value = value ? 1 : 0; + _isError = false; + } - /** - * set the error value for the cell. See {@link FormulaError} for valid codes. - * - * @param value error representing the error value - * this value can only be 0,7,15,23,29,36 or 42 - * see bugzilla bug 16560 for an explanation - */ - public void setValue(byte value) { - setValue(FormulaError.forInt(value)); - } + /** + * set the error value for the cell. See {@link FormulaError} for valid codes. + * + * @param value error representing the error value + * this value can only be 0,7,15,23,29,36 or 42 + * see bugzilla bug 16560 for an explanation + */ + public void setValue(byte value) { + setValue(FormulaError.forInt(value)); + } - /** - * set the error value for the cell - * - * @param value error representing the error value - * this value can only be 0,7,15,23,29,36 or 42 - * see bugzilla bug 16560 for an explanation - */ - public void setValue(FormulaError value) { - switch(value) { - case NULL: - case DIV0: - case VALUE: - case REF: - case NAME: - case NUM: - case NA: - _value = value.getCode(); - _isError = true; - return; - default: - throw new IllegalArgumentException("Error Value can only be 0,7,15,23,29,36 or 42. It cannot be "+value.getCode()+" ("+value+")"); - } - } + /** + * set the error value for the cell + * + * @param value error representing the error value + * this value can only be 0,7,15,23,29,36 or 42 + * see bugzilla bug 16560 for an explanation + */ + public void setValue(FormulaError value) { + switch(value) { + case NULL: + case DIV0: + case VALUE: + case REF: + case NAME: + case NUM: + case NA: + _value = value.getCode(); + _isError = true; + return; + default: + throw new IllegalArgumentException("Error Value can only be 0,7,15,23,29,36 or 42. It cannot be "+value.getCode()+" ("+value+")"); + } + } - /** - * get the value for the cell - * - * @return boolean representing the boolean value - */ - public boolean getBooleanValue() { - return _value != 0; - } + /** + * get the value for the cell + * + * @return boolean representing the boolean value + */ + public boolean getBooleanValue() { + return _value != 0; + } - /** - * get the error value for the cell - * - * @return byte representing the error value - */ - public byte getErrorValue() { - return (byte)_value; - } + /** + * get the error value for the cell + * + * @return byte representing the error value + */ + public byte getErrorValue() { + return (byte)_value; + } - /** - * Indicates whether the call holds a boolean value - * - * @return boolean true if the cell holds a boolean value - */ - public boolean isBoolean() { - return !_isError; - } + /** + * Indicates whether the call holds a boolean value + * + * @return boolean true if the cell holds a boolean value + */ + public boolean isBoolean() { + return !_isError; + } - /** - * Indicates whether the call holds an error value - * - * @return boolean true if the cell holds an error value - */ - public boolean isError() { - return _isError; - } + /** + * Indicates whether the call holds an error value + * + * @return boolean true if the cell holds an error value + */ + public boolean isError() { + return _isError; + } - @Override - protected String getRecordName() { - return "BOOLERR"; - } + @Override + protected String getRecordName() { + return "BOOLERR"; + } - @Override - protected void serializeValue(LittleEndianOutput out) { - out.writeByte(_value); - out.writeByte(_isError ? 1 : 0); - } + @Override + protected void serializeValue(LittleEndianOutput out) { + out.writeByte(_value); + out.writeByte(_isError ? 1 : 0); + } - @Override - protected int getValueDataSize() { - return 2; - } + @Override + protected int getValueDataSize() { + return 2; + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - @Override - public BoolErrRecord copy() { - return new BoolErrRecord(this); - } + @Override + public BoolErrRecord copy() { + return new BoolErrRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.BOOL_ERR; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.BOOL_ERR; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "base", super::getGenericProperties, - "isBoolean", this::isBoolean, - "booleanVal", this::getBooleanValue, - "isError", this::isError, - "errorVal", this::getErrorValue, - "errorTxt", () -> isError() ? FormulaError.forInt(getErrorValue()).getString() : null - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "base", super::getGenericProperties, + "isBoolean", this::isBoolean, + "booleanVal", this::getBooleanValue, + "isError", this::isError, + "errorVal", this::getErrorValue, + "errorTxt", () -> isError() ? FormulaError.forInt(getErrorValue()).getString() : null + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/BoundSheetRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/BoundSheetRecord.java index 0640640f7e..32e48dd5d4 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/BoundSheetRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/BoundSheetRecord.java @@ -36,194 +36,194 @@ import org.apache.poi.util.StringUtil; * tells where the Beginning of file record is within the HSSF file. */ public final class BoundSheetRecord extends StandardRecord { - public static final short sid = 0x0085; - private static final BitField hiddenFlag = BitFieldFactory.getInstance(0x01); - private static final BitField veryHiddenFlag = BitFieldFactory.getInstance(0x02); + public static final short sid = 0x0085; + private static final BitField hiddenFlag = BitFieldFactory.getInstance(0x01); + private static final BitField veryHiddenFlag = BitFieldFactory.getInstance(0x02); - private int field_1_position_of_BOF; - private int field_2_option_flags; - private int field_4_isMultibyteUnicode; - private String field_5_sheetname; + private int field_1_position_of_BOF; + private int field_2_option_flags; + private int field_4_isMultibyteUnicode; + private String field_5_sheetname; - public BoundSheetRecord(String sheetname) { - field_2_option_flags = 0; - setSheetname(sheetname); - } + public BoundSheetRecord(String sheetname) { + field_2_option_flags = 0; + setSheetname(sheetname); + } - public BoundSheetRecord(BoundSheetRecord other) { - super(other); - field_1_position_of_BOF = other.field_1_position_of_BOF; - field_2_option_flags = other.field_2_option_flags; - field_4_isMultibyteUnicode = other.field_4_isMultibyteUnicode; - field_5_sheetname = other.field_5_sheetname; - } + public BoundSheetRecord(BoundSheetRecord other) { + super(other); + field_1_position_of_BOF = other.field_1_position_of_BOF; + field_2_option_flags = other.field_2_option_flags; + field_4_isMultibyteUnicode = other.field_4_isMultibyteUnicode; + field_5_sheetname = other.field_5_sheetname; + } - /** - * UTF8: sid + len + bof + flags + len(str) + unicode + str 2 + 2 + 4 + 2 + - * 1 + 1 + len(str) - * - * UNICODE: sid + len + bof + flags + len(str) + unicode + str 2 + 2 + 4 + 2 + - * 1 + 1 + 2 * len(str) - * - * @param in the record stream to read from - */ - public BoundSheetRecord(RecordInputStream in) { + /** + * UTF8: sid + len + bof + flags + len(str) + unicode + str 2 + 2 + 4 + 2 + + * 1 + 1 + len(str) + * + * UNICODE: sid + len + bof + flags + len(str) + unicode + str 2 + 2 + 4 + 2 + + * 1 + 1 + 2 * len(str) + * + * @param in the record stream to read from + */ + public BoundSheetRecord(RecordInputStream in) { byte[] buf = new byte[LittleEndianConsts.INT_SIZE]; - in.readPlain(buf, 0, buf.length); - field_1_position_of_BOF = LittleEndian.getInt(buf); - field_2_option_flags = in.readUShort(); - int field_3_sheetname_length = in.readUByte(); - field_4_isMultibyteUnicode = in.readByte(); + in.readPlain(buf, 0, buf.length); + field_1_position_of_BOF = LittleEndian.getInt(buf); + field_2_option_flags = in.readUShort(); + int field_3_sheetname_length = in.readUByte(); + field_4_isMultibyteUnicode = in.readByte(); - if (isMultibyte()) { - field_5_sheetname = in.readUnicodeLEString(field_3_sheetname_length); - } else { - field_5_sheetname = in.readCompressedUnicode(field_3_sheetname_length); - } - } + if (isMultibyte()) { + field_5_sheetname = in.readUnicodeLEString(field_3_sheetname_length); + } else { + field_5_sheetname = in.readCompressedUnicode(field_3_sheetname_length); + } + } - /** - * set the offset in bytes of the Beginning of File Marker within the HSSF - * Stream part of the POIFS file - * - * @param pos offset in bytes - */ - public void setPositionOfBof(int pos) { - field_1_position_of_BOF = pos; - } + /** + * set the offset in bytes of the Beginning of File Marker within the HSSF + * Stream part of the POIFS file + * + * @param pos offset in bytes + */ + public void setPositionOfBof(int pos) { + field_1_position_of_BOF = pos; + } - /** - * Set the sheetname for this sheet. (this appears in the tabs at the bottom) - * @param sheetName the name of the sheet - * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal) - * for a safe way to create valid names - * @throws IllegalArgumentException if sheet name will cause excel to crash. - */ - public void setSheetname(String sheetName) { + /** + * Set the sheetname for this sheet. (this appears in the tabs at the bottom) + * @param sheetName the name of the sheet + * @see org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String nameProposal) + * for a safe way to create valid names + * @throws IllegalArgumentException if sheet name will cause excel to crash. + */ + public void setSheetname(String sheetName) { - WorkbookUtil.validateSheetName(sheetName); - field_5_sheetname = sheetName; - field_4_isMultibyteUnicode = StringUtil.hasMultibyte(sheetName) ? 1 : 0; - } + WorkbookUtil.validateSheetName(sheetName); + field_5_sheetname = sheetName; + field_4_isMultibyteUnicode = StringUtil.hasMultibyte(sheetName) ? 1 : 0; + } - /** - * get the offset in bytes of the Beginning of File Marker within the HSSF Stream part of the POIFS file - * - * @return offset in bytes - */ - public int getPositionOfBof() { - return field_1_position_of_BOF; - } + /** + * get the offset in bytes of the Beginning of File Marker within the HSSF Stream part of the POIFS file + * + * @return offset in bytes + */ + public int getPositionOfBof() { + return field_1_position_of_BOF; + } - private boolean isMultibyte() { - return (field_4_isMultibyteUnicode & 0x01) != 0; - } + private boolean isMultibyte() { + return (field_4_isMultibyteUnicode & 0x01) != 0; + } - /** - * get the sheetname for this sheet. (this appears in the tabs at the bottom) - * @return sheetname the name of the sheet - */ - public String getSheetname() { - return field_5_sheetname; - } + /** + * get the sheetname for this sheet. (this appears in the tabs at the bottom) + * @return sheetname the name of the sheet + */ + public String getSheetname() { + return field_5_sheetname; + } - protected int getDataSize() { - return 8 + field_5_sheetname.length() * (isMultibyte() ? 2 : 1); - } + protected int getDataSize() { + return 8 + field_5_sheetname.length() * (isMultibyte() ? 2 : 1); + } - public void serialize(LittleEndianOutput out) { - out.writeInt(getPositionOfBof()); - out.writeShort(field_2_option_flags); + public void serialize(LittleEndianOutput out) { + out.writeInt(getPositionOfBof()); + out.writeShort(field_2_option_flags); - String name = field_5_sheetname; - out.writeByte(name.length()); - out.writeByte(field_4_isMultibyteUnicode); + String name = field_5_sheetname; + out.writeByte(name.length()); + out.writeByte(field_4_isMultibyteUnicode); - if (isMultibyte()) { - StringUtil.putUnicodeLE(name, out); - } else { - StringUtil.putCompressedUnicode(name, out); - } - } + if (isMultibyte()) { + StringUtil.putUnicodeLE(name, out); + } else { + StringUtil.putCompressedUnicode(name, out); + } + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - /** - * Is the sheet hidden? Different from very hidden - * - * @return {@code true} if hidden - */ - public boolean isHidden() { - return hiddenFlag.isSet(field_2_option_flags); - } + /** + * Is the sheet hidden? Different from very hidden + * + * @return {@code true} if hidden + */ + public boolean isHidden() { + return hiddenFlag.isSet(field_2_option_flags); + } - /** - * Is the sheet hidden? Different from very hidden - * - * @param hidden {@code true} if hidden - */ - public void setHidden(boolean hidden) { - field_2_option_flags = hiddenFlag.setBoolean(field_2_option_flags, hidden); - } + /** + * Is the sheet hidden? Different from very hidden + * + * @param hidden {@code true} if hidden + */ + public void setHidden(boolean hidden) { + field_2_option_flags = hiddenFlag.setBoolean(field_2_option_flags, hidden); + } - /** - * Is the sheet very hidden? Different from (normal) hidden - * - * @return {@code true} if very hidden - */ - public boolean isVeryHidden() { - return veryHiddenFlag.isSet(field_2_option_flags); - } + /** + * Is the sheet very hidden? Different from (normal) hidden + * + * @return {@code true} if very hidden + */ + public boolean isVeryHidden() { + return veryHiddenFlag.isSet(field_2_option_flags); + } - /** - * Is the sheet very hidden? Different from (normal) hidden - * - * @param veryHidden {@code true} if very hidden - */ - public void setVeryHidden(boolean veryHidden) { - field_2_option_flags = veryHiddenFlag.setBoolean(field_2_option_flags, veryHidden); - } + /** + * Is the sheet very hidden? Different from (normal) hidden + * + * @param veryHidden {@code true} if very hidden + */ + public void setVeryHidden(boolean veryHidden) { + field_2_option_flags = veryHiddenFlag.setBoolean(field_2_option_flags, veryHidden); + } - /** - * Converts a List of {@link BoundSheetRecord}s to an array and sorts by the position of their - * BOFs. - * - * @param boundSheetRecords the boundSheetRecord list to arrayify - * - * @return the sorted boundSheetRecords - */ - public static BoundSheetRecord[] orderByBofPosition(List boundSheetRecords) { - BoundSheetRecord[] bsrs = new BoundSheetRecord[boundSheetRecords.size()]; - boundSheetRecords.toArray(bsrs); - Arrays.sort(bsrs, BoundSheetRecord::compareRecords); - return bsrs; - } + /** + * Converts a List of {@link BoundSheetRecord}s to an array and sorts by the position of their + * BOFs. + * + * @param boundSheetRecords the boundSheetRecord list to arrayify + * + * @return the sorted boundSheetRecords + */ + public static BoundSheetRecord[] orderByBofPosition(List boundSheetRecords) { + BoundSheetRecord[] bsrs = new BoundSheetRecord[boundSheetRecords.size()]; + boundSheetRecords.toArray(bsrs); + Arrays.sort(bsrs, BoundSheetRecord::compareRecords); + return bsrs; + } - private static int compareRecords(BoundSheetRecord bsr1, BoundSheetRecord bsr2) { - return bsr1.getPositionOfBof() - bsr2.getPositionOfBof(); - } + private static int compareRecords(BoundSheetRecord bsr1, BoundSheetRecord bsr2) { + return bsr1.getPositionOfBof() - bsr2.getPositionOfBof(); + } - @Override - public BoundSheetRecord copy() { - return new BoundSheetRecord(this); - } + @Override + public BoundSheetRecord copy() { + return new BoundSheetRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.BOUND_SHEET; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.BOUND_SHEET; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "bof", this::getPositionOfBof, - "optionFlags", () -> field_2_option_flags, - "multiByte", this::isMultibyte, - "sheetName", this::getSheetname, - "hidden", this::isHidden, - "veryHidden", this::isVeryHidden - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "bof", this::getPositionOfBof, + "optionFlags", () -> field_2_option_flags, + "multiByte", this::isMultibyte, + "sheetName", this::getSheetname, + "hidden", this::isHidden, + "veryHidden", this::isVeryHidden + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/CFRule12Record.java b/poi/src/main/java/org/apache/poi/hssf/record/CFRule12Record.java index e1a3fc5883..fad2fb11a1 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/CFRule12Record.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/CFRule12Record.java @@ -352,7 +352,7 @@ public final class CFRule12Record extends CFRuleBase implements FutureRecord { * * @return list of tokens (casts stack to a list and returns it!) * this method can return null is we are unable to create Ptgs from - * existing excel file + * existing excel file * callers should check for null! */ public Ptg[] getParsedExpressionScale() { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/CFRuleBase.java b/poi/src/main/java/org/apache/poi/hssf/record/CFRuleBase.java index 34a7340aaa..54cfc4de51 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/CFRuleBase.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/CFRuleBase.java @@ -401,7 +401,7 @@ public abstract class CFRuleBase extends StandardRecord { * * @return list of tokens (casts stack to a list and returns it!) * this method can return null is we are unable to create Ptgs from - * existing excel file + * existing excel file * callers should check for null! */ public Ptg[] getParsedExpression1() { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/CRNCountRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/CRNCountRecord.java index eb7d3f607d..6e162423e6 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/CRNCountRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/CRNCountRecord.java @@ -26,63 +26,63 @@ import org.apache.poi.util.LittleEndianOutput; * XCT - CRN Count */ public final class CRNCountRecord extends StandardRecord { - public static final short sid = 0x59; + public static final short sid = 0x59; - private static final short DATA_SIZE = 4; + private static final short DATA_SIZE = 4; - private int field_1_number_crn_records; - private int field_2_sheet_table_index; + private int field_1_number_crn_records; + private int field_2_sheet_table_index; - public CRNCountRecord(CRNCountRecord other) { - super(other); - field_1_number_crn_records = other.field_1_number_crn_records; - field_2_sheet_table_index = other.field_2_sheet_table_index; - } + public CRNCountRecord(CRNCountRecord other) { + super(other); + field_1_number_crn_records = other.field_1_number_crn_records; + field_2_sheet_table_index = other.field_2_sheet_table_index; + } - public CRNCountRecord(RecordInputStream in) { - field_1_number_crn_records = in.readShort(); - if(field_1_number_crn_records < 0) { - // TODO - seems like the sign bit of this field might be used for some other purpose - // see example file for test case "TestBugs.test19599()" - field_1_number_crn_records = (short)-field_1_number_crn_records; - } - field_2_sheet_table_index = in.readShort(); - } + public CRNCountRecord(RecordInputStream in) { + field_1_number_crn_records = in.readShort(); + if(field_1_number_crn_records < 0) { + // TODO - seems like the sign bit of this field might be used for some other purpose + // see example file for test case "TestBugs.test19599()" + field_1_number_crn_records = (short)-field_1_number_crn_records; + } + field_2_sheet_table_index = in.readShort(); + } - public int getNumberOfCRNs() { - return field_1_number_crn_records; - } + public int getNumberOfCRNs() { + return field_1_number_crn_records; + } - public void serialize(LittleEndianOutput out) { - out.writeShort((short)field_1_number_crn_records); - out.writeShort((short)field_2_sheet_table_index); - } - protected int getDataSize() { - return DATA_SIZE; - } + public void serialize(LittleEndianOutput out) { + out.writeShort((short)field_1_number_crn_records); + out.writeShort((short)field_2_sheet_table_index); + } + protected int getDataSize() { + return DATA_SIZE; + } - /** - * return the non static version of the id for this record. - */ - public short getSid() { - return sid; - } + /** + * return the non static version of the id for this record. + */ + public short getSid() { + return sid; + } - @Override - public CRNCountRecord copy() { - return new CRNCountRecord(this); - } + @Override + public CRNCountRecord copy() { + return new CRNCountRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.CRN_COUNT; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.CRN_COUNT; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "numberOfCRNs", this::getNumberOfCRNs, - "sheetTableIndex", () -> field_2_sheet_table_index - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "numberOfCRNs", this::getNumberOfCRNs, + "sheetTableIndex", () -> field_2_sheet_table_index + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/CRNRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/CRNRecord.java index dc52d0b19a..603c4f931a 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/CRNRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/CRNRecord.java @@ -28,70 +28,70 @@ import org.apache.poi.util.LittleEndianOutput; * This record stores the contents of an external cell or cell range */ public final class CRNRecord extends StandardRecord { - public static final short sid = 0x005A; + public static final short sid = 0x005A; - private int field_1_last_column_index; - private int field_2_first_column_index; - private int field_3_row_index; - private Object[] field_4_constant_values; + private int field_1_last_column_index; + private int field_2_first_column_index; + private int field_3_row_index; + private Object[] field_4_constant_values; - public CRNRecord(CRNRecord other) { - super(other); - field_1_last_column_index = other.field_1_last_column_index; - field_2_first_column_index = other.field_2_first_column_index; - field_3_row_index = other.field_3_row_index; - // field_4_constant_values are instances of Double, Boolean, String, ErrorCode, - // i.e. they are immutable and can their references can be simply cloned - field_4_constant_values = (other.field_4_constant_values == null) ? null : other.field_4_constant_values.clone(); - } + public CRNRecord(CRNRecord other) { + super(other); + field_1_last_column_index = other.field_1_last_column_index; + field_2_first_column_index = other.field_2_first_column_index; + field_3_row_index = other.field_3_row_index; + // field_4_constant_values are instances of Double, Boolean, String, ErrorCode, + // i.e. they are immutable and can their references can be simply cloned + field_4_constant_values = (other.field_4_constant_values == null) ? null : other.field_4_constant_values.clone(); + } - public CRNRecord(RecordInputStream in) { - field_1_last_column_index = in.readUByte(); - field_2_first_column_index = in.readUByte(); - field_3_row_index = in.readShort(); - int nValues = field_1_last_column_index - field_2_first_column_index + 1; - field_4_constant_values = ConstantValueParser.parse(in, nValues); - } + public CRNRecord(RecordInputStream in) { + field_1_last_column_index = in.readUByte(); + field_2_first_column_index = in.readUByte(); + field_3_row_index = in.readShort(); + int nValues = field_1_last_column_index - field_2_first_column_index + 1; + field_4_constant_values = ConstantValueParser.parse(in, nValues); + } - public int getNumberOfCRNs() { - return field_1_last_column_index; - } + public int getNumberOfCRNs() { + return field_1_last_column_index; + } - protected int getDataSize() { - return 4 + ConstantValueParser.getEncodedSize(field_4_constant_values); - } + protected int getDataSize() { + return 4 + ConstantValueParser.getEncodedSize(field_4_constant_values); + } - public void serialize(LittleEndianOutput out) { - out.writeByte(field_1_last_column_index); - out.writeByte(field_2_first_column_index); - out.writeShort(field_3_row_index); - ConstantValueParser.encode(out, field_4_constant_values); - } + public void serialize(LittleEndianOutput out) { + out.writeByte(field_1_last_column_index); + out.writeByte(field_2_first_column_index); + out.writeShort(field_3_row_index); + ConstantValueParser.encode(out, field_4_constant_values); + } - /** - * return the non static version of the id for this record. - */ - public short getSid() { - return sid; - } + /** + * return the non static version of the id for this record. + */ + public short getSid() { + return sid; + } - @Override - public CRNRecord copy() { - return new CRNRecord(this); - } + @Override + public CRNRecord copy() { + return new CRNRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.CRN; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.CRN; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "row", () -> field_3_row_index, - "firstColumn", () -> field_2_first_column_index, - "lastColumn", () -> field_1_last_column_index, - "constantValues", () -> field_4_constant_values - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "row", () -> field_3_row_index, + "firstColumn", () -> field_2_first_column_index, + "lastColumn", () -> field_1_last_column_index, + "constantValues", () -> field_4_constant_values + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/CommonObjectDataSubRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/CommonObjectDataSubRecord.java index 14d7c2f1f5..548356930d 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/CommonObjectDataSubRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/CommonObjectDataSubRecord.java @@ -122,14 +122,14 @@ public final class CommonObjectDataSubRecord extends SubRecord { out.writeInt(field_6_reserved3); } - @Override + @Override protected int getDataSize() { return 2 + 2 + 2 + 4 + 4 + 4; } - /** - * @return the record sid - */ + /** + * @return the record sid + */ public short getSid() { return sid; diff --git a/poi/src/main/java/org/apache/poi/hssf/record/DVALRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/DVALRecord.java index 8fed47a429..9589315aa3 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/DVALRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/DVALRecord.java @@ -27,67 +27,67 @@ import org.apache.poi.util.LittleEndianOutput; * This record is the list header of all data validation records (0x01BE) in the current sheet. */ public final class DVALRecord extends StandardRecord { - public static final short sid = 0x01B2; + public static final short sid = 0x01B2; - /** Options of the DVAL */ - private short field_1_options; - /** Horizontal position of the dialog */ - private int field_2_horiz_pos; - /** Vertical position of the dialog */ - private int field_3_vert_pos; + /** Options of the DVAL */ + private short field_1_options; + /** Horizontal position of the dialog */ + private int field_2_horiz_pos; + /** Vertical position of the dialog */ + private int field_3_vert_pos; - /** Object ID of the drop down arrow object for list boxes ; - * in our case this will be always FFFF , until - * MSODrawingGroup and MSODrawing records are implemented */ - private int field_cbo_id; + /** Object ID of the drop down arrow object for list boxes ; + * in our case this will be always FFFF , until + * MSODrawingGroup and MSODrawing records are implemented */ + private int field_cbo_id; - /** Number of following DV Records */ - private int field_5_dv_no; + /** Number of following DV Records */ + private int field_5_dv_no; public DVALRecord() { field_cbo_id = 0xFFFFFFFF; field_5_dv_no = 0x00000000; } - public DVALRecord(DVALRecord other) { - super(other); - field_1_options = other.field_1_options; - field_2_horiz_pos = other.field_2_horiz_pos; - field_3_vert_pos = other.field_3_vert_pos; - field_cbo_id = other.field_cbo_id; - field_5_dv_no = other.field_5_dv_no; - } + public DVALRecord(DVALRecord other) { + super(other); + field_1_options = other.field_1_options; + field_2_horiz_pos = other.field_2_horiz_pos; + field_3_vert_pos = other.field_3_vert_pos; + field_cbo_id = other.field_cbo_id; + field_5_dv_no = other.field_5_dv_no; + } - public DVALRecord(RecordInputStream in) { - field_1_options = in.readShort(); - field_2_horiz_pos = in.readInt(); - field_3_vert_pos = in.readInt(); + public DVALRecord(RecordInputStream in) { + field_1_options = in.readShort(); + field_2_horiz_pos = in.readInt(); + field_3_vert_pos = in.readInt(); field_cbo_id = in.readInt(); field_5_dv_no = in.readInt(); - } + } /** - * @param options the options of the dialog - */ - public void setOptions(short options) { - field_1_options = options; - } + * @param options the options of the dialog + */ + public void setOptions(short options) { + field_1_options = options; + } - /** - * @param horiz_pos the Horizontal position of the dialog - */ - public void setHorizontalPos(int horiz_pos) { - field_2_horiz_pos = horiz_pos; - } + /** + * @param horiz_pos the Horizontal position of the dialog + */ + public void setHorizontalPos(int horiz_pos) { + field_2_horiz_pos = horiz_pos; + } - /** - * @param vert_pos the Vertical position of the dialog - */ - public void setVerticalPos(int vert_pos) { - field_3_vert_pos = vert_pos; - } + /** + * @param vert_pos the Vertical position of the dialog + */ + public void setVerticalPos(int vert_pos) { + field_3_vert_pos = vert_pos; + } - /** + /** * set the object ID of the drop down arrow object for list boxes * @param cboID - Object ID */ @@ -104,27 +104,27 @@ public final class DVALRecord extends StandardRecord { } /** - * @return the field_1_options - */ - public short getOptions() { - return field_1_options; - } + * @return the field_1_options + */ + public short getOptions() { + return field_1_options; + } - /** - * @return the Horizontal position of the dialog - */ - public int getHorizontalPos() { - return field_2_horiz_pos; - } + /** + * @return the Horizontal position of the dialog + */ + public int getHorizontalPos() { + return field_2_horiz_pos; + } - /** - * @return the the Vertical position of the dialog - */ - public int getVerticalPos() { - return field_3_vert_pos; - } + /** + * @return the the Vertical position of the dialog + */ + public int getVerticalPos() { + return field_3_vert_pos; + } - /** + /** * @return the Object ID of the drop down arrow object for list boxes */ public int getObjectID() { @@ -139,11 +139,11 @@ public final class DVALRecord extends StandardRecord { } public void serialize(LittleEndianOutput out) { - out.writeShort(getOptions()); - out.writeInt(getHorizontalPos()); - out.writeInt(getVerticalPos()); - out.writeInt(getObjectID()); - out.writeInt(getDVRecNo()); + out.writeShort(getOptions()); + out.writeInt(getHorizontalPos()); + out.writeInt(getVerticalPos()); + out.writeInt(getObjectID()); + out.writeInt(getDVRecNo()); } protected int getDataSize() { @@ -154,24 +154,24 @@ public final class DVALRecord extends StandardRecord { return sid; } - @Override + @Override public DVALRecord copy() { return new DVALRecord(this); } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.DVAL; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.DVAL; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "options", this::getOptions, - "horizPos", this::getHorizontalPos, - "vertPos", this::getVerticalPos, - "comboObjectID", this::getObjectID, - "dvRecordsNumber", this::getDVRecNo - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "options", this::getOptions, + "horizPos", this::getHorizontalPos, + "vertPos", this::getVerticalPos, + "comboObjectID", this::getObjectID, + "dvRecordsNumber", this::getDVRecNo + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/DVRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/DVRecord.java index a81e67295e..ac851b225a 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/DVRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/DVRecord.java @@ -38,201 +38,201 @@ import org.apache.poi.util.StringUtil; * This list is followed by DVAL record(s) */ public final class DVRecord extends StandardRecord { - public static final short sid = 0x01BE; + public static final short sid = 0x01BE; - /** the unicode string used for error/prompt title/text when not present */ - private static final UnicodeString NULL_TEXT_STRING = new UnicodeString("\0"); + /** the unicode string used for error/prompt title/text when not present */ + private static final UnicodeString NULL_TEXT_STRING = new UnicodeString("\0"); - /** - * Option flags field - * - * @see HSSFDataValidation utility class - */ - private static final BitField opt_data_type = new BitField(0x0000000F); - private static final BitField opt_error_style = new BitField(0x00000070); - private static final BitField opt_string_list_formula = new BitField(0x00000080); - private static final BitField opt_empty_cell_allowed = new BitField(0x00000100); - private static final BitField opt_suppress_dropdown_arrow = new BitField(0x00000200); - private static final BitField opt_show_prompt_on_cell_selected = new BitField(0x00040000); - private static final BitField opt_show_error_on_invalid_value = new BitField(0x00080000); - private static final BitField opt_condition_operator = new BitField(0x00700000); + /** + * Option flags field + * + * @see HSSFDataValidation utility class + */ + private static final BitField opt_data_type = new BitField(0x0000000F); + private static final BitField opt_error_style = new BitField(0x00000070); + private static final BitField opt_string_list_formula = new BitField(0x00000080); + private static final BitField opt_empty_cell_allowed = new BitField(0x00000100); + private static final BitField opt_suppress_dropdown_arrow = new BitField(0x00000200); + private static final BitField opt_show_prompt_on_cell_selected = new BitField(0x00040000); + private static final BitField opt_show_error_on_invalid_value = new BitField(0x00080000); + private static final BitField opt_condition_operator = new BitField(0x00700000); - private static final int[] FLAG_MASKS = { 0x0000000F,0x00000070,0x00000080,0x00000100, - 0x00000200,0x00040000,0x00080000,0x00700000 }; + private static final int[] FLAG_MASKS = { 0x0000000F,0x00000070,0x00000080,0x00000100, + 0x00000200,0x00040000,0x00080000,0x00700000 }; - private static final String[] FLAG_NAMES = { "DATA_TYPE", "ERROR_STYLE", "STRING_LIST_FORMULA", - "EMPTY_CELL_ALLOWED", "SUPPRESS_DROPDOWN_ARROW", "SHOW_PROMPT_ON_CELL_SELECTED", - "SHOW_ERROR_ON_INVALID_VALUE", "CONDITION_OPERATOR" }; + private static final String[] FLAG_NAMES = { "DATA_TYPE", "ERROR_STYLE", "STRING_LIST_FORMULA", + "EMPTY_CELL_ALLOWED", "SUPPRESS_DROPDOWN_ARROW", "SHOW_PROMPT_ON_CELL_SELECTED", + "SHOW_ERROR_ON_INVALID_VALUE", "CONDITION_OPERATOR" }; - /** Option flags */ - private int _option_flags; - /** Title of the prompt box, cannot be longer than 32 chars */ - private final UnicodeString _promptTitle; - /** Title of the error box, cannot be longer than 32 chars */ - private final UnicodeString _errorTitle; - /** Text of the prompt box, cannot be longer than 255 chars */ - private final UnicodeString _promptText; - /** Text of the error box, cannot be longer than 255 chars */ - private final UnicodeString _errorText; - /** Not used - Excel seems to always write 0x3FE0 */ - private short _not_used_1 = 0x3FE0; - /** Formula data for first condition (RPN token array without size field) */ - private final Formula _formula1; - /** Not used - Excel seems to always write 0x0000 */ - @SuppressWarnings("RedundantFieldInitialization") - private short _not_used_2 = 0x0000; - /** Formula data for second condition (RPN token array without size field) */ - private final Formula _formula2; - /** Cell range address list with all affected ranges */ - private final CellRangeAddressList _regions; + /** Option flags */ + private int _option_flags; + /** Title of the prompt box, cannot be longer than 32 chars */ + private final UnicodeString _promptTitle; + /** Title of the error box, cannot be longer than 32 chars */ + private final UnicodeString _errorTitle; + /** Text of the prompt box, cannot be longer than 255 chars */ + private final UnicodeString _promptText; + /** Text of the error box, cannot be longer than 255 chars */ + private final UnicodeString _errorText; + /** Not used - Excel seems to always write 0x3FE0 */ + private short _not_used_1 = 0x3FE0; + /** Formula data for first condition (RPN token array without size field) */ + private final Formula _formula1; + /** Not used - Excel seems to always write 0x0000 */ + @SuppressWarnings("RedundantFieldInitialization") + private short _not_used_2 = 0x0000; + /** Formula data for second condition (RPN token array without size field) */ + private final Formula _formula2; + /** Cell range address list with all affected ranges */ + private final CellRangeAddressList _regions; - public DVRecord(DVRecord other) { - super(other); - _option_flags = other._option_flags; - _promptTitle = other._promptTitle.copy(); - _errorTitle = other._errorTitle.copy(); - _promptText = other._promptText.copy(); - _errorText = other._errorText.copy(); - _not_used_1 = other._not_used_1; - _formula1 = (other._formula1 == null) ? null : other._formula1.copy(); - _not_used_2 = other._not_used_2; - _formula2 = (other._formula2 == null) ? null : other._formula2.copy(); - _regions = (other._regions == null) ? null : other._regions.copy(); - } + public DVRecord(DVRecord other) { + super(other); + _option_flags = other._option_flags; + _promptTitle = other._promptTitle.copy(); + _errorTitle = other._errorTitle.copy(); + _promptText = other._promptText.copy(); + _errorText = other._errorText.copy(); + _not_used_1 = other._not_used_1; + _formula1 = (other._formula1 == null) ? null : other._formula1.copy(); + _not_used_2 = other._not_used_2; + _formula2 = (other._formula2 == null) ? null : other._formula2.copy(); + _regions = (other._regions == null) ? null : other._regions.copy(); + } - public DVRecord(int validationType, int operator, int errorStyle, boolean emptyCellAllowed, - boolean suppressDropDownArrow, boolean isExplicitList, - boolean showPromptBox, String promptTitle, String promptText, - boolean showErrorBox, String errorTitle, String errorText, - Ptg[] formula1, Ptg[] formula2, - CellRangeAddressList regions) { + public DVRecord(int validationType, int operator, int errorStyle, boolean emptyCellAllowed, + boolean suppressDropDownArrow, boolean isExplicitList, + boolean showPromptBox, String promptTitle, String promptText, + boolean showErrorBox, String errorTitle, String errorText, + Ptg[] formula1, Ptg[] formula2, + CellRangeAddressList regions) { - // check length-limits - if(promptTitle != null && promptTitle.length() > 32) { - throw new IllegalStateException("Prompt-title cannot be longer than 32 characters, but had: " + promptTitle); - } - if(promptText != null && promptText.length() > 255) { - throw new IllegalStateException("Prompt-text cannot be longer than 255 characters, but had: " + promptText); - } + // check length-limits + if(promptTitle != null && promptTitle.length() > 32) { + throw new IllegalStateException("Prompt-title cannot be longer than 32 characters, but had: " + promptTitle); + } + if(promptText != null && promptText.length() > 255) { + throw new IllegalStateException("Prompt-text cannot be longer than 255 characters, but had: " + promptText); + } - if(errorTitle != null && errorTitle.length() > 32) { - throw new IllegalStateException("Error-title cannot be longer than 32 characters, but had: " + errorTitle); - } - if(errorText != null && errorText.length() > 255) { - throw new IllegalStateException("Error-text cannot be longer than 255 characters, but had: " + errorText); - } + if(errorTitle != null && errorTitle.length() > 32) { + throw new IllegalStateException("Error-title cannot be longer than 32 characters, but had: " + errorTitle); + } + if(errorText != null && errorText.length() > 255) { + throw new IllegalStateException("Error-text cannot be longer than 255 characters, but had: " + errorText); + } - int flags = 0; - flags = opt_data_type.setValue(flags, validationType); - flags = opt_condition_operator.setValue(flags, operator); - flags = opt_error_style.setValue(flags, errorStyle); - flags = opt_empty_cell_allowed.setBoolean(flags, emptyCellAllowed); - flags = opt_suppress_dropdown_arrow.setBoolean(flags, suppressDropDownArrow); - flags = opt_string_list_formula.setBoolean(flags, isExplicitList); - flags = opt_show_prompt_on_cell_selected.setBoolean(flags, showPromptBox); - flags = opt_show_error_on_invalid_value.setBoolean(flags, showErrorBox); - _option_flags = flags; - _promptTitle = resolveTitleText(promptTitle); - _promptText = resolveTitleText(promptText); - _errorTitle = resolveTitleText(errorTitle); - _errorText = resolveTitleText(errorText); - _formula1 = Formula.create(formula1); - _formula2 = Formula.create(formula2); - _regions = regions; - } + int flags = 0; + flags = opt_data_type.setValue(flags, validationType); + flags = opt_condition_operator.setValue(flags, operator); + flags = opt_error_style.setValue(flags, errorStyle); + flags = opt_empty_cell_allowed.setBoolean(flags, emptyCellAllowed); + flags = opt_suppress_dropdown_arrow.setBoolean(flags, suppressDropDownArrow); + flags = opt_string_list_formula.setBoolean(flags, isExplicitList); + flags = opt_show_prompt_on_cell_selected.setBoolean(flags, showPromptBox); + flags = opt_show_error_on_invalid_value.setBoolean(flags, showErrorBox); + _option_flags = flags; + _promptTitle = resolveTitleText(promptTitle); + _promptText = resolveTitleText(promptText); + _errorTitle = resolveTitleText(errorTitle); + _errorText = resolveTitleText(errorText); + _formula1 = Formula.create(formula1); + _formula2 = Formula.create(formula2); + _regions = regions; + } - public DVRecord(RecordInputStream in) { - _option_flags = in.readInt(); + public DVRecord(RecordInputStream in) { + _option_flags = in.readInt(); - _promptTitle = readUnicodeString(in); - _errorTitle = readUnicodeString(in); - _promptText = readUnicodeString(in); - _errorText = readUnicodeString(in); + _promptTitle = readUnicodeString(in); + _errorTitle = readUnicodeString(in); + _promptText = readUnicodeString(in); + _errorText = readUnicodeString(in); - int field_size_first_formula = in.readUShort(); - _not_used_1 = in.readShort(); + int field_size_first_formula = in.readUShort(); + _not_used_1 = in.readShort(); - // "You may not use unions, intersections or array constants in Data Validation criteria" + // "You may not use unions, intersections or array constants in Data Validation criteria" - // read first formula data condition - _formula1 = Formula.read(field_size_first_formula, in); + // read first formula data condition + _formula1 = Formula.read(field_size_first_formula, in); - int field_size_sec_formula = in.readUShort(); - _not_used_2 = in.readShort(); + int field_size_sec_formula = in.readUShort(); + _not_used_2 = in.readShort(); - // read sec formula data condition - _formula2 = Formula.read(field_size_sec_formula, in); + // read sec formula data condition + _formula2 = Formula.read(field_size_sec_formula, in); - // read cell range address list with all affected ranges - _regions = new CellRangeAddressList(in); - } + // read cell range address list with all affected ranges + _regions = new CellRangeAddressList(in); + } - /** - * @return the condition data type - * @see org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType - */ - public int getDataType() { - return opt_data_type.getValue(_option_flags); - } + /** + * @return the condition data type + * @see org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType + */ + public int getDataType() { + return opt_data_type.getValue(_option_flags); + } - /** - * @return the condition error style - * @see org.apache.poi.ss.usermodel.DataValidation.ErrorStyle - */ - public int getErrorStyle() { - return opt_error_style.getValue(_option_flags); - } + /** + * @return the condition error style + * @see org.apache.poi.ss.usermodel.DataValidation.ErrorStyle + */ + public int getErrorStyle() { + return opt_error_style.getValue(_option_flags); + } - /** - * @return true if in list validations the string list is explicitly given in the - * formula, false otherwise - */ - public boolean getListExplicitFormula() { - return (opt_string_list_formula.isSet(_option_flags)); - } + /** + * @return true if in list validations the string list is explicitly given in the + * formula, false otherwise + */ + public boolean getListExplicitFormula() { + return (opt_string_list_formula.isSet(_option_flags)); + } - /** - * @return true if empty values are allowed in cells, false otherwise - */ - public boolean getEmptyCellAllowed() { - return (opt_empty_cell_allowed.isSet(_option_flags)); - } + /** + * @return true if empty values are allowed in cells, false otherwise + */ + public boolean getEmptyCellAllowed() { + return (opt_empty_cell_allowed.isSet(_option_flags)); + } - /** - * @return true if drop down arrow should be suppressed when list validation is - * used, false otherwise - */ - public boolean getSuppressDropdownArrow() { - return (opt_suppress_dropdown_arrow.isSet(_option_flags)); - } + /** + * @return true if drop down arrow should be suppressed when list validation is + * used, false otherwise + */ + public boolean getSuppressDropdownArrow() { + return (opt_suppress_dropdown_arrow.isSet(_option_flags)); + } - /** - * @return true if a prompt window should appear when cell is selected, false otherwise - */ - public boolean getShowPromptOnCellSelected() { - return (opt_show_prompt_on_cell_selected.isSet(_option_flags)); - } + /** + * @return true if a prompt window should appear when cell is selected, false otherwise + */ + public boolean getShowPromptOnCellSelected() { + return (opt_show_prompt_on_cell_selected.isSet(_option_flags)); + } - /** - * @return true if an error window should appear when an invalid value is entered - * in the cell, false otherwise - */ - public boolean getShowErrorOnInvalidValue() { - return (opt_show_error_on_invalid_value.isSet(_option_flags)); - } + /** + * @return true if an error window should appear when an invalid value is entered + * in the cell, false otherwise + */ + public boolean getShowErrorOnInvalidValue() { + return (opt_show_error_on_invalid_value.isSet(_option_flags)); + } - /** - * get the condition operator - * @return the condition operator - * @see HSSFDataValidation utility class - */ - public int getConditionOperator() { - return opt_condition_operator.getValue(_option_flags); - } - // <-- end option flags + /** + * get the condition operator + * @return the condition operator + * @see HSSFDataValidation utility class + */ + public int getConditionOperator() { + return opt_condition_operator.getValue(_option_flags); + } + // <-- end option flags public String getPromptTitle() { return resolveTitleString(_promptTitle); @@ -258,42 +258,42 @@ public final class DVRecord extends StandardRecord { return Formula.getTokens(_formula2); } - public CellRangeAddressList getCellRangeAddress() { - return this._regions; - } + public CellRangeAddressList getCellRangeAddress() { + return this._regions; + } - public void serialize(LittleEndianOutput out) { + public void serialize(LittleEndianOutput out) { - out.writeInt(_option_flags); + out.writeInt(_option_flags); - serializeUnicodeString(_promptTitle, out); - serializeUnicodeString(_errorTitle, out); - serializeUnicodeString(_promptText, out); - serializeUnicodeString(_errorText, out); - out.writeShort(_formula1.getEncodedTokenSize()); - out.writeShort(_not_used_1); - _formula1.serializeTokens(out); + serializeUnicodeString(_promptTitle, out); + serializeUnicodeString(_errorTitle, out); + serializeUnicodeString(_promptText, out); + serializeUnicodeString(_errorText, out); + out.writeShort(_formula1.getEncodedTokenSize()); + out.writeShort(_not_used_1); + _formula1.serializeTokens(out); - out.writeShort(_formula2.getEncodedTokenSize()); - out.writeShort(_not_used_2); - _formula2.serializeTokens(out); + out.writeShort(_formula2.getEncodedTokenSize()); + out.writeShort(_not_used_2); + _formula2.serializeTokens(out); - _regions.serialize(out); - } + _regions.serialize(out); + } - /** - * When entered via the UI, Excel translates empty string into "\0" - * While it is possible to encode the title/text as empty string (Excel doesn't exactly crash), - * the resulting tool-tip text / message box looks wrong. It is best to do the same as the - * Excel UI and encode 'not present' as "\0". - */ - private static UnicodeString resolveTitleText(String str) { - if (str == null || str.length() < 1) { - return NULL_TEXT_STRING; - } - return new UnicodeString(str); - } + /** + * When entered via the UI, Excel translates empty string into "\0" + * While it is possible to encode the title/text as empty string (Excel doesn't exactly crash), + * the resulting tool-tip text / message box looks wrong. It is best to do the same as the + * Excel UI and encode 'not present' as "\0". + */ + private static UnicodeString resolveTitleText(String str) { + if (str == null || str.length() < 1) { + return NULL_TEXT_STRING; + } + return new UnicodeString(str); + } private static String resolveTitleString(UnicodeString us) { if (us == null || us.equals(NULL_TEXT_STRING)) { @@ -302,56 +302,56 @@ public final class DVRecord extends StandardRecord { return us.getString(); } - private static UnicodeString readUnicodeString(RecordInputStream in) { - return new UnicodeString(in); - } + private static UnicodeString readUnicodeString(RecordInputStream in) { + return new UnicodeString(in); + } - private static void serializeUnicodeString(UnicodeString us, LittleEndianOutput out) { - StringUtil.writeUnicodeString(out, us.getString()); - } - private static int getUnicodeStringSize(UnicodeString us) { - String str = us.getString(); - return 3 + str.length() * (StringUtil.hasMultibyte(str) ? 2 : 1); - } + private static void serializeUnicodeString(UnicodeString us, LittleEndianOutput out) { + StringUtil.writeUnicodeString(out, us.getString()); + } + private static int getUnicodeStringSize(UnicodeString us) { + String str = us.getString(); + return 3 + str.length() * (StringUtil.hasMultibyte(str) ? 2 : 1); + } - protected int getDataSize() { - int size = 4+2+2+2+2;//options_field+first_formula_size+first_unused+sec_formula_size+sec+unused; - size += getUnicodeStringSize(_promptTitle); - size += getUnicodeStringSize(_errorTitle); - size += getUnicodeStringSize(_promptText); - size += getUnicodeStringSize(_errorText); - size += _formula1.getEncodedTokenSize(); - size += _formula2.getEncodedTokenSize(); - size += _regions.getSize(); - return size; - } + protected int getDataSize() { + int size = 4+2+2+2+2;//options_field+first_formula_size+first_unused+sec_formula_size+sec+unused; + size += getUnicodeStringSize(_promptTitle); + size += getUnicodeStringSize(_errorTitle); + size += getUnicodeStringSize(_promptText); + size += getUnicodeStringSize(_errorText); + size += _formula1.getEncodedTokenSize(); + size += _formula2.getEncodedTokenSize(); + size += _regions.getSize(); + return size; + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - /** Clones the object. */ - @Override - public DVRecord copy() { - return new DVRecord(this); - } + /** Clones the object. */ + @Override + public DVRecord copy() { + return new DVRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.DV; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.DV; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "optionFlags", getBitsAsString(() -> _option_flags, FLAG_MASKS, FLAG_NAMES), - "promptTitle", this::getPromptTitle, - "errorTitle", this::getErrorTitle, - "promptText", this::getPromptText, - "errorText", this::getErrorText, - "formula1", this::getFormula1, - "formula2", this::getFormula2, - "regions", () -> _regions - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "optionFlags", getBitsAsString(() -> _option_flags, FLAG_MASKS, FLAG_NAMES), + "promptTitle", this::getPromptTitle, + "errorTitle", this::getErrorTitle, + "promptText", this::getPromptText, + "errorText", this::getErrorText, + "formula1", this::getFormula1, + "formula2", this::getFormula2, + "regions", () -> _regions + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/DrawingRecordForBiffViewer.java b/poi/src/main/java/org/apache/poi/hssf/record/DrawingRecordForBiffViewer.java index 8c9743f4bd..f03028d823 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/DrawingRecordForBiffViewer.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/DrawingRecordForBiffViewer.java @@ -41,17 +41,17 @@ public final class DrawingRecordForBiffViewer extends AbstractEscherHolderRecord public DrawingRecordForBiffViewer(DrawingRecord r) { - super(convertToInputStream(r)); - decode(); + super(convertToInputStream(r)); + decode(); } private static RecordInputStream convertToInputStream(DrawingRecord r) { - byte[] data = r.serialize(); - RecordInputStream rinp = new RecordInputStream( - new ByteArrayInputStream(data) - ); - rinp.nextRecord(); - return rinp; + byte[] data = r.serialize(); + RecordInputStream rinp = new RecordInputStream( + new ByteArrayInputStream(data) + ); + rinp.nextRecord(); + return rinp; } protected String getRecordName() diff --git a/poi/src/main/java/org/apache/poi/hssf/record/DrawingSelectionRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/DrawingSelectionRecord.java index 94b6ac83d6..ea2654ee35 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/DrawingSelectionRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/DrawingSelectionRecord.java @@ -31,107 +31,107 @@ import org.apache.poi.util.LittleEndianOutput; * [MS-OGRAPH].pdf sec 2.4.69 */ public final class DrawingSelectionRecord extends StandardRecord { - public static final short sid = 0x00ED; + public static final short sid = 0x00ED; - /** - * From [MS-ODRAW].pdf sec 2.2.1

- * TODO - make EscherRecordHeader {@link LittleEndianInput} aware and refactor with this - */ - private static final class OfficeArtRecordHeader implements GenericRecord { - public static final int ENCODED_SIZE = 8; - /** - * lower 4 bits is 'version' usually 0x01 or 0x0F (for containers) - * upper 12 bits is 'instance' - */ - private final int _verAndInstance; - /** value should be between 0xF000 and 0xFFFF */ - private final int _type; - private final int _length; + /** + * From [MS-ODRAW].pdf sec 2.2.1

+ * TODO - make EscherRecordHeader {@link LittleEndianInput} aware and refactor with this + */ + private static final class OfficeArtRecordHeader implements GenericRecord { + public static final int ENCODED_SIZE = 8; + /** + * lower 4 bits is 'version' usually 0x01 or 0x0F (for containers) + * upper 12 bits is 'instance' + */ + private final int _verAndInstance; + /** value should be between 0xF000 and 0xFFFF */ + private final int _type; + private final int _length; - public OfficeArtRecordHeader(LittleEndianInput in) { - _verAndInstance = in.readUShort(); - _type = in.readUShort(); - _length = in.readInt(); - } + public OfficeArtRecordHeader(LittleEndianInput in) { + _verAndInstance = in.readUShort(); + _type = in.readUShort(); + _length = in.readInt(); + } - public void serialize(LittleEndianOutput out) { - out.writeShort(_verAndInstance); - out.writeShort(_type); - out.writeInt(_length); - } + public void serialize(LittleEndianOutput out) { + out.writeShort(_verAndInstance); + out.writeShort(_type); + out.writeInt(_length); + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "verAndInstance", () -> _verAndInstance, - "type", () -> _type, - "length", () -> _length - ); - } - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "verAndInstance", () -> _verAndInstance, + "type", () -> _type, + "length", () -> _length + ); + } + } - // [MS-OGRAPH].pdf says that the data of this record is an OfficeArtFDGSL structure - // as described in[MS-ODRAW].pdf sec 2.2.33 - private OfficeArtRecordHeader _header; - private int _cpsp; - /** a MSODGSLK enum value for the current selection mode */ - private int _dgslk; - private int _spidFocus; - /** selected shape IDs (e.g. from EscherSpRecord.ShapeId) */ - private int[] _shapeIds; + // [MS-OGRAPH].pdf says that the data of this record is an OfficeArtFDGSL structure + // as described in[MS-ODRAW].pdf sec 2.2.33 + private OfficeArtRecordHeader _header; + private int _cpsp; + /** a MSODGSLK enum value for the current selection mode */ + private int _dgslk; + private int _spidFocus; + /** selected shape IDs (e.g. from EscherSpRecord.ShapeId) */ + private int[] _shapeIds; - public DrawingSelectionRecord(RecordInputStream in) { - _header = new OfficeArtRecordHeader(in); - _cpsp = in.readInt(); - _dgslk = in.readInt(); - _spidFocus = in.readInt(); - int nShapes = in.available() / 4; - int[] shapeIds = new int[nShapes]; - for (int i = 0; i < nShapes; i++) { - shapeIds[i] = in.readInt(); - } - _shapeIds = shapeIds; - } + public DrawingSelectionRecord(RecordInputStream in) { + _header = new OfficeArtRecordHeader(in); + _cpsp = in.readInt(); + _dgslk = in.readInt(); + _spidFocus = in.readInt(); + int nShapes = in.available() / 4; + int[] shapeIds = new int[nShapes]; + for (int i = 0; i < nShapes; i++) { + shapeIds[i] = in.readInt(); + } + _shapeIds = shapeIds; + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - protected int getDataSize() { - return OfficeArtRecordHeader.ENCODED_SIZE - + 12 // 3 int fields - + _shapeIds.length * 4; - } + protected int getDataSize() { + return OfficeArtRecordHeader.ENCODED_SIZE + + 12 // 3 int fields + + _shapeIds.length * 4; + } - public void serialize(LittleEndianOutput out) { - _header.serialize(out); - out.writeInt(_cpsp); - out.writeInt(_dgslk); - out.writeInt(_spidFocus); - for (int shapeId : _shapeIds) { - out.writeInt(shapeId); - } - } + public void serialize(LittleEndianOutput out) { + _header.serialize(out); + out.writeInt(_cpsp); + out.writeInt(_dgslk); + out.writeInt(_spidFocus); + for (int shapeId : _shapeIds) { + out.writeInt(shapeId); + } + } - @Override - public DrawingSelectionRecord copy() { - // currently immutable - return this; - } + @Override + public DrawingSelectionRecord copy() { + // currently immutable + return this; + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.DRAWING_SELECTION; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.DRAWING_SELECTION; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "rh", () -> _header, - "cpsp", () -> _cpsp, - "dgslk", () -> _dgslk, - "spidFocus", () -> _spidFocus, - "shapeIds", () -> _shapeIds - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "rh", () -> _header, + "cpsp", () -> _cpsp, + "dgslk", () -> _dgslk, + "spidFocus", () -> _spidFocus, + "shapeIds", () -> _shapeIds + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/EOFRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/EOFRecord.java index a067b2917d..cd7657b5b3 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/EOFRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/EOFRecord.java @@ -29,9 +29,9 @@ import org.apache.poi.util.LittleEndianOutput; */ public final class EOFRecord extends StandardRecord { public static final short sid = 0x0A; - public static final int ENCODED_SIZE = 4; + public static final int ENCODED_SIZE = 4; - public static final EOFRecord instance = new EOFRecord(); + public static final EOFRecord instance = new EOFRecord(); private EOFRecord() {} diff --git a/poi/src/main/java/org/apache/poi/hssf/record/EmbeddedObjectRefSubRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/EmbeddedObjectRefSubRecord.java index ab5d3874ef..f43bf9ed52 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/EmbeddedObjectRefSubRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/EmbeddedObjectRefSubRecord.java @@ -6,7 +6,7 @@ (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 + 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, @@ -45,315 +45,315 @@ import static org.apache.logging.log4j.util.Unbox.box; * stored in a separate entry within the OLE2 compound file. */ public final class EmbeddedObjectRefSubRecord extends SubRecord { - private static final Logger LOG = LogManager.getLogger(EmbeddedObjectRefSubRecord.class); - //arbitrarily selected; may need to increase - private static final int MAX_RECORD_LENGTH = 100_000; + private static final Logger LOG = LogManager.getLogger(EmbeddedObjectRefSubRecord.class); + //arbitrarily selected; may need to increase + private static final int MAX_RECORD_LENGTH = 100_000; - public static final short sid = 0x0009; + public static final short sid = 0x0009; - private static final byte[] EMPTY_BYTE_ARRAY = { }; + private static final byte[] EMPTY_BYTE_ARRAY = { }; - private int field_1_unknown_int; - /** either an area or a cell ref */ - private Ptg field_2_refPtg; - /** for when the 'formula' doesn't parse properly */ - private byte[] field_2_unknownFormulaData; - /** note- this byte is not present in the encoding if the string length is zero */ - private boolean field_3_unicode_flag; // Flags whether the string is Unicode. - private String field_4_ole_classname; // Classname of the embedded OLE document (e.g. Word.Document.8) - /** Formulas often have a single non-zero trailing byte. - * This is in a similar position to he pre-streamId padding - * It is unknown if the value is important (it seems to mirror a value a few bytes earlier) - * */ - private Byte field_4_unknownByte; - private Integer field_5_stream_id; // ID of the OLE stream containing the actual data. - private byte[] field_6_unknown; + private int field_1_unknown_int; + /** either an area or a cell ref */ + private Ptg field_2_refPtg; + /** for when the 'formula' doesn't parse properly */ + private byte[] field_2_unknownFormulaData; + /** note- this byte is not present in the encoding if the string length is zero */ + private boolean field_3_unicode_flag; // Flags whether the string is Unicode. + private String field_4_ole_classname; // Classname of the embedded OLE document (e.g. Word.Document.8) + /** Formulas often have a single non-zero trailing byte. + * This is in a similar position to he pre-streamId padding + * It is unknown if the value is important (it seems to mirror a value a few bytes earlier) + * */ + private Byte field_4_unknownByte; + private Integer field_5_stream_id; // ID of the OLE stream containing the actual data. + private byte[] field_6_unknown; - // currently for testing only - needs review - public EmbeddedObjectRefSubRecord() { - field_2_unknownFormulaData = new byte[] { 0x02, 0x6C, 0x6A, 0x16, 0x01, }; // just some sample data. These values vary a lot - field_6_unknown = EMPTY_BYTE_ARRAY; - field_4_ole_classname = null; - } + // currently for testing only - needs review + public EmbeddedObjectRefSubRecord() { + field_2_unknownFormulaData = new byte[] { 0x02, 0x6C, 0x6A, 0x16, 0x01, }; // just some sample data. These values vary a lot + field_6_unknown = EMPTY_BYTE_ARRAY; + field_4_ole_classname = null; + } - public EmbeddedObjectRefSubRecord(EmbeddedObjectRefSubRecord other) { - super(other); - field_1_unknown_int = other.field_1_unknown_int; - field_2_refPtg = (other.field_2_refPtg == null) ? null : other.field_2_refPtg.copy(); - field_2_unknownFormulaData = (other.field_2_unknownFormulaData == null) ? null : other.field_2_unknownFormulaData.clone(); - field_3_unicode_flag = other.field_3_unicode_flag; - field_4_ole_classname = other.field_4_ole_classname; - field_4_unknownByte = other.field_4_unknownByte; - field_5_stream_id = other.field_5_stream_id; - field_6_unknown = (other.field_6_unknown == null) ? null : other.field_6_unknown.clone(); - } + public EmbeddedObjectRefSubRecord(EmbeddedObjectRefSubRecord other) { + super(other); + field_1_unknown_int = other.field_1_unknown_int; + field_2_refPtg = (other.field_2_refPtg == null) ? null : other.field_2_refPtg.copy(); + field_2_unknownFormulaData = (other.field_2_unknownFormulaData == null) ? null : other.field_2_unknownFormulaData.clone(); + field_3_unicode_flag = other.field_3_unicode_flag; + field_4_ole_classname = other.field_4_ole_classname; + field_4_unknownByte = other.field_4_unknownByte; + field_5_stream_id = other.field_5_stream_id; + field_6_unknown = (other.field_6_unknown == null) ? null : other.field_6_unknown.clone(); + } - public EmbeddedObjectRefSubRecord(LittleEndianInput in, int size) { - this(in,size,-1); - } + public EmbeddedObjectRefSubRecord(LittleEndianInput in, int size) { + this(in,size,-1); + } - EmbeddedObjectRefSubRecord(LittleEndianInput in, int size, int cmoOt) { + EmbeddedObjectRefSubRecord(LittleEndianInput in, int size, int cmoOt) { - // Much guess-work going on here due to lack of any documentation. - // See similar source code in OOO: - // http://svn.services.openoffice.org/ooo/trunk/sc/source/filter/excel/xiescher.cxx - // 1223 void XclImpOleObj::ReadPictFmla( XclImpStream& rStrm, sal_uInt16 nRecSize ) + // Much guess-work going on here due to lack of any documentation. + // See similar source code in OOO: + // http://svn.services.openoffice.org/ooo/trunk/sc/source/filter/excel/xiescher.cxx + // 1223 void XclImpOleObj::ReadPictFmla( XclImpStream& rStrm, sal_uInt16 nRecSize ) - int streamIdOffset = in.readShort(); // OOO calls this 'nFmlaLen' - int remaining = size - LittleEndianConsts.SHORT_SIZE; + int streamIdOffset = in.readShort(); // OOO calls this 'nFmlaLen' + int remaining = size - LittleEndianConsts.SHORT_SIZE; - int dataLenAfterFormula = remaining - streamIdOffset; - int formulaSize = in.readUShort(); - remaining -= LittleEndianConsts.SHORT_SIZE; - field_1_unknown_int = in.readInt(); - remaining -= LittleEndianConsts.INT_SIZE; - byte[] formulaRawBytes = readRawData(in, formulaSize); - remaining -= formulaSize; - field_2_refPtg = readRefPtg(formulaRawBytes); - if (field_2_refPtg == null) { - // common case - // field_2_n16 seems to be 5 here - // The formula almost looks like tTbl but the row/column values seem like garbage. - field_2_unknownFormulaData = formulaRawBytes; - } else { - field_2_unknownFormulaData = null; - } + int dataLenAfterFormula = remaining - streamIdOffset; + int formulaSize = in.readUShort(); + remaining -= LittleEndianConsts.SHORT_SIZE; + field_1_unknown_int = in.readInt(); + remaining -= LittleEndianConsts.INT_SIZE; + byte[] formulaRawBytes = readRawData(in, formulaSize); + remaining -= formulaSize; + field_2_refPtg = readRefPtg(formulaRawBytes); + if (field_2_refPtg == null) { + // common case + // field_2_n16 seems to be 5 here + // The formula almost looks like tTbl but the row/column values seem like garbage. + field_2_unknownFormulaData = formulaRawBytes; + } else { + field_2_unknownFormulaData = null; + } - int stringByteCount; - if (remaining >= dataLenAfterFormula + 3) { - int tag = in.readByte(); - stringByteCount = LittleEndianConsts.BYTE_SIZE; - if (tag != 0x03) { - throw new RecordFormatException("Expected byte 0x03 here"); - } - int nChars = in.readUShort(); - stringByteCount += LittleEndianConsts.SHORT_SIZE; - if (nChars > 0) { - // OOO: the 4th way Xcl stores a unicode string: not even a Grbit byte present if length 0 - field_3_unicode_flag = ( in.readByte() & 0x01 ) != 0; - stringByteCount += LittleEndianConsts.BYTE_SIZE; - if (field_3_unicode_flag) { - field_4_ole_classname = StringUtil.readUnicodeLE(in, nChars); - stringByteCount += nChars * 2; - } else { - field_4_ole_classname = StringUtil.readCompressedUnicode(in, nChars); - stringByteCount += nChars; - } - } else { - field_4_ole_classname = ""; - } - } else { - field_4_ole_classname = null; - stringByteCount = 0; - } - remaining -= stringByteCount; - // Pad to next 2-byte boundary - if (((stringByteCount + formulaSize) % 2) != 0) { - int b = in.readByte(); - remaining -= LittleEndianConsts.BYTE_SIZE; - if (field_2_refPtg != null && field_4_ole_classname == null) { - field_4_unknownByte = (byte)b; - } - } - int nUnexpectedPadding = remaining - dataLenAfterFormula; + int stringByteCount; + if (remaining >= dataLenAfterFormula + 3) { + int tag = in.readByte(); + stringByteCount = LittleEndianConsts.BYTE_SIZE; + if (tag != 0x03) { + throw new RecordFormatException("Expected byte 0x03 here"); + } + int nChars = in.readUShort(); + stringByteCount += LittleEndianConsts.SHORT_SIZE; + if (nChars > 0) { + // OOO: the 4th way Xcl stores a unicode string: not even a Grbit byte present if length 0 + field_3_unicode_flag = ( in.readByte() & 0x01 ) != 0; + stringByteCount += LittleEndianConsts.BYTE_SIZE; + if (field_3_unicode_flag) { + field_4_ole_classname = StringUtil.readUnicodeLE(in, nChars); + stringByteCount += nChars * 2; + } else { + field_4_ole_classname = StringUtil.readCompressedUnicode(in, nChars); + stringByteCount += nChars; + } + } else { + field_4_ole_classname = ""; + } + } else { + field_4_ole_classname = null; + stringByteCount = 0; + } + remaining -= stringByteCount; + // Pad to next 2-byte boundary + if (((stringByteCount + formulaSize) % 2) != 0) { + int b = in.readByte(); + remaining -= LittleEndianConsts.BYTE_SIZE; + if (field_2_refPtg != null && field_4_ole_classname == null) { + field_4_unknownByte = (byte)b; + } + } + int nUnexpectedPadding = remaining - dataLenAfterFormula; - if (nUnexpectedPadding > 0) { - LOG.atError().log("Discarding {} unexpected padding bytes", box(nUnexpectedPadding)); - readRawData(in, nUnexpectedPadding); - remaining-=nUnexpectedPadding; - } + if (nUnexpectedPadding > 0) { + LOG.atError().log("Discarding {} unexpected padding bytes", box(nUnexpectedPadding)); + readRawData(in, nUnexpectedPadding); + remaining-=nUnexpectedPadding; + } - // Fetch the stream ID - if (dataLenAfterFormula >= 4) { - field_5_stream_id = in.readInt(); - remaining -= LittleEndianConsts.INT_SIZE; - } else { - field_5_stream_id = null; - } - field_6_unknown = readRawData(in, remaining); - } + // Fetch the stream ID + if (dataLenAfterFormula >= 4) { + field_5_stream_id = in.readInt(); + remaining -= LittleEndianConsts.INT_SIZE; + } else { + field_5_stream_id = null; + } + field_6_unknown = readRawData(in, remaining); + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - private static Ptg readRefPtg(byte[] formulaRawBytes) { - LittleEndianInput in = new LittleEndianInputStream(new ByteArrayInputStream(formulaRawBytes)); - byte ptgSid = in.readByte(); - switch(ptgSid) { - case AreaPtg.sid: return new AreaPtg(in); - case Area3DPtg.sid: return new Area3DPtg(in); - case RefPtg.sid: return new RefPtg(in); - case Ref3DPtg.sid: return new Ref3DPtg(in); - } - return null; - } + private static Ptg readRefPtg(byte[] formulaRawBytes) { + LittleEndianInput in = new LittleEndianInputStream(new ByteArrayInputStream(formulaRawBytes)); + byte ptgSid = in.readByte(); + switch(ptgSid) { + case AreaPtg.sid: return new AreaPtg(in); + case Area3DPtg.sid: return new Area3DPtg(in); + case RefPtg.sid: return new RefPtg(in); + case Ref3DPtg.sid: return new Ref3DPtg(in); + } + return null; + } - private static byte[] readRawData(LittleEndianInput in, int size) { - if (size < 0) { - throw new IllegalArgumentException("Negative size (" + size + ")"); - } - if (size == 0) { - return EMPTY_BYTE_ARRAY; - } - byte[] result = IOUtils.safelyAllocate(size, MAX_RECORD_LENGTH); - in.readFully(result); - return result; - } + private static byte[] readRawData(LittleEndianInput in, int size) { + if (size < 0) { + throw new IllegalArgumentException("Negative size (" + size + ")"); + } + if (size == 0) { + return EMPTY_BYTE_ARRAY; + } + byte[] result = IOUtils.safelyAllocate(size, MAX_RECORD_LENGTH); + in.readFully(result); + return result; + } - private int getStreamIDOffset(int formulaSize) { - int result = 2 + 4; // formulaSize + f2unknown_int - result += formulaSize; + private int getStreamIDOffset(int formulaSize) { + int result = 2 + 4; // formulaSize + f2unknown_int + result += formulaSize; - // don't write 0x03, stringLen, flag, text - if (field_4_ole_classname != null) { - result += 1 + 2; // 0x03, stringLen - int stringLen = field_4_ole_classname.length(); - if (stringLen > 0) { - result += 1; // flag - if (field_3_unicode_flag) { - result += stringLen * 2; - } else { - result += stringLen; - } - } - } - // pad to next 2 byte boundary - if ((result % 2) != 0) { - result ++; - } - return result; - } + // don't write 0x03, stringLen, flag, text + if (field_4_ole_classname != null) { + result += 1 + 2; // 0x03, stringLen + int stringLen = field_4_ole_classname.length(); + if (stringLen > 0) { + result += 1; // flag + if (field_3_unicode_flag) { + result += stringLen * 2; + } else { + result += stringLen; + } + } + } + // pad to next 2 byte boundary + if ((result % 2) != 0) { + result ++; + } + return result; + } - private int getDataSize(int idOffset) { + private int getDataSize(int idOffset) { - int result = 2 + idOffset; // 2 for idOffset short field itself - if (field_5_stream_id != null) { - result += 4; - } - return result + field_6_unknown.length; - } - protected int getDataSize() { - int formulaSize = field_2_refPtg == null ? field_2_unknownFormulaData.length : field_2_refPtg.getSize(); - int idOffset = getStreamIDOffset(formulaSize); - return getDataSize(idOffset); - } + int result = 2 + idOffset; // 2 for idOffset short field itself + if (field_5_stream_id != null) { + result += 4; + } + return result + field_6_unknown.length; + } + protected int getDataSize() { + int formulaSize = field_2_refPtg == null ? field_2_unknownFormulaData.length : field_2_refPtg.getSize(); + int idOffset = getStreamIDOffset(formulaSize); + return getDataSize(idOffset); + } - public void serialize(LittleEndianOutput out) { + public void serialize(LittleEndianOutput out) { - int formulaSize = field_2_refPtg == null ? field_2_unknownFormulaData.length : field_2_refPtg.getSize(); - int idOffset = getStreamIDOffset(formulaSize); - int dataSize = getDataSize(idOffset); + int formulaSize = field_2_refPtg == null ? field_2_unknownFormulaData.length : field_2_refPtg.getSize(); + int idOffset = getStreamIDOffset(formulaSize); + int dataSize = getDataSize(idOffset); - out.writeShort(sid); - out.writeShort(dataSize); + out.writeShort(sid); + out.writeShort(dataSize); - out.writeShort(idOffset); - out.writeShort(formulaSize); - out.writeInt(field_1_unknown_int); + out.writeShort(idOffset); + out.writeShort(formulaSize); + out.writeInt(field_1_unknown_int); - int pos = 12; + int pos = 12; - if (field_2_refPtg == null) { - out.write(field_2_unknownFormulaData); - } else { - field_2_refPtg.write(out); - } - pos += formulaSize; + if (field_2_refPtg == null) { + out.write(field_2_unknownFormulaData); + } else { + field_2_refPtg.write(out); + } + pos += formulaSize; - // don't write 0x03, stringLen, flag, text - if (field_4_ole_classname != null) { - out.writeByte(0x03); - pos+=1; - int stringLen = field_4_ole_classname.length(); - out.writeShort(stringLen); - pos+=2; - if (stringLen > 0) { - out.writeByte(field_3_unicode_flag ? 0x01 : 0x00); - pos+=1; + // don't write 0x03, stringLen, flag, text + if (field_4_ole_classname != null) { + out.writeByte(0x03); + pos+=1; + int stringLen = field_4_ole_classname.length(); + out.writeShort(stringLen); + pos+=2; + if (stringLen > 0) { + out.writeByte(field_3_unicode_flag ? 0x01 : 0x00); + pos+=1; - if (field_3_unicode_flag) { - StringUtil.putUnicodeLE(field_4_ole_classname, out); - pos += stringLen * 2; - } else { - StringUtil.putCompressedUnicode(field_4_ole_classname, out); - pos += stringLen; - } - } - } + if (field_3_unicode_flag) { + StringUtil.putUnicodeLE(field_4_ole_classname, out); + pos += stringLen * 2; + } else { + StringUtil.putCompressedUnicode(field_4_ole_classname, out); + pos += stringLen; + } + } + } - // pad to next 2-byte boundary (requires 0 or 1 bytes) - switch(idOffset - (pos - 6)) { // 6 for 3 shorts: sid, dataSize, idOffset - case 1: - out.writeByte(field_4_unknownByte == null ? 0x00 : field_4_unknownByte.intValue()); - break; - case 0: - break; - default: - throw new IllegalStateException("Bad padding calculation (" + idOffset + ", " + pos + ")"); - } + // pad to next 2-byte boundary (requires 0 or 1 bytes) + switch(idOffset - (pos - 6)) { // 6 for 3 shorts: sid, dataSize, idOffset + case 1: + out.writeByte(field_4_unknownByte == null ? 0x00 : field_4_unknownByte.intValue()); + break; + case 0: + break; + default: + throw new IllegalStateException("Bad padding calculation (" + idOffset + ", " + pos + ")"); + } - if (field_5_stream_id != null) { - out.writeInt(field_5_stream_id); - } - out.write(field_6_unknown); - } + if (field_5_stream_id != null) { + out.writeInt(field_5_stream_id); + } + out.write(field_6_unknown); + } - /** - * Gets the stream ID containing the actual data. The data itself - * can be found under a top-level directory entry in the OLE2 filesystem - * under the name "MBDxxxxxxxx" where xxxxxxxx is - * this ID converted into hex (in big endian order, funnily enough.) - * - * @return the data stream ID. Possibly null - */ - public Integer getStreamId() { - return field_5_stream_id; - } + /** + * Gets the stream ID containing the actual data. The data itself + * can be found under a top-level directory entry in the OLE2 filesystem + * under the name "MBDxxxxxxxx" where xxxxxxxx is + * this ID converted into hex (in big endian order, funnily enough.) + * + * @return the data stream ID. Possibly null + */ + public Integer getStreamId() { + return field_5_stream_id; + } - public String getOLEClassName() { - return field_4_ole_classname; - } + public String getOLEClassName() { + return field_4_ole_classname; + } - public byte[] getObjectData() { - return field_6_unknown; - } + public byte[] getObjectData() { + return field_6_unknown; + } - @Override - public EmbeddedObjectRefSubRecord copy() { - return new EmbeddedObjectRefSubRecord(this); - } + @Override + public EmbeddedObjectRefSubRecord copy() { + return new EmbeddedObjectRefSubRecord(this); + } - public void setUnknownFormulaData(byte[] formularData) { - field_2_unknownFormulaData = formularData; - } + public void setUnknownFormulaData(byte[] formularData) { + field_2_unknownFormulaData = formularData; + } - public void setOleClassname(String oleClassname) { - field_4_ole_classname = oleClassname; - } + public void setOleClassname(String oleClassname) { + field_4_ole_classname = oleClassname; + } - public void setStorageId(int storageId) { - field_5_stream_id = storageId; - } + public void setStorageId(int storageId) { + field_5_stream_id = storageId; + } - @Override - public SubRecordTypes getGenericRecordType() { - return SubRecordTypes.EMBEDDED_OBJECT_REF; - } + @Override + public SubRecordTypes getGenericRecordType() { + return SubRecordTypes.EMBEDDED_OBJECT_REF; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "f2unknown", () -> field_1_unknown_int, - "f3unknown", () -> field_2_unknownFormulaData, - "formula", () -> field_2_refPtg, - "unicodeFlag", () -> field_3_unicode_flag, - "oleClassname", () -> field_4_ole_classname, - "f4unknown", () -> field_4_unknownByte, - "streamId", () -> field_5_stream_id, - "f7unknown", () -> field_6_unknown - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "f2unknown", () -> field_1_unknown_int, + "f3unknown", () -> field_2_unknownFormulaData, + "formula", () -> field_2_refPtg, + "unicodeFlag", () -> field_3_unicode_flag, + "oleClassname", () -> field_4_ole_classname, + "f4unknown", () -> field_4_unknownByte, + "streamId", () -> field_5_stream_id, + "f7unknown", () -> field_6_unknown + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/EndSubRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/EndSubRecord.java index 498ce88b06..bcc9c0b86f 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/EndSubRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/EndSubRecord.java @@ -60,7 +60,7 @@ public final class EndSubRecord extends SubRecord { out.writeShort(ENCODED_SIZE); } - protected int getDataSize() { + protected int getDataSize() { return ENCODED_SIZE; } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/ExtSSTRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/ExtSSTRecord.java index b8a9aed2c0..a2e6d46be1 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/ExtSSTRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/ExtSSTRecord.java @@ -43,7 +43,7 @@ public final class ExtSSTRecord extends ContinuableRecord { public static final class InfoSubRecord implements GenericRecord { - public static final int ENCODED_SIZE = 8; + public static final int ENCODED_SIZE = 8; private int field_1_stream_pos; // stream pointer to the SST record private int field_2_bucket_sst_offset; // don't really understand this yet. /** unused - supposed to be zero */ @@ -101,7 +101,7 @@ public final class ExtSSTRecord extends ContinuableRecord { public ExtSSTRecord() { - _stringsPerBucket = DEFAULT_BUCKET_SIZE; + _stringsPerBucket = DEFAULT_BUCKET_SIZE; _sstInfos = new InfoSubRecord[0]; } @@ -140,7 +140,7 @@ public final class ExtSSTRecord extends ContinuableRecord { } int getDataSize() { - return 2 + InfoSubRecord.ENCODED_SIZE*_sstInfos.length; + return 2 + InfoSubRecord.ENCODED_SIZE*_sstInfos.length; } InfoSubRecord[] getInfoSubRecords() { @@ -174,7 +174,7 @@ public final class ExtSSTRecord extends ContinuableRecord { } public void setBucketOffsets(int[] bucketAbsoluteOffsets, int[] bucketRelativeOffsets) { - // TODO - replace no-arg constructor with this logic + // TODO - replace no-arg constructor with this logic _sstInfos = new InfoSubRecord[bucketAbsoluteOffsets.length]; for (int i = 0; i < bucketAbsoluteOffsets.length; i++) { _sstInfos[i] = new InfoSubRecord(bucketAbsoluteOffsets[i], bucketRelativeOffsets[i]); diff --git a/poi/src/main/java/org/apache/poi/hssf/record/ExtendedFormatRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/ExtendedFormatRecord.java index de42bfd8bf..b5a1d3d94e 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/ExtendedFormatRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/ExtendedFormatRecord.java @@ -1699,7 +1699,7 @@ public final class ExtendedFormatRecord extends StandardRecord { field_9_fill_palette_options = source.field_9_fill_palette_options; } - @Override + @Override public int hashCode() { return Objects.hash( field_1_font_index @@ -1712,30 +1712,30 @@ public final class ExtendedFormatRecord extends StandardRecord { , field_8_adtl_palette_options , field_9_fill_palette_options ); - } + } - /** - * Will consider two different records with the same - * contents as equals, as the various indexes - * that matter are embedded in the records - */ - @Override + /** + * Will consider two different records with the same + * contents as equals, as the various indexes + * that matter are embedded in the records + */ + @Override public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (obj instanceof ExtendedFormatRecord) { - final ExtendedFormatRecord other = (ExtendedFormatRecord) obj; - return Arrays.equals(stateSummary(), other.stateSummary()); - } - return false; - } + if (this == obj) + return true; + if (obj == null) + return false; + if (obj instanceof ExtendedFormatRecord) { + final ExtendedFormatRecord other = (ExtendedFormatRecord) obj; + return Arrays.equals(stateSummary(), other.stateSummary()); + } + return false; + } - public int[] stateSummary() { - return new int[] { field_1_font_index, field_2_format_index, field_3_cell_options, field_4_alignment_options, - field_5_indention_options, field_6_border_options, field_7_palette_options, field_8_adtl_palette_options, field_9_fill_palette_options }; - } + public int[] stateSummary() { + return new int[] { field_1_font_index, field_2_format_index, field_3_cell_options, field_4_alignment_options, + field_5_indention_options, field_6_border_options, field_7_palette_options, field_8_adtl_palette_options, field_9_fill_palette_options }; + } @Override diff --git a/poi/src/main/java/org/apache/poi/hssf/record/ExternSheetRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/ExternSheetRecord.java index 7883f988cf..0c386152b0 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/ExternSheetRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/ExternSheetRecord.java @@ -34,146 +34,146 @@ import org.apache.poi.util.LittleEndianOutput; public class ExternSheetRecord extends StandardRecord { public static final short sid = 0x0017; - private final List _list = new ArrayList<>(); + private final List _list = new ArrayList<>(); - private static final class RefSubRecord implements GenericRecord { - public static final int ENCODED_SIZE = 6; + private static final class RefSubRecord implements GenericRecord { + public static final int ENCODED_SIZE = 6; - /** index to External Book Block (which starts with a EXTERNALBOOK record) */ - private final int _extBookIndex; - private int _firstSheetIndex; // may be -1 (0xFFFF) - private int _lastSheetIndex; // may be -1 (0xFFFF) + /** index to External Book Block (which starts with a EXTERNALBOOK record) */ + private final int _extBookIndex; + private int _firstSheetIndex; // may be -1 (0xFFFF) + private int _lastSheetIndex; // may be -1 (0xFFFF) - public RefSubRecord(int extBookIndex, int firstSheetIndex, int lastSheetIndex) { - _extBookIndex = extBookIndex; - _firstSheetIndex = firstSheetIndex; - _lastSheetIndex = lastSheetIndex; - } + public RefSubRecord(int extBookIndex, int firstSheetIndex, int lastSheetIndex) { + _extBookIndex = extBookIndex; + _firstSheetIndex = firstSheetIndex; + _lastSheetIndex = lastSheetIndex; + } - public RefSubRecord(RefSubRecord other) { - _extBookIndex = other._extBookIndex; - _firstSheetIndex = other._firstSheetIndex; - _lastSheetIndex = other._lastSheetIndex; - } + public RefSubRecord(RefSubRecord other) { + _extBookIndex = other._extBookIndex; + _firstSheetIndex = other._firstSheetIndex; + _lastSheetIndex = other._lastSheetIndex; + } - /** - * @param in the RecordInputstream to read the record from - */ - public RefSubRecord(RecordInputStream in) { - this(in.readShort(), in.readShort(), in.readShort()); - } + /** + * @param in the RecordInputstream to read the record from + */ + public RefSubRecord(RecordInputStream in) { + this(in.readShort(), in.readShort(), in.readShort()); + } - public int getExtBookIndex(){ - return _extBookIndex; - } - public int getFirstSheetIndex(){ - return _firstSheetIndex; - } - public int getLastSheetIndex(){ - return _lastSheetIndex; - } + public int getExtBookIndex(){ + return _extBookIndex; + } + public int getFirstSheetIndex(){ + return _firstSheetIndex; + } + public int getLastSheetIndex(){ + return _lastSheetIndex; + } - @Override - public String toString() { - return GenericRecordJsonWriter.marshal(this); - } + @Override + public String toString() { + return GenericRecordJsonWriter.marshal(this); + } - public void serialize(LittleEndianOutput out) { - out.writeShort(_extBookIndex); - out.writeShort(_firstSheetIndex); - out.writeShort(_lastSheetIndex); - } + public void serialize(LittleEndianOutput out) { + out.writeShort(_extBookIndex); + out.writeShort(_firstSheetIndex); + out.writeShort(_lastSheetIndex); + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "extBookIndex", this::getExtBookIndex, - "firstSheetIndex", this::getFirstSheetIndex, - "lastSheetIndex", this::getLastSheetIndex - ); - } - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "extBookIndex", this::getExtBookIndex, + "firstSheetIndex", this::getFirstSheetIndex, + "lastSheetIndex", this::getLastSheetIndex + ); + } + } - public ExternSheetRecord() {} + public ExternSheetRecord() {} - public ExternSheetRecord(ExternSheetRecord other) { - other._list.stream().map(RefSubRecord::new).forEach(_list::add); - } + public ExternSheetRecord(ExternSheetRecord other) { + other._list.stream().map(RefSubRecord::new).forEach(_list::add); + } - public ExternSheetRecord(RecordInputStream in) { - int nItems = in.readShort(); + public ExternSheetRecord(RecordInputStream in) { + int nItems = in.readShort(); - for (int i = 0 ; i < nItems ; ++i) { - RefSubRecord rec = new RefSubRecord(in); - _list.add(rec); - } - } + for (int i = 0 ; i < nItems ; ++i) { + RefSubRecord rec = new RefSubRecord(in); + _list.add(rec); + } + } - /** - * @return number of REF structures - */ - public int getNumOfRefs() { - return _list.size(); - } + /** + * @return number of REF structures + */ + public int getNumOfRefs() { + return _list.size(); + } - /** - * adds REF struct (ExternSheetSubRecord) - * @param rec REF struct - */ - public void addREFRecord(RefSubRecord rec) { - _list.add(rec); - } + /** + * adds REF struct (ExternSheetSubRecord) + * @param rec REF struct + */ + public void addREFRecord(RefSubRecord rec) { + _list.add(rec); + } - /** returns the number of REF Records, which is in model - * @return number of REF records - */ - public int getNumOfREFRecords() { - return _list.size(); - } + /** returns the number of REF Records, which is in model + * @return number of REF records + */ + public int getNumOfREFRecords() { + return _list.size(); + } - @Override - protected int getDataSize() { - return 2 + _list.size() * RefSubRecord.ENCODED_SIZE; - } + @Override + protected int getDataSize() { + return 2 + _list.size() * RefSubRecord.ENCODED_SIZE; + } - @Override - public void serialize(LittleEndianOutput out) { - int nItems = _list.size(); + @Override + public void serialize(LittleEndianOutput out) { + int nItems = _list.size(); - out.writeShort(nItems); + out.writeShort(nItems); - for (int i = 0; i < nItems; i++) { - getRef(i).serialize(out); - } - } + for (int i = 0; i < nItems; i++) { + getRef(i).serialize(out); + } + } - private RefSubRecord getRef(int i) { - return _list.get(i); - } + private RefSubRecord getRef(int i) { + return _list.get(i); + } - public void removeSheet(int sheetIdx) { + public void removeSheet(int sheetIdx) { int nItems = _list.size(); for (int i = 0; i < nItems; i++) { RefSubRecord refSubRecord = _list.get(i); if(refSubRecord.getFirstSheetIndex() == sheetIdx && refSubRecord.getLastSheetIndex() == sheetIdx) { - // removing the entry would mess up the sheet index in Formula of NameRecord - _list.set(i, new RefSubRecord(refSubRecord.getExtBookIndex(), -1, -1)); + // removing the entry would mess up the sheet index in Formula of NameRecord + _list.set(i, new RefSubRecord(refSubRecord.getExtBookIndex(), -1, -1)); } else if (refSubRecord.getFirstSheetIndex() > sheetIdx && refSubRecord.getLastSheetIndex() > sheetIdx) { _list.set(i, new RefSubRecord(refSubRecord.getExtBookIndex(), refSubRecord.getFirstSheetIndex()-1, refSubRecord.getLastSheetIndex()-1)); } } - } + } - /** - * return the non static version of the id for this record. - */ - @Override - public short getSid() { - return sid; - } + /** + * return the non static version of the id for this record. + */ + @Override + public short getSid() { + return sid; + } /** * @param refIndex specifies the n-th refIndex @@ -185,20 +185,20 @@ public class ExternSheetRecord extends StandardRecord { return refRec.getExtBookIndex(); } - /** - * @param extBookIndex external sheet reference index - * - * @return -1 if not found - */ - public int findRefIndexFromExtBookIndex(int extBookIndex) { - int nItems = _list.size(); - for (int i = 0; i < nItems; i++) { - if (getRef(i).getExtBookIndex() == extBookIndex) { - return i; - } - } - return -1; - } + /** + * @param extBookIndex external sheet reference index + * + * @return -1 if not found + */ + public int findRefIndexFromExtBookIndex(int extBookIndex) { + int nItems = _list.size(); + for (int i = 0; i < nItems; i++) { + if (getRef(i).getExtBookIndex() == extBookIndex) { + return i; + } + } + return -1; + } /** * Returns the first sheet that the reference applies to, or @@ -211,9 +211,9 @@ public class ExternSheetRecord extends StandardRecord { * -1 if the referenced sheet can't be found, or -2 if the * reference is workbook scoped */ - public int getFirstSheetIndexFromRefIndex(int extRefIndex) { - return getRef(extRefIndex).getFirstSheetIndex(); - } + public int getFirstSheetIndexFromRefIndex(int extRefIndex) { + return getRef(extRefIndex).getFirstSheetIndex(); + } /** * Returns the last sheet that the reference applies to, or @@ -232,7 +232,7 @@ public class ExternSheetRecord extends StandardRecord { return getRef(extRefIndex).getLastSheetIndex(); } - /** + /** * Add a zero-based reference to a {@link org.apache.poi.hssf.record.SupBookRecord}. *

* If the type of the SupBook record is same-sheet referencing, Add-In referencing, @@ -259,51 +259,51 @@ public class ExternSheetRecord extends StandardRecord { * @param extBookIndex the external book block index * @param firstSheetIndex the scope, must be -2 for add-in references * @param lastSheetIndex the scope, must be -2 for add-in references - * @return index of newly added ref - */ - public int addRef(int extBookIndex, int firstSheetIndex, int lastSheetIndex) { - _list.add(new RefSubRecord(extBookIndex, firstSheetIndex, lastSheetIndex)); - return _list.size() - 1; - } + * @return index of newly added ref + */ + public int addRef(int extBookIndex, int firstSheetIndex, int lastSheetIndex) { + _list.add(new RefSubRecord(extBookIndex, firstSheetIndex, lastSheetIndex)); + return _list.size() - 1; + } - public int getRefIxForSheet(int externalBookIndex, int firstSheetIndex, int lastSheetIndex) { - int nItems = _list.size(); - for (int i = 0; i < nItems; i++) { - RefSubRecord ref = getRef(i); - if (ref.getExtBookIndex() != externalBookIndex) { - continue; - } - if (ref.getFirstSheetIndex() == firstSheetIndex && - ref.getLastSheetIndex() == lastSheetIndex) { - return i; - } - } - return -1; - } + public int getRefIxForSheet(int externalBookIndex, int firstSheetIndex, int lastSheetIndex) { + int nItems = _list.size(); + for (int i = 0; i < nItems; i++) { + RefSubRecord ref = getRef(i); + if (ref.getExtBookIndex() != externalBookIndex) { + continue; + } + if (ref.getFirstSheetIndex() == firstSheetIndex && + ref.getLastSheetIndex() == lastSheetIndex) { + return i; + } + } + return -1; + } - public static ExternSheetRecord combine(ExternSheetRecord[] esrs) { - ExternSheetRecord result = new ExternSheetRecord(); - for (ExternSheetRecord esr : esrs) { - int nRefs = esr.getNumOfREFRecords(); - for (int j=0; j> getGenericProperties() { - return GenericRecordUtil.getGenericProperties("refrec", () -> _list); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties("refrec", () -> _list); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/ExternalNameRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/ExternalNameRecord.java index 41999c819e..195b0593f6 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/ExternalNameRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/ExternalNameRecord.java @@ -32,150 +32,150 @@ import org.apache.poi.util.StringUtil; */ public final class ExternalNameRecord extends StandardRecord { - public static final short sid = 0x0023; // as per BIFF8. (some old versions used 0x223) + public static final short sid = 0x0023; // as per BIFF8. (some old versions used 0x223) - private static final int OPT_BUILTIN_NAME = 0x0001; - private static final int OPT_AUTOMATIC_LINK = 0x0002; // m$ doc calls this fWantAdvise - private static final int OPT_PICTURE_LINK = 0x0004; - private static final int OPT_STD_DOCUMENT_NAME = 0x0008; //fOle - private static final int OPT_OLE_LINK = 0x0010; //fOleLink -// private static final int OPT_CLIP_FORMAT_MASK = 0x7FE0; - private static final int OPT_ICONIFIED_PICTURE_LINK= 0x8000; + private static final int OPT_BUILTIN_NAME = 0x0001; + private static final int OPT_AUTOMATIC_LINK = 0x0002; // m$ doc calls this fWantAdvise + private static final int OPT_PICTURE_LINK = 0x0004; + private static final int OPT_STD_DOCUMENT_NAME = 0x0008; //fOle + private static final int OPT_OLE_LINK = 0x0010; //fOleLink +// private static final int OPT_CLIP_FORMAT_MASK = 0x7FE0; + private static final int OPT_ICONIFIED_PICTURE_LINK= 0x8000; - private static final int[] OPTION_FLAGS = { - OPT_BUILTIN_NAME,OPT_AUTOMATIC_LINK,OPT_PICTURE_LINK,OPT_STD_DOCUMENT_NAME,OPT_OLE_LINK,OPT_ICONIFIED_PICTURE_LINK}; - private static final String[] OPTION_NAMES = { - "BUILTIN_NAME","AUTOMATIC_LINK","PICTURE_LINK","STD_DOCUMENT_NAME","OLE_LINK","ICONIFIED_PICTURE_LINK"}; + private static final int[] OPTION_FLAGS = { + OPT_BUILTIN_NAME,OPT_AUTOMATIC_LINK,OPT_PICTURE_LINK,OPT_STD_DOCUMENT_NAME,OPT_OLE_LINK,OPT_ICONIFIED_PICTURE_LINK}; + private static final String[] OPTION_NAMES = { + "BUILTIN_NAME","AUTOMATIC_LINK","PICTURE_LINK","STD_DOCUMENT_NAME","OLE_LINK","ICONIFIED_PICTURE_LINK"}; - private short field_1_option_flag; - private short field_2_ixals; - private short field_3_not_used; - private String field_4_name; - private Formula field_5_name_definition; + private short field_1_option_flag; + private short field_2_ixals; + private short field_3_not_used; + private String field_4_name; + private Formula field_5_name_definition; - /** - * 'rgoper' / 'Last received results of the DDE link' - * (seems to be only applicable to DDE links)
- * Logically this is a 2-D array, which has been flattened into 1-D array here. - */ - private Object[] _ddeValues; - /** - * (logical) number of columns in the {@link #_ddeValues} array - */ - private int _nColumns; - /** - * (logical) number of rows in the {@link #_ddeValues} array - */ - private int _nRows; + /** + * 'rgoper' / 'Last received results of the DDE link' + * (seems to be only applicable to DDE links)
+ * Logically this is a 2-D array, which has been flattened into 1-D array here. + */ + private Object[] _ddeValues; + /** + * (logical) number of columns in the {@link #_ddeValues} array + */ + private int _nColumns; + /** + * (logical) number of rows in the {@link #_ddeValues} array + */ + private int _nRows; - public ExternalNameRecord() { - field_2_ixals = 0; - } + public ExternalNameRecord() { + field_2_ixals = 0; + } - public ExternalNameRecord(ExternalNameRecord other) { - super(other); - field_1_option_flag = other.field_1_option_flag; - field_2_ixals = other.field_2_ixals; - field_3_not_used = other.field_3_not_used; - field_4_name = other.field_4_name; - field_5_name_definition = (other.field_5_name_definition == null) ? null : other.field_5_name_definition.copy(); - _ddeValues = (other._ddeValues == null) ? null : other._ddeValues.clone(); - _nColumns = other._nColumns; - _nRows = other._nRows; - } + public ExternalNameRecord(ExternalNameRecord other) { + super(other); + field_1_option_flag = other.field_1_option_flag; + field_2_ixals = other.field_2_ixals; + field_3_not_used = other.field_3_not_used; + field_4_name = other.field_4_name; + field_5_name_definition = (other.field_5_name_definition == null) ? null : other.field_5_name_definition.copy(); + _ddeValues = (other._ddeValues == null) ? null : other._ddeValues.clone(); + _nColumns = other._nColumns; + _nRows = other._nRows; + } - public ExternalNameRecord(RecordInputStream in) { - field_1_option_flag = in.readShort(); - field_2_ixals = in.readShort(); - field_3_not_used = in.readShort(); + public ExternalNameRecord(RecordInputStream in) { + field_1_option_flag = in.readShort(); + field_2_ixals = in.readShort(); + field_3_not_used = in.readShort(); - int numChars = in.readUByte(); - field_4_name = StringUtil.readUnicodeString(in, numChars); + int numChars = in.readUByte(); + field_4_name = StringUtil.readUnicodeString(in, numChars); - // the record body can take different forms. - // The form is dictated by the values of 3-th and 4-th bits in field_1_option_flag - if(!isOLELink() && !isStdDocumentNameIdentifier()){ - // another switch: the fWantAdvise bit specifies whether the body describes - // an external defined name or a DDE data item - if(isAutomaticLink()){ - if(in.available() > 0) { - //body specifies DDE data item - int nColumns = in.readUByte() + 1; - int nRows = in.readShort() + 1; + // the record body can take different forms. + // The form is dictated by the values of 3-th and 4-th bits in field_1_option_flag + if(!isOLELink() && !isStdDocumentNameIdentifier()){ + // another switch: the fWantAdvise bit specifies whether the body describes + // an external defined name or a DDE data item + if(isAutomaticLink()){ + if(in.available() > 0) { + //body specifies DDE data item + int nColumns = in.readUByte() + 1; + int nRows = in.readShort() + 1; - int totalCount = nRows * nColumns; - _ddeValues = ConstantValueParser.parse(in, totalCount); - _nColumns = nColumns; - _nRows = nRows; - } - } else { - //body specifies an external defined name - int formulaLen = in.readUShort(); - field_5_name_definition = Formula.read(formulaLen, in); - } - } - } + int totalCount = nRows * nColumns; + _ddeValues = ConstantValueParser.parse(in, totalCount); + _nColumns = nColumns; + _nRows = nRows; + } + } else { + //body specifies an external defined name + int formulaLen = in.readUShort(); + field_5_name_definition = Formula.read(formulaLen, in); + } + } + } - /** - * @return {@code true} if the name is a built-in name - */ - public boolean isBuiltInName() { - return (field_1_option_flag & OPT_BUILTIN_NAME) != 0; - } - /** - * For OLE and DDE, links can be either 'automatic' or 'manual' - * - * @return {@code true} if this is a automatic link - */ - public boolean isAutomaticLink() { - return (field_1_option_flag & OPT_AUTOMATIC_LINK) != 0; - } - /** - * only for OLE and DDE - * - * @return {@code true} if this is a picture link - */ - public boolean isPicureLink() { - return (field_1_option_flag & OPT_PICTURE_LINK) != 0; - } - /** - * DDE links only. If true, this denotes the 'StdDocumentName' - * - * @return {@code true} if this denotes the 'StdDocumentName' - */ - public boolean isStdDocumentNameIdentifier() { - return (field_1_option_flag & OPT_STD_DOCUMENT_NAME) != 0; - } - public boolean isOLELink() { - return (field_1_option_flag & OPT_OLE_LINK) != 0; - } - public boolean isIconifiedPictureLink() { - return (field_1_option_flag & OPT_ICONIFIED_PICTURE_LINK) != 0; - } - /** - * @return the standard String representation of this name - */ - public String getText() { - return field_4_name; - } + /** + * @return {@code true} if the name is a built-in name + */ + public boolean isBuiltInName() { + return (field_1_option_flag & OPT_BUILTIN_NAME) != 0; + } + /** + * For OLE and DDE, links can be either 'automatic' or 'manual' + * + * @return {@code true} if this is a automatic link + */ + public boolean isAutomaticLink() { + return (field_1_option_flag & OPT_AUTOMATIC_LINK) != 0; + } + /** + * only for OLE and DDE + * + * @return {@code true} if this is a picture link + */ + public boolean isPicureLink() { + return (field_1_option_flag & OPT_PICTURE_LINK) != 0; + } + /** + * DDE links only. If true, this denotes the 'StdDocumentName' + * + * @return {@code true} if this denotes the 'StdDocumentName' + */ + public boolean isStdDocumentNameIdentifier() { + return (field_1_option_flag & OPT_STD_DOCUMENT_NAME) != 0; + } + public boolean isOLELink() { + return (field_1_option_flag & OPT_OLE_LINK) != 0; + } + public boolean isIconifiedPictureLink() { + return (field_1_option_flag & OPT_ICONIFIED_PICTURE_LINK) != 0; + } + /** + * @return the standard String representation of this name + */ + public String getText() { + return field_4_name; + } public void setText(String str) { field_4_name = str; } - /** - * If this is a local name, then this is the (1 based) - * index of the name of the Sheet this refers to, as - * defined in the preceding {@link SupBookRecord}. - * If it isn't a local name, then it must be zero. - * - * @return the index of the name of the Sheet this refers to - */ - public short getIx() { - return field_2_ixals; - } + /** + * If this is a local name, then this is the (1 based) + * index of the name of the Sheet this refers to, as + * defined in the preceding {@link SupBookRecord}. + * If it isn't a local name, then it must be zero. + * + * @return the index of the name of the Sheet this refers to + */ + public short getIx() { + return field_2_ixals; + } public void setIx(short ix) { field_2_ixals = ix; @@ -189,69 +189,69 @@ public final class ExternalNameRecord extends StandardRecord { } - @Override - protected int getDataSize(){ - int result = 2 + 4; // short and int + @Override + protected int getDataSize(){ + int result = 2 + 4; // short and int result += StringUtil.getEncodedSize(field_4_name) - 1; //size is byte, not short if(!isOLELink() && !isStdDocumentNameIdentifier()){ if(isAutomaticLink()){ - if(_ddeValues != null) { + if(_ddeValues != null) { result += 3; // byte, short result += ConstantValueParser.getEncodedSize(_ddeValues); - } + } } else { result += field_5_name_definition.getEncodedSize(); } } - return result; - } + return result; + } - @Override - public void serialize(LittleEndianOutput out) { - out.writeShort(field_1_option_flag); - out.writeShort(field_2_ixals); - out.writeShort(field_3_not_used); + @Override + public void serialize(LittleEndianOutput out) { + out.writeShort(field_1_option_flag); + out.writeShort(field_2_ixals); + out.writeShort(field_3_not_used); - out.writeByte(field_4_name.length()); - StringUtil.writeUnicodeStringFlagAndData(out, field_4_name); + out.writeByte(field_4_name.length()); + StringUtil.writeUnicodeStringFlagAndData(out, field_4_name); if(!isOLELink() && !isStdDocumentNameIdentifier()){ if(isAutomaticLink()){ - if(_ddeValues != null) { + if(_ddeValues != null) { out.writeByte(_nColumns-1); out.writeShort(_nRows-1); ConstantValueParser.encode(out, _ddeValues); - } + } } else { field_5_name_definition.serialize(out); } } - } + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public ExternalNameRecord copy() { - return new ExternalNameRecord(this); - } + @Override + public ExternalNameRecord copy() { + return new ExternalNameRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.EXTERNAL_NAME; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.EXTERNAL_NAME; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "options", GenericRecordUtil.getBitsAsString(() -> field_1_option_flag, OPTION_FLAGS, OPTION_NAMES), - "ix", this::getIx, - "name", this::getText, - "nameDefinition", (field_5_name_definition == null ? () -> null : field_5_name_definition::getTokens) - ); + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "options", GenericRecordUtil.getBitsAsString(() -> field_1_option_flag, OPTION_FLAGS, OPTION_NAMES), + "ix", this::getIx, + "name", this::getText, + "nameDefinition", (field_5_name_definition == null ? () -> null : field_5_name_definition::getTokens) + ); - } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/FeatHdrRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/FeatHdrRecord.java index deb5daaa6a..d758339576 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/FeatHdrRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/FeatHdrRecord.java @@ -33,103 +33,103 @@ import org.apache.poi.util.LittleEndianOutput; * ABNF or worksheet substream ABNF) specifies Shared Feature data. */ public final class FeatHdrRecord extends StandardRecord { - /** - * Specifies the enhanced protection type. Used to protect a - * shared workbook by restricting access to some areas of it - */ - public static final int SHAREDFEATURES_ISFPROTECTION = 0x02; - /** - * Specifies that formula errors should be ignored - */ - public static final int SHAREDFEATURES_ISFFEC2 = 0x03; - /** - * Specifies the smart tag type. Recognises certain - * types of entries (proper names, dates/times etc) and - * flags them for action - */ - public static final int SHAREDFEATURES_ISFFACTOID = 0x04; - /** - * Specifies the shared list type. Used for a table - * within a sheet - */ - public static final int SHAREDFEATURES_ISFLIST = 0x05; + /** + * Specifies the enhanced protection type. Used to protect a + * shared workbook by restricting access to some areas of it + */ + public static final int SHAREDFEATURES_ISFPROTECTION = 0x02; + /** + * Specifies that formula errors should be ignored + */ + public static final int SHAREDFEATURES_ISFFEC2 = 0x03; + /** + * Specifies the smart tag type. Recognises certain + * types of entries (proper names, dates/times etc) and + * flags them for action + */ + public static final int SHAREDFEATURES_ISFFACTOID = 0x04; + /** + * Specifies the shared list type. Used for a table + * within a sheet + */ + public static final int SHAREDFEATURES_ISFLIST = 0x05; - public static final short sid = 0x0867; + public static final short sid = 0x0867; - private final FtrHeader futureHeader; - // See SHAREDFEATURES - private int isf_sharedFeatureType; - // Should always be one - private byte reserved; - /** - * 0x00000000 = rgbHdrData not present - * 0xffffffff = rgbHdrData present - */ - private long cbHdrData; - /** We need a BOFRecord to make sense of this... */ - private byte[] rgbHdrData; + private final FtrHeader futureHeader; + // See SHAREDFEATURES + private int isf_sharedFeatureType; + // Should always be one + private byte reserved; + /** + * 0x00000000 = rgbHdrData not present + * 0xffffffff = rgbHdrData present + */ + private long cbHdrData; + /** We need a BOFRecord to make sense of this... */ + private byte[] rgbHdrData; - public FeatHdrRecord() { - futureHeader = new FtrHeader(); - futureHeader.setRecordType(sid); - } + public FeatHdrRecord() { + futureHeader = new FtrHeader(); + futureHeader.setRecordType(sid); + } - public FeatHdrRecord(FeatHdrRecord other) { - super(other); - futureHeader = other.futureHeader.copy(); - isf_sharedFeatureType = other.isf_sharedFeatureType; - reserved = other.reserved; - cbHdrData = other.cbHdrData; - rgbHdrData = (other.rgbHdrData == null) ? null : other.rgbHdrData.clone(); - } + public FeatHdrRecord(FeatHdrRecord other) { + super(other); + futureHeader = other.futureHeader.copy(); + isf_sharedFeatureType = other.isf_sharedFeatureType; + reserved = other.reserved; + cbHdrData = other.cbHdrData; + rgbHdrData = (other.rgbHdrData == null) ? null : other.rgbHdrData.clone(); + } - public FeatHdrRecord(RecordInputStream in) { - futureHeader = new FtrHeader(in); + public FeatHdrRecord(RecordInputStream in) { + futureHeader = new FtrHeader(in); - isf_sharedFeatureType = in.readShort(); - reserved = in.readByte(); - cbHdrData = in.readInt(); - // Don't process this just yet, need the BOFRecord - rgbHdrData = in.readRemainder(); - } + isf_sharedFeatureType = in.readShort(); + reserved = in.readByte(); + cbHdrData = in.readInt(); + // Don't process this just yet, need the BOFRecord + rgbHdrData = in.readRemainder(); + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - public void serialize(LittleEndianOutput out) { - futureHeader.serialize(out); + public void serialize(LittleEndianOutput out) { + futureHeader.serialize(out); - out.writeShort(isf_sharedFeatureType); - out.writeByte(reserved); - out.writeInt((int)cbHdrData); - out.write(rgbHdrData); - } + out.writeShort(isf_sharedFeatureType); + out.writeByte(reserved); + out.writeInt((int)cbHdrData); + out.write(rgbHdrData); + } - protected int getDataSize() { - return 12 + 2+1+4+rgbHdrData.length; - } + protected int getDataSize() { + return 12 + 2+1+4+rgbHdrData.length; + } - @Override + @Override public FeatHdrRecord copy() { - //HACK: do a "cheat" clone, see Record.java for more information + //HACK: do a "cheat" clone, see Record.java for more information return new FeatHdrRecord(this); } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.FEAT_HDR; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.FEAT_HDR; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "futureHeader", () -> futureHeader, - "isf_sharedFeatureType", () -> isf_sharedFeatureType, - "reserved", () -> reserved, - "cbHdrData", () -> cbHdrData, - "rgbHdrData", () -> rgbHdrData - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "futureHeader", () -> futureHeader, + "isf_sharedFeatureType", () -> isf_sharedFeatureType, + "reserved", () -> reserved, + "cbHdrData", () -> cbHdrData, + "rgbHdrData", () -> rgbHdrData + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/FeatRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/FeatRecord.java index f5850bfefa..a434658ba4 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/FeatRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/FeatRecord.java @@ -42,167 +42,167 @@ import static org.apache.logging.log4j.util.Unbox.box; */ public final class FeatRecord extends StandardRecord { private static final Logger LOG = LogManager.getLogger(FeatRecord.class); - public static final short sid = 0x0868; + public static final short sid = 0x0868; // SIDs from newer versions public static final short v11_sid = 0x0872; public static final short v12_sid = 0x0878; - private final FtrHeader futureHeader; + private final FtrHeader futureHeader; - /** See SHAREDFEATURES_* on {@link FeatHdrRecord} */ - private int isf_sharedFeatureType; - private byte reserved1; // Should always be zero - private long reserved2; // Should always be zero - /** Only matters if type is ISFFEC2 */ - private long cbFeatData; - private int reserved3; // Should always be zero - private CellRangeAddress[] cellRefs; + /** See SHAREDFEATURES_* on {@link FeatHdrRecord} */ + private int isf_sharedFeatureType; + private byte reserved1; // Should always be zero + private long reserved2; // Should always be zero + /** Only matters if type is ISFFEC2 */ + private long cbFeatData; + private int reserved3; // Should always be zero + private CellRangeAddress[] cellRefs; - /** - * Contents depends on isf_sharedFeatureType : - * ISFPROTECTION -> FeatProtection - * ISFFEC2 -> FeatFormulaErr2 - * ISFFACTOID -> FeatSmartTag - */ - private SharedFeature sharedFeature; + /** + * Contents depends on isf_sharedFeatureType : + * ISFPROTECTION -> FeatProtection + * ISFFEC2 -> FeatFormulaErr2 + * ISFFACTOID -> FeatSmartTag + */ + private SharedFeature sharedFeature; - public FeatRecord() { - futureHeader = new FtrHeader(); - futureHeader.setRecordType(sid); - } + public FeatRecord() { + futureHeader = new FtrHeader(); + futureHeader.setRecordType(sid); + } - public FeatRecord(FeatRecord other) { - super(other); - futureHeader = other.futureHeader.copy(); - isf_sharedFeatureType = other.isf_sharedFeatureType; - reserved1 = other.reserved1; - reserved2 = other.reserved2; - cbFeatData = other.cbFeatData; - reserved3 = other.reserved3; - cellRefs = (other.cellRefs == null) ? null : - Stream.of(other.cellRefs).map(CellRangeAddress::copy).toArray(CellRangeAddress[]::new); - sharedFeature = (other.sharedFeature == null) ? null : other.sharedFeature.copy(); - } + public FeatRecord(FeatRecord other) { + super(other); + futureHeader = other.futureHeader.copy(); + isf_sharedFeatureType = other.isf_sharedFeatureType; + reserved1 = other.reserved1; + reserved2 = other.reserved2; + cbFeatData = other.cbFeatData; + reserved3 = other.reserved3; + cellRefs = (other.cellRefs == null) ? null : + Stream.of(other.cellRefs).map(CellRangeAddress::copy).toArray(CellRangeAddress[]::new); + sharedFeature = (other.sharedFeature == null) ? null : other.sharedFeature.copy(); + } - public FeatRecord(RecordInputStream in) { - futureHeader = new FtrHeader(in); + public FeatRecord(RecordInputStream in) { + futureHeader = new FtrHeader(in); - isf_sharedFeatureType = in.readShort(); - reserved1 = in.readByte(); - reserved2 = in.readInt(); - int cref = in.readUShort(); - cbFeatData = in.readInt(); - reserved3 = in.readShort(); + isf_sharedFeatureType = in.readShort(); + reserved1 = in.readByte(); + reserved2 = in.readInt(); + int cref = in.readUShort(); + cbFeatData = in.readInt(); + reserved3 = in.readShort(); - cellRefs = new CellRangeAddress[cref]; - for(int i=0; i> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "futureHeader", () -> futureHeader, - "isf_sharedFeatureType", this::getIsf_sharedFeatureType, - "reserved1", () -> reserved1, - "reserved2", () -> reserved2, - "cbFeatData", this::getCbFeatData, - "reserved3", () -> reserved3, - "cellRefs", this::getCellRefs, - "sharedFeature", this::getSharedFeature - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "futureHeader", () -> futureHeader, + "isf_sharedFeatureType", this::getIsf_sharedFeatureType, + "reserved1", () -> reserved1, + "reserved2", () -> reserved2, + "cbFeatData", this::getCbFeatData, + "reserved3", () -> reserved3, + "cellRefs", this::getCellRefs, + "sharedFeature", this::getSharedFeature + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java index cbb73a65e4..833310d495 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/FilePassRecord.java @@ -42,28 +42,28 @@ import org.apache.poi.util.LittleEndianOutputStream; * Indicates that the record after this record are encrypted. */ public final class FilePassRecord extends StandardRecord { - public static final short sid = 0x002F; + public static final short sid = 0x002F; private static final int ENCRYPTION_XOR = 0; private static final int ENCRYPTION_OTHER = 1; - private final int encryptionType; + private final int encryptionType; private final EncryptionInfo encryptionInfo; - private FilePassRecord(FilePassRecord other) { + private FilePassRecord(FilePassRecord other) { super(other); - encryptionType = other.encryptionType; + encryptionType = other.encryptionType; encryptionInfo = other.encryptionInfo.copy(); - } + } - public FilePassRecord(EncryptionMode encryptionMode) { - encryptionType = (encryptionMode == EncryptionMode.xor) ? ENCRYPTION_XOR : ENCRYPTION_OTHER; - encryptionInfo = new EncryptionInfo(encryptionMode); - } + public FilePassRecord(EncryptionMode encryptionMode) { + encryptionType = (encryptionMode == EncryptionMode.xor) ? ENCRYPTION_XOR : ENCRYPTION_OTHER; + encryptionInfo = new EncryptionInfo(encryptionMode); + } - public FilePassRecord(RecordInputStream in) { - encryptionType = in.readUShort(); + public FilePassRecord(RecordInputStream in) { + encryptionType = in.readUShort(); - EncryptionMode preferredMode; + EncryptionMode preferredMode; switch (encryptionType) { case ENCRYPTION_XOR: preferredMode = EncryptionMode.xor; @@ -75,14 +75,14 @@ public final class FilePassRecord extends StandardRecord { throw new EncryptedDocumentException("invalid encryption type"); } - try { + try { encryptionInfo = new EncryptionInfo(in, preferredMode); } catch (IOException e) { throw new EncryptedDocumentException(e); } - } + } - @SuppressWarnings("resource") + @SuppressWarnings("resource") @Override public void serialize(LittleEndianOutput out) { out.writeShort(encryptionType); @@ -118,29 +118,29 @@ public final class FilePassRecord extends StandardRecord { // should never happen in practice throw new IllegalStateException(ioe); } - } + } - @Override + @Override protected int getDataSize() { - UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); - LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); + UnsynchronizedByteArrayOutputStream bos = new UnsynchronizedByteArrayOutputStream(); + LittleEndianOutputStream leos = new LittleEndianOutputStream(bos); serialize(leos); return bos.size(); - } + } - public EncryptionInfo getEncryptionInfo() { + public EncryptionInfo getEncryptionInfo() { return encryptionInfo; } @Override public short getSid() { - return sid; - } + return sid; + } @Override - public FilePassRecord copy() { - return new FilePassRecord(this); - } + public FilePassRecord copy() { + return new FilePassRecord(this); + } @Override public HSSFRecordTypes getGenericRecordType() { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/FileSharingRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/FileSharingRecord.java index 4249e72a83..a2aee4b43b 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/FileSharingRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/FileSharingRecord.java @@ -115,7 +115,7 @@ public final class FileSharingRecord extends StandardRecord { out.writeShort(getPassword()); out.writeShort(field_3_username_value.length()); if(field_3_username_value.length() > 0) { - out.writeByte(field_3_username_unicode_options); + out.writeByte(field_3_username_unicode_options); StringUtil.putCompressedUnicode(getUsername(), out); } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/FontRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/FontRecord.java index aedb462a4e..77ddcf4b25 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/FontRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/FontRecord.java @@ -29,489 +29,489 @@ import org.apache.poi.util.StringUtil; /** Describes a font in the workbook */ public final class FontRecord extends StandardRecord { - // docs are wrong (0x231 Microsoft Support site article Q184647) - public static final short sid = 0x0031; - public static final short SS_NONE = 0; - public static final short SS_SUPER = 1; - public static final short SS_SUB = 2; - public static final byte U_NONE = 0; - public static final byte U_SINGLE = 1; - public static final byte U_DOUBLE = 2; - public static final byte U_SINGLE_ACCOUNTING = 0x21; - public static final byte U_DOUBLE_ACCOUNTING = 0x22; + // docs are wrong (0x231 Microsoft Support site article Q184647) + public static final short sid = 0x0031; + public static final short SS_NONE = 0; + public static final short SS_SUPER = 1; + public static final short SS_SUB = 2; + public static final byte U_NONE = 0; + public static final byte U_SINGLE = 1; + public static final byte U_DOUBLE = 2; + public static final byte U_SINGLE_ACCOUNTING = 0x21; + public static final byte U_DOUBLE_ACCOUNTING = 0x22; - // 0 0x01 - Reserved bit must be 0 - // is this font in italics - private static final BitField italic = BitFieldFactory.getInstance(0x02); + // 0 0x01 - Reserved bit must be 0 + // is this font in italics + private static final BitField italic = BitFieldFactory.getInstance(0x02); - // 2 0x04 - reserved bit must be 0 - // is this font has a line through the center - private static final BitField strikeout = BitFieldFactory.getInstance(0x08); - // some weird macintosh thing....but who understands those mac people anyhow - private static final BitField macoutline = BitFieldFactory.getInstance(0x10); - private static final BitField macshadow = BitFieldFactory.getInstance(0x20); + // 2 0x04 - reserved bit must be 0 + // is this font has a line through the center + private static final BitField strikeout = BitFieldFactory.getInstance(0x08); + // some weird macintosh thing....but who understands those mac people anyhow + private static final BitField macoutline = BitFieldFactory.getInstance(0x10); + private static final BitField macshadow = BitFieldFactory.getInstance(0x20); - // in units of .05 of a point - private short field_1_font_height; - private short field_2_attributes; + // in units of .05 of a point + private short field_1_font_height; + private short field_2_attributes; - // 7-6 - reserved bits must be 0 - // the rest is unused - private short field_3_color_palette_index; - private short field_4_bold_weight; - // 00none/01super/02sub - private short field_5_super_sub_script; - // 00none/01single/02double/21singleaccounting/22doubleaccounting - private byte field_6_underline; - // ?? defined by windows api logfont structure? - private byte field_7_family; - // ?? defined by windows api logfont structure? - private byte field_8_charset; - // must be 0 - private byte field_9_zero; - /** possibly empty string never null */ - private String field_11_font_name; + // 7-6 - reserved bits must be 0 + // the rest is unused + private short field_3_color_palette_index; + private short field_4_bold_weight; + // 00none/01super/02sub + private short field_5_super_sub_script; + // 00none/01single/02double/21singleaccounting/22doubleaccounting + private byte field_6_underline; + // ?? defined by windows api logfont structure? + private byte field_7_family; + // ?? defined by windows api logfont structure? + private byte field_8_charset; + // must be 0 + private byte field_9_zero; + /** possibly empty string never null */ + private String field_11_font_name; - public FontRecord() { - } + public FontRecord() { + } - public FontRecord(FontRecord other) { - super(other); - field_1_font_height = other.field_1_font_height; - field_2_attributes = other.field_2_attributes; - field_3_color_palette_index = other.field_3_color_palette_index; - field_4_bold_weight = other.field_4_bold_weight; - field_5_super_sub_script = other.field_5_super_sub_script; - field_6_underline = other.field_6_underline; - field_7_family = other.field_7_family; - field_8_charset = other.field_8_charset; - field_9_zero = other.field_9_zero; - field_11_font_name = other.field_11_font_name; - } + public FontRecord(FontRecord other) { + super(other); + field_1_font_height = other.field_1_font_height; + field_2_attributes = other.field_2_attributes; + field_3_color_palette_index = other.field_3_color_palette_index; + field_4_bold_weight = other.field_4_bold_weight; + field_5_super_sub_script = other.field_5_super_sub_script; + field_6_underline = other.field_6_underline; + field_7_family = other.field_7_family; + field_8_charset = other.field_8_charset; + field_9_zero = other.field_9_zero; + field_11_font_name = other.field_11_font_name; + } - public FontRecord(RecordInputStream in) { - field_1_font_height = in.readShort(); - field_2_attributes = in.readShort(); - field_3_color_palette_index = in.readShort(); - field_4_bold_weight = in.readShort(); - field_5_super_sub_script = in.readShort(); - field_6_underline = in.readByte(); - field_7_family = in.readByte(); - field_8_charset = in.readByte(); - field_9_zero = in.readByte(); - int field_10_font_name_len = in.readUByte(); - int unicodeFlags = in.readUByte(); // options byte present always (even if no character data) + public FontRecord(RecordInputStream in) { + field_1_font_height = in.readShort(); + field_2_attributes = in.readShort(); + field_3_color_palette_index = in.readShort(); + field_4_bold_weight = in.readShort(); + field_5_super_sub_script = in.readShort(); + field_6_underline = in.readByte(); + field_7_family = in.readByte(); + field_8_charset = in.readByte(); + field_9_zero = in.readByte(); + int field_10_font_name_len = in.readUByte(); + int unicodeFlags = in.readUByte(); // options byte present always (even if no character data) - if (field_10_font_name_len > 0) { - if (unicodeFlags == 0) { // is compressed unicode - field_11_font_name = in.readCompressedUnicode(field_10_font_name_len); - } else { // is not compressed unicode - field_11_font_name = in.readUnicodeLEString(field_10_font_name_len); - } - } else { - field_11_font_name = ""; - } - } + if (field_10_font_name_len > 0) { + if (unicodeFlags == 0) { // is compressed unicode + field_11_font_name = in.readCompressedUnicode(field_10_font_name_len); + } else { // is not compressed unicode + field_11_font_name = in.readUnicodeLEString(field_10_font_name_len); + } + } else { + field_11_font_name = ""; + } + } - /** - * sets the height of the font in 1/20th point units - * - * @param height fontheight (in points/20) - */ - public void setFontHeight(short height) { - field_1_font_height = height; - } + /** + * sets the height of the font in 1/20th point units + * + * @param height fontheight (in points/20) + */ + public void setFontHeight(short height) { + field_1_font_height = height; + } - /** - * set the font attributes (see individual bit setters that reference this method) - * - * @param attributes the bitmask to set - */ - public void setAttributes(short attributes) { - field_2_attributes = attributes; - } + /** + * set the font attributes (see individual bit setters that reference this method) + * + * @param attributes the bitmask to set + */ + public void setAttributes(short attributes) { + field_2_attributes = attributes; + } - // attributes bitfields + // attributes bitfields - /** - * set the font to be italics or not - * - * @param italics - whether the font is italics or not - * @see #setAttributes(short) - */ - public void setItalic(boolean italics) { - field_2_attributes = italic.setShortBoolean(field_2_attributes, italics); - } + /** + * set the font to be italics or not + * + * @param italics - whether the font is italics or not + * @see #setAttributes(short) + */ + public void setItalic(boolean italics) { + field_2_attributes = italic.setShortBoolean(field_2_attributes, italics); + } - /** - * set the font to be stricken out or not - * - * @param strike - whether the font is stricken out or not - * @see #setAttributes(short) - */ - public void setStrikeout(boolean strike) { - field_2_attributes = strikeout.setShortBoolean(field_2_attributes, strike); - } + /** + * set the font to be stricken out or not + * + * @param strike - whether the font is stricken out or not + * @see #setAttributes(short) + */ + public void setStrikeout(boolean strike) { + field_2_attributes = strikeout.setShortBoolean(field_2_attributes, strike); + } - /** - * whether to use the mac outline font style thing (mac only) - Some mac person - * should comment this instead of me doing it (since I have no idea) - * - * @param mac - whether to do that mac font outline thing or not - * @see #setAttributes(short) - */ - public void setMacoutline(boolean mac) { - field_2_attributes = macoutline.setShortBoolean(field_2_attributes, mac); - } + /** + * whether to use the mac outline font style thing (mac only) - Some mac person + * should comment this instead of me doing it (since I have no idea) + * + * @param mac - whether to do that mac font outline thing or not + * @see #setAttributes(short) + */ + public void setMacoutline(boolean mac) { + field_2_attributes = macoutline.setShortBoolean(field_2_attributes, mac); + } - /** - * whether to use the mac shado font style thing (mac only) - Some mac person - * should comment this instead of me doing it (since I have no idea) - * - * @param mac - whether to do that mac font shadow thing or not - * @see #setAttributes(short) - */ - public void setMacshadow(boolean mac) { - field_2_attributes = macshadow.setShortBoolean(field_2_attributes, mac); - } + /** + * whether to use the mac shado font style thing (mac only) - Some mac person + * should comment this instead of me doing it (since I have no idea) + * + * @param mac - whether to do that mac font shadow thing or not + * @see #setAttributes(short) + */ + public void setMacshadow(boolean mac) { + field_2_attributes = macshadow.setShortBoolean(field_2_attributes, mac); + } - /** - * set the font's color palette index - * - * @param cpi - font color index - */ - public void setColorPaletteIndex(short cpi) { - field_3_color_palette_index = cpi; - } + /** + * set the font's color palette index + * + * @param cpi - font color index + */ + public void setColorPaletteIndex(short cpi) { + field_3_color_palette_index = cpi; + } - /** - * set the bold weight for this font (100-1000dec or 0x64-0x3e8). Default is - * 0x190 for normal and 0x2bc for bold - * - * @param bw - a number between 100-1000 for the fonts "boldness" - */ - public void setBoldWeight(short bw) { - field_4_bold_weight = bw; - } + /** + * set the bold weight for this font (100-1000dec or 0x64-0x3e8). Default is + * 0x190 for normal and 0x2bc for bold + * + * @param bw - a number between 100-1000 for the fonts "boldness" + */ + public void setBoldWeight(short bw) { + field_4_bold_weight = bw; + } - /** - * set the type of super or subscript for the font - * - * @param sss super or subscript option - * @see #SS_NONE - * @see #SS_SUPER - * @see #SS_SUB - */ - public void setSuperSubScript(short sss) { - field_5_super_sub_script = sss; - } + /** + * set the type of super or subscript for the font + * + * @param sss super or subscript option + * @see #SS_NONE + * @see #SS_SUPER + * @see #SS_SUB + */ + public void setSuperSubScript(short sss) { + field_5_super_sub_script = sss; + } - /** - * set the type of underlining for the font - * - * @param u super or subscript option - * - * @see #U_NONE - * @see #U_SINGLE - * @see #U_DOUBLE - * @see #U_SINGLE_ACCOUNTING - * @see #U_DOUBLE_ACCOUNTING - */ - public void setUnderline(byte u) { - field_6_underline = u; - } + /** + * set the type of underlining for the font + * + * @param u super or subscript option + * + * @see #U_NONE + * @see #U_SINGLE + * @see #U_DOUBLE + * @see #U_SINGLE_ACCOUNTING + * @see #U_DOUBLE_ACCOUNTING + */ + public void setUnderline(byte u) { + field_6_underline = u; + } - /** - * set the font family (TODO) - * - * @param f family - */ - public void setFamily(byte f) { - field_7_family = f; - } + /** + * set the font family (TODO) + * + * @param f family + */ + public void setFamily(byte f) { + field_7_family = f; + } - /** - * set the character set - * - * @param charset - character set - */ - public void setCharset(byte charset) { - field_8_charset = charset; - } + /** + * set the character set + * + * @param charset - character set + */ + public void setCharset(byte charset) { + field_8_charset = charset; + } - /** - * set the name of the font - * - * @param fn - name of the font (i.e. "Arial") - */ - public void setFontName(String fn) { - field_11_font_name = fn; - } + /** + * set the name of the font + * + * @param fn - name of the font (i.e. "Arial") + */ + public void setFontName(String fn) { + field_11_font_name = fn; + } - /** - * gets the height of the font in 1/20th point units - * - * @return fontheight (in points/20) - */ - public short getFontHeight() { - return field_1_font_height; - } + /** + * gets the height of the font in 1/20th point units + * + * @return fontheight (in points/20) + */ + public short getFontHeight() { + return field_1_font_height; + } - /** - * get the font attributes (see individual bit getters that reference this method) - * - * @return attribute - the bitmask - */ - public short getAttributes() { - return field_2_attributes; - } + /** + * get the font attributes (see individual bit getters that reference this method) + * + * @return attribute - the bitmask + */ + public short getAttributes() { + return field_2_attributes; + } - /** - * get whether the font is to be italics or not - * - * @return italics - whether the font is italics or not - * @see #getAttributes() - */ - public boolean isItalic() { - return italic.isSet(field_2_attributes); - } + /** + * get whether the font is to be italics or not + * + * @return italics - whether the font is italics or not + * @see #getAttributes() + */ + public boolean isItalic() { + return italic.isSet(field_2_attributes); + } - /** - * get whether the font is to be stricken out or not - * - * @return strike - whether the font is stricken out or not - * @see #getAttributes() - */ - public boolean isStruckout(){ - return strikeout.isSet(field_2_attributes); - } + /** + * get whether the font is to be stricken out or not + * + * @return strike - whether the font is stricken out or not + * @see #getAttributes() + */ + public boolean isStruckout(){ + return strikeout.isSet(field_2_attributes); + } - /** - * whether to use the mac outline font style thing (mac only) - Some mac person - * should comment this instead of me doing it (since I have no idea) - * - * @return mac - whether to do that mac font outline thing or not - * @see #getAttributes() - */ - public boolean isMacoutlined(){ - return macoutline.isSet(field_2_attributes); - } + /** + * whether to use the mac outline font style thing (mac only) - Some mac person + * should comment this instead of me doing it (since I have no idea) + * + * @return mac - whether to do that mac font outline thing or not + * @see #getAttributes() + */ + public boolean isMacoutlined(){ + return macoutline.isSet(field_2_attributes); + } - /** - * whether to use the mac shado font style thing (mac only) - Some mac person - * should comment this instead of me doing it (since I have no idea) - * - * @return mac - whether to do that mac font shadow thing or not - * @see #getAttributes() - */ - public boolean isMacshadowed(){ - return macshadow.isSet(field_2_attributes); - } + /** + * whether to use the mac shado font style thing (mac only) - Some mac person + * should comment this instead of me doing it (since I have no idea) + * + * @return mac - whether to do that mac font shadow thing or not + * @see #getAttributes() + */ + public boolean isMacshadowed(){ + return macshadow.isSet(field_2_attributes); + } - /** - * get the font's color palette index - * - * @return cpi - font color index - */ - public short getColorPaletteIndex(){ - return field_3_color_palette_index; - } + /** + * get the font's color palette index + * + * @return cpi - font color index + */ + public short getColorPaletteIndex(){ + return field_3_color_palette_index; + } - /** - * get the bold weight for this font (100-1000dec or 0x64-0x3e8). Default is - * 0x190 for normal and 0x2bc for bold - * - * @return bw - a number between 100-1000 for the fonts "boldness" - */ - public short getBoldWeight(){ - return field_4_bold_weight; - } + /** + * get the bold weight for this font (100-1000dec or 0x64-0x3e8). Default is + * 0x190 for normal and 0x2bc for bold + * + * @return bw - a number between 100-1000 for the fonts "boldness" + */ + public short getBoldWeight(){ + return field_4_bold_weight; + } - /** - * get the type of super or subscript for the font - * - * @return super or subscript option - * @see #SS_NONE - * @see #SS_SUPER - * @see #SS_SUB - */ - public short getSuperSubScript(){ - return field_5_super_sub_script; - } + /** + * get the type of super or subscript for the font + * + * @return super or subscript option + * @see #SS_NONE + * @see #SS_SUPER + * @see #SS_SUB + */ + public short getSuperSubScript(){ + return field_5_super_sub_script; + } - /** - * get the type of underlining for the font - * - * @return super or subscript option - * - * @see #U_NONE - * @see #U_SINGLE - * @see #U_DOUBLE - * @see #U_SINGLE_ACCOUNTING - * @see #U_DOUBLE_ACCOUNTING - */ - public byte getUnderline() { - return field_6_underline; - } + /** + * get the type of underlining for the font + * + * @return super or subscript option + * + * @see #U_NONE + * @see #U_SINGLE + * @see #U_DOUBLE + * @see #U_SINGLE_ACCOUNTING + * @see #U_DOUBLE_ACCOUNTING + */ + public byte getUnderline() { + return field_6_underline; + } - /** - * get the font family (TODO) - * - * @return family - */ - public byte getFamily() { - return field_7_family; - } + /** + * get the font family (TODO) + * + * @return family + */ + public byte getFamily() { + return field_7_family; + } - /** - * get the character set - * - * @return charset - character set - */ - public byte getCharset() { - return field_8_charset; - } + /** + * get the character set + * + * @return charset - character set + */ + public byte getCharset() { + return field_8_charset; + } - /** - * get the name of the font - * - * @return fn - name of the font (i.e. "Arial") - */ - public String getFontName() { - return field_11_font_name; - } + /** + * get the name of the font + * + * @return fn - name of the font (i.e. "Arial") + */ + public String getFontName() { + return field_11_font_name; + } - public void serialize(LittleEndianOutput out) { + public void serialize(LittleEndianOutput out) { - out.writeShort(getFontHeight()); - out.writeShort(getAttributes()); - out.writeShort(getColorPaletteIndex()); - out.writeShort(getBoldWeight()); - out.writeShort(getSuperSubScript()); - out.writeByte(getUnderline()); - out.writeByte(getFamily()); - out.writeByte(getCharset()); - out.writeByte(field_9_zero); - int fontNameLen = field_11_font_name.length(); - out.writeByte(fontNameLen); - boolean hasMultibyte = StringUtil.hasMultibyte(field_11_font_name); - out.writeByte(hasMultibyte ? 0x01 : 0x00); - if (fontNameLen > 0) { - if (hasMultibyte) { - StringUtil.putUnicodeLE(field_11_font_name, out); - } else { - StringUtil.putCompressedUnicode(field_11_font_name, out); - } - } - } - protected int getDataSize() { - int size = 16; // 5 shorts + 6 bytes - int fontNameLen = field_11_font_name.length(); - if (fontNameLen < 1) { - return size; - } + out.writeShort(getFontHeight()); + out.writeShort(getAttributes()); + out.writeShort(getColorPaletteIndex()); + out.writeShort(getBoldWeight()); + out.writeShort(getSuperSubScript()); + out.writeByte(getUnderline()); + out.writeByte(getFamily()); + out.writeByte(getCharset()); + out.writeByte(field_9_zero); + int fontNameLen = field_11_font_name.length(); + out.writeByte(fontNameLen); + boolean hasMultibyte = StringUtil.hasMultibyte(field_11_font_name); + out.writeByte(hasMultibyte ? 0x01 : 0x00); + if (fontNameLen > 0) { + if (hasMultibyte) { + StringUtil.putUnicodeLE(field_11_font_name, out); + } else { + StringUtil.putCompressedUnicode(field_11_font_name, out); + } + } + } + protected int getDataSize() { + int size = 16; // 5 shorts + 6 bytes + int fontNameLen = field_11_font_name.length(); + if (fontNameLen < 1) { + return size; + } - boolean hasMultibyte = StringUtil.hasMultibyte(field_11_font_name); - return size + fontNameLen * (hasMultibyte ? 2 : 1); - } + boolean hasMultibyte = StringUtil.hasMultibyte(field_11_font_name); + return size + fontNameLen * (hasMultibyte ? 2 : 1); + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - /** - * Clones all the font style information from another - * FontRecord, onto this one. This - * will then hold all the same font style options. - * - * @param source the record to clone the properties from - */ - public void cloneStyleFrom(FontRecord source) { - field_1_font_height = source.field_1_font_height; - field_2_attributes = source.field_2_attributes; - field_3_color_palette_index = source.field_3_color_palette_index; - field_4_bold_weight = source.field_4_bold_weight; - field_5_super_sub_script = source.field_5_super_sub_script; - field_6_underline = source.field_6_underline; - field_7_family = source.field_7_family; - field_8_charset = source.field_8_charset; - field_9_zero = source.field_9_zero; - field_11_font_name = source.field_11_font_name; - } + /** + * Clones all the font style information from another + * FontRecord, onto this one. This + * will then hold all the same font style options. + * + * @param source the record to clone the properties from + */ + public void cloneStyleFrom(FontRecord source) { + field_1_font_height = source.field_1_font_height; + field_2_attributes = source.field_2_attributes; + field_3_color_palette_index = source.field_3_color_palette_index; + field_4_bold_weight = source.field_4_bold_weight; + field_5_super_sub_script = source.field_5_super_sub_script; + field_6_underline = source.field_6_underline; + field_7_family = source.field_7_family; + field_8_charset = source.field_8_charset; + field_9_zero = source.field_9_zero; + field_11_font_name = source.field_11_font_name; + } - public int hashCode() { - return Objects.hash( - field_1_font_height - , field_2_attributes - , field_3_color_palette_index - , field_4_bold_weight - , field_5_super_sub_script - , field_6_underline - , field_7_family - , field_8_charset - , field_9_zero - , field_11_font_name - ); - } + public int hashCode() { + return Objects.hash( + field_1_font_height + , field_2_attributes + , field_3_color_palette_index + , field_4_bold_weight + , field_5_super_sub_script + , field_6_underline + , field_7_family + , field_8_charset + , field_9_zero + , field_11_font_name + ); + } - /** - * Does this FontRecord have all the same font - * properties as the supplied FontRecord? - * Note that {@link #equals(Object)} will check - * for exact objects, while this will check - * for exact contents, because normally the - * font record's position makes a big - * difference too. - * - * @param other the record to compare with - * - * @return true, if the properties match - */ - public boolean sameProperties(FontRecord other) { + /** + * Does this FontRecord have all the same font + * properties as the supplied FontRecord? + * Note that {@link #equals(Object)} will check + * for exact objects, while this will check + * for exact contents, because normally the + * font record's position makes a big + * difference too. + * + * @param other the record to compare with + * + * @return true, if the properties match + */ + public boolean sameProperties(FontRecord other) { - return - field_1_font_height == other.field_1_font_height && - field_2_attributes == other.field_2_attributes && - field_3_color_palette_index == other.field_3_color_palette_index && - field_4_bold_weight == other.field_4_bold_weight && - field_5_super_sub_script == other.field_5_super_sub_script && - field_6_underline == other.field_6_underline && - field_7_family == other.field_7_family && - field_8_charset == other.field_8_charset && - field_9_zero == other.field_9_zero && - Objects.equals(this.field_11_font_name, other.field_11_font_name) - ; - } + return + field_1_font_height == other.field_1_font_height && + field_2_attributes == other.field_2_attributes && + field_3_color_palette_index == other.field_3_color_palette_index && + field_4_bold_weight == other.field_4_bold_weight && + field_5_super_sub_script == other.field_5_super_sub_script && + field_6_underline == other.field_6_underline && + field_7_family == other.field_7_family && + field_8_charset == other.field_8_charset && + field_9_zero == other.field_9_zero && + Objects.equals(this.field_11_font_name, other.field_11_font_name) + ; + } public boolean equals(Object o) { return (o instanceof FontRecord) && sameProperties((FontRecord) o); } - @Override - public FontRecord copy() { - return new FontRecord(this); - } + @Override + public FontRecord copy() { + return new FontRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.FONT; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.FONT; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "fontHeight", this::getFontHeight, - "attributes", GenericRecordUtil.getBitsAsString(this::getAttributes, - new BitField[]{italic,strikeout,macoutline,macshadow}, - new String[]{"ITALIC","STRIKEOUT","MACOUTLINE","MACSHADOW"}), - "colorPalette", this::getColorPaletteIndex, - "boldWeight", this::getBoldWeight, - "superSubScript", this::getSuperSubScript, - "underline", this::getUnderline, - "family", this::getFamily, - "charset", this::getCharset, - "fontName", this::getFontName - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "fontHeight", this::getFontHeight, + "attributes", GenericRecordUtil.getBitsAsString(this::getAttributes, + new BitField[]{italic,strikeout,macoutline,macshadow}, + new String[]{"ITALIC","STRIKEOUT","MACOUTLINE","MACSHADOW"}), + "colorPalette", this::getColorPaletteIndex, + "boldWeight", this::getBoldWeight, + "superSubScript", this::getSuperSubScript, + "underline", this::getUnderline, + "family", this::getFamily, + "charset", this::getCharset, + "fontName", this::getFontName + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/FooterRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/FooterRecord.java index 5aee71d1c8..97b7b5d082 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/FooterRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/FooterRecord.java @@ -21,31 +21,31 @@ package org.apache.poi.hssf.record; * Specifies the footer for a sheet */ public final class FooterRecord extends HeaderFooterBase { - public static final short sid = 0x0015; + public static final short sid = 0x0015; - public FooterRecord(String text) { - super(text); - } + public FooterRecord(String text) { + super(text); + } - public FooterRecord(FooterRecord other) { - super(other); - } + public FooterRecord(FooterRecord other) { + super(other); + } - public FooterRecord(RecordInputStream in) { - super(in); - } + public FooterRecord(RecordInputStream in) { + super(in); + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - @Override - public FooterRecord copy() { - return new FooterRecord(this); - } + @Override + public FooterRecord copy() { + return new FooterRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.FOOTER; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.FOOTER; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/FormulaRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/FormulaRecord.java index 0b702b0128..e42dcb6a6b 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/FormulaRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/FormulaRecord.java @@ -34,241 +34,241 @@ import org.apache.poi.util.Removal; */ public final class FormulaRecord extends CellRecord { - // docs say 406...because of a bug Microsoft support site article #Q184647) - public static final short sid = 0x0006; - // double + short + int - private static final int FIXED_SIZE = 14; + // docs say 406...because of a bug Microsoft support site article #Q184647) + public static final short sid = 0x0006; + // double + short + int + private static final int FIXED_SIZE = 14; - private static final BitField alwaysCalc = BitFieldFactory.getInstance(0x0001); - private static final BitField calcOnLoad = BitFieldFactory.getInstance(0x0002); - private static final BitField sharedFormula = BitFieldFactory.getInstance(0x0008); + private static final BitField alwaysCalc = BitFieldFactory.getInstance(0x0001); + private static final BitField calcOnLoad = BitFieldFactory.getInstance(0x0002); + private static final BitField sharedFormula = BitFieldFactory.getInstance(0x0008); - private double field_4_value; - private short field_5_options; - /** - * Unused field. As it turns out this field is often not zero.. - * According to Microsoft Excel Developer's Kit Page 318: - * when writing the chn field (offset 20), it's supposed to be 0 but ignored on read - */ - private int field_6_zero; - private Formula field_8_parsed_expr; + private double field_4_value; + private short field_5_options; + /** + * Unused field. As it turns out this field is often not zero.. + * According to Microsoft Excel Developer's Kit Page 318: + * when writing the chn field (offset 20), it's supposed to be 0 but ignored on read + */ + private int field_6_zero; + private Formula field_8_parsed_expr; - /** - * Since the NaN support seems sketchy (different constants) we'll store and spit it out directly - */ - private FormulaSpecialCachedValue specialCachedValue; + /** + * Since the NaN support seems sketchy (different constants) we'll store and spit it out directly + */ + private FormulaSpecialCachedValue specialCachedValue; - /** Creates new FormulaRecord */ - public FormulaRecord() { - field_8_parsed_expr = Formula.create(Ptg.EMPTY_PTG_ARRAY); - } + /** Creates new FormulaRecord */ + public FormulaRecord() { + field_8_parsed_expr = Formula.create(Ptg.EMPTY_PTG_ARRAY); + } - public FormulaRecord(FormulaRecord other) { - super(other); - field_4_value = other.field_4_value; - field_5_options = other.field_5_options; - field_6_zero = other.field_6_zero; - field_8_parsed_expr = (other.field_8_parsed_expr == null) ? null : new Formula(other.field_8_parsed_expr); - specialCachedValue = (other.specialCachedValue == null) ? null : new FormulaSpecialCachedValue(other.specialCachedValue); - } + public FormulaRecord(FormulaRecord other) { + super(other); + field_4_value = other.field_4_value; + field_5_options = other.field_5_options; + field_6_zero = other.field_6_zero; + field_8_parsed_expr = (other.field_8_parsed_expr == null) ? null : new Formula(other.field_8_parsed_expr); + specialCachedValue = (other.specialCachedValue == null) ? null : new FormulaSpecialCachedValue(other.specialCachedValue); + } - public FormulaRecord(RecordInputStream ris) { - super(ris); - long valueLongBits = ris.readLong(); - field_5_options = ris.readShort(); - specialCachedValue = FormulaSpecialCachedValue.create(valueLongBits); - if (specialCachedValue == null) { - field_4_value = Double.longBitsToDouble(valueLongBits); - } + public FormulaRecord(RecordInputStream ris) { + super(ris); + long valueLongBits = ris.readLong(); + field_5_options = ris.readShort(); + specialCachedValue = FormulaSpecialCachedValue.create(valueLongBits); + if (specialCachedValue == null) { + field_4_value = Double.longBitsToDouble(valueLongBits); + } - field_6_zero = ris.readInt(); + field_6_zero = ris.readInt(); - int field_7_expression_len = ris.readShort(); // this length does not include any extra array data - int nBytesAvailable = ris.available(); - field_8_parsed_expr = Formula.read(field_7_expression_len, ris, nBytesAvailable); - } + int field_7_expression_len = ris.readShort(); // this length does not include any extra array data + int nBytesAvailable = ris.available(); + field_8_parsed_expr = Formula.read(field_7_expression_len, ris, nBytesAvailable); + } - /** - * set the calculated value of the formula - * - * @param value calculated value - */ - public void setValue(double value) { - field_4_value = value; - specialCachedValue = null; - } + /** + * set the calculated value of the formula + * + * @param value calculated value + */ + public void setValue(double value) { + field_4_value = value; + specialCachedValue = null; + } - public void setCachedResultTypeEmptyString() { - specialCachedValue = FormulaSpecialCachedValue.createCachedEmptyValue(); - } - public void setCachedResultTypeString() { - specialCachedValue = FormulaSpecialCachedValue.createForString(); - } - public void setCachedResultErrorCode(int errorCode) { - specialCachedValue = FormulaSpecialCachedValue.createCachedErrorCode(errorCode); - } - public void setCachedResultBoolean(boolean value) { - specialCachedValue = FormulaSpecialCachedValue.createCachedBoolean(value); - } - /** - * @return true if this {@link FormulaRecord} is followed by a - * {@link StringRecord} representing the cached text result of the formula - * evaluation. - */ - public boolean hasCachedResultString() { - return specialCachedValue != null && - specialCachedValue.getTypeCode() == FormulaSpecialCachedValue.STRING; - } + public void setCachedResultTypeEmptyString() { + specialCachedValue = FormulaSpecialCachedValue.createCachedEmptyValue(); + } + public void setCachedResultTypeString() { + specialCachedValue = FormulaSpecialCachedValue.createForString(); + } + public void setCachedResultErrorCode(int errorCode) { + specialCachedValue = FormulaSpecialCachedValue.createCachedErrorCode(errorCode); + } + public void setCachedResultBoolean(boolean value) { + specialCachedValue = FormulaSpecialCachedValue.createCachedBoolean(value); + } + /** + * @return true if this {@link FormulaRecord} is followed by a + * {@link StringRecord} representing the cached text result of the formula + * evaluation. + */ + public boolean hasCachedResultString() { + return specialCachedValue != null && + specialCachedValue.getTypeCode() == FormulaSpecialCachedValue.STRING; + } - /** - * @deprecated POI 5.0.0, will be removed in 6.0, use getCachedResultTypeEnum until switch to enum is fully done - */ - @Deprecated - @Removal(version = "6.0.0") - public int getCachedResultType() { - if (specialCachedValue == null) { - return CellType.NUMERIC.getCode(); - } - return specialCachedValue.getValueType(); - } + /** + * @deprecated POI 5.0.0, will be removed in 6.0, use getCachedResultTypeEnum until switch to enum is fully done + */ + @Deprecated + @Removal(version = "6.0.0") + public int getCachedResultType() { + if (specialCachedValue == null) { + return CellType.NUMERIC.getCode(); + } + return specialCachedValue.getValueType(); + } - /** - * Returns the type of the cached result - * @return A CellType - * @since POI 5.0.0 - */ - public CellType getCachedResultTypeEnum() { - if (specialCachedValue == null) { - return CellType.NUMERIC; - } - return specialCachedValue.getValueTypeEnum(); - } + /** + * Returns the type of the cached result + * @return A CellType + * @since POI 5.0.0 + */ + public CellType getCachedResultTypeEnum() { + if (specialCachedValue == null) { + return CellType.NUMERIC; + } + return specialCachedValue.getValueTypeEnum(); + } - public boolean getCachedBooleanValue() { - return specialCachedValue.getBooleanValue(); - } - public int getCachedErrorValue() { - return specialCachedValue.getErrorValue(); - } + public boolean getCachedBooleanValue() { + return specialCachedValue.getBooleanValue(); + } + public int getCachedErrorValue() { + return specialCachedValue.getErrorValue(); + } - /** - * set the option flags - * - * @param options bitmask - */ - public void setOptions(short options) { - field_5_options = options; - } + /** + * set the option flags + * + * @param options bitmask + */ + public void setOptions(short options) { + field_5_options = options; + } - /** - * get the calculated value of the formula - * - * @return calculated value - */ - public double getValue() { - return field_4_value; - } + /** + * get the calculated value of the formula + * + * @return calculated value + */ + public double getValue() { + return field_4_value; + } - /** - * get the option flags - * - * @return bitmask - */ - public short getOptions() { - return field_5_options; - } + /** + * get the option flags + * + * @return bitmask + */ + public short getOptions() { + return field_5_options; + } - public boolean isSharedFormula() { - return sharedFormula.isSet(field_5_options); - } - public void setSharedFormula(boolean flag) { - field_5_options = - sharedFormula.setShortBoolean(field_5_options, flag); - } + public boolean isSharedFormula() { + return sharedFormula.isSet(field_5_options); + } + public void setSharedFormula(boolean flag) { + field_5_options = + sharedFormula.setShortBoolean(field_5_options, flag); + } - public boolean isAlwaysCalc() { - return alwaysCalc.isSet(field_5_options); - } - public void setAlwaysCalc(boolean flag) { - field_5_options = - alwaysCalc.setShortBoolean(field_5_options, flag); - } + public boolean isAlwaysCalc() { + return alwaysCalc.isSet(field_5_options); + } + public void setAlwaysCalc(boolean flag) { + field_5_options = + alwaysCalc.setShortBoolean(field_5_options, flag); + } - public boolean isCalcOnLoad() { - return calcOnLoad.isSet(field_5_options); - } - public void setCalcOnLoad(boolean flag) { - field_5_options = - calcOnLoad.setShortBoolean(field_5_options, flag); - } + public boolean isCalcOnLoad() { + return calcOnLoad.isSet(field_5_options); + } + public void setCalcOnLoad(boolean flag) { + field_5_options = + calcOnLoad.setShortBoolean(field_5_options, flag); + } - /** - * @return the formula tokens. never null - */ - public Ptg[] getParsedExpression() { - return field_8_parsed_expr.getTokens(); - } + /** + * @return the formula tokens. never null + */ + public Ptg[] getParsedExpression() { + return field_8_parsed_expr.getTokens(); + } - public Formula getFormula() { - return field_8_parsed_expr; - } + public Formula getFormula() { + return field_8_parsed_expr; + } - public void setParsedExpression(Ptg[] ptgs) { - field_8_parsed_expr = Formula.create(ptgs); - } + public void setParsedExpression(Ptg[] ptgs) { + field_8_parsed_expr = Formula.create(ptgs); + } - @Override + @Override public short getSid() { - return sid; - } + return sid; + } - @Override - protected int getValueDataSize() { - return FIXED_SIZE + field_8_parsed_expr.getEncodedSize(); - } - @Override - protected void serializeValue(LittleEndianOutput out) { + @Override + protected int getValueDataSize() { + return FIXED_SIZE + field_8_parsed_expr.getEncodedSize(); + } + @Override + protected void serializeValue(LittleEndianOutput out) { - if (specialCachedValue == null) { - out.writeDouble(field_4_value); - } else { - specialCachedValue.serialize(out); - } + if (specialCachedValue == null) { + out.writeDouble(field_4_value); + } else { + specialCachedValue.serialize(out); + } - out.writeShort(getOptions()); + out.writeShort(getOptions()); - out.writeInt(field_6_zero); // may as well write original data back so as to minimise differences from original - field_8_parsed_expr.serialize(out); - } + out.writeInt(field_6_zero); // may as well write original data back so as to minimise differences from original + field_8_parsed_expr.serialize(out); + } - @Override - protected String getRecordName() { - return "FORMULA"; - } + @Override + protected String getRecordName() { + return "FORMULA"; + } - @Override - public FormulaRecord copy() { - return new FormulaRecord(this); - } + @Override + public FormulaRecord copy() { + return new FormulaRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.FORMULA; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.FORMULA; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "base", super::getGenericProperties, - "options", this::getOptions, - "alwaysCalc", this::isAlwaysCalc, - "calcOnLoad", this::isCalcOnLoad, - "shared", this::isSharedFormula, - "zero", () -> field_6_zero, - "value", () -> specialCachedValue == null ? field_4_value : specialCachedValue, - "formula", this::getFormula - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "base", super::getGenericProperties, + "options", this::getOptions, + "alwaysCalc", this::isAlwaysCalc, + "calcOnLoad", this::isCalcOnLoad, + "shared", this::isSharedFormula, + "zero", () -> field_6_zero, + "value", () -> specialCachedValue == null ? field_4_value : specialCachedValue, + "formula", this::getFormula + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/FtCblsSubRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/FtCblsSubRecord.java index 529b9ec234..c849ec4f8f 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/FtCblsSubRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/FtCblsSubRecord.java @@ -73,7 +73,7 @@ public final class FtCblsSubRecord extends SubRecord { out.write(reserved); } - protected int getDataSize() { + protected int getDataSize() { return reserved.length; } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/GroupMarkerSubRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/GroupMarkerSubRecord.java index 805bca3442..dcbf4ee7d8 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/GroupMarkerSubRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/GroupMarkerSubRecord.java @@ -65,7 +65,7 @@ public final class GroupMarkerSubRecord extends SubRecord { out.write(reserved); } - protected int getDataSize() { + protected int getDataSize() { return reserved.length; } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/HeaderFooterBase.java b/poi/src/main/java/org/apache/poi/hssf/record/HeaderFooterBase.java index 68e242e7bd..88374d84a6 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/HeaderFooterBase.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/HeaderFooterBase.java @@ -28,99 +28,99 @@ import org.apache.poi.util.StringUtil; * Common header/footer base class */ public abstract class HeaderFooterBase extends StandardRecord { - private boolean field_2_hasMultibyte; - private String field_3_text; + private boolean field_2_hasMultibyte; + private String field_3_text; - protected HeaderFooterBase(String text) { - setText(text); - } + protected HeaderFooterBase(String text) { + setText(text); + } - protected HeaderFooterBase(HeaderFooterBase other) { - super(other); - field_2_hasMultibyte = other.field_2_hasMultibyte; - field_3_text = other.field_3_text; - } + protected HeaderFooterBase(HeaderFooterBase other) { + super(other); + field_2_hasMultibyte = other.field_2_hasMultibyte; + field_3_text = other.field_3_text; + } - protected HeaderFooterBase(RecordInputStream in) { - if (in.remaining() > 0) { - int field_1_footer_len = in.readShort(); - //61287 -- if the footer_len == 0, there may not be a multibyte flag - if (field_1_footer_len == 0) { - field_3_text = ""; - if (in.remaining() == 0) { - return; - } - } - field_2_hasMultibyte = in.readByte() != 0x00; + protected HeaderFooterBase(RecordInputStream in) { + if (in.remaining() > 0) { + int field_1_footer_len = in.readShort(); + //61287 -- if the footer_len == 0, there may not be a multibyte flag + if (field_1_footer_len == 0) { + field_3_text = ""; + if (in.remaining() == 0) { + return; + } + } + field_2_hasMultibyte = in.readByte() != 0x00; - if (field_2_hasMultibyte) { - field_3_text = in.readUnicodeLEString(field_1_footer_len); - } else { - field_3_text = in.readCompressedUnicode(field_1_footer_len); - } - } else { - // Note - this is unusual for BIFF records in general, but normal for header / footer records: - // when the text is empty string, the whole record is empty (just the 4 byte BIFF header) - field_3_text = ""; - } - } + if (field_2_hasMultibyte) { + field_3_text = in.readUnicodeLEString(field_1_footer_len); + } else { + field_3_text = in.readCompressedUnicode(field_1_footer_len); + } + } else { + // Note - this is unusual for BIFF records in general, but normal for header / footer records: + // when the text is empty string, the whole record is empty (just the 4 byte BIFF header) + field_3_text = ""; + } + } - /** - * set the footer string - * - * @param text string to display - */ - public final void setText(String text) { - if (text == null) { - throw new IllegalArgumentException("text must not be null"); - } - field_2_hasMultibyte = StringUtil.hasMultibyte(text); - field_3_text = text; + /** + * set the footer string + * + * @param text string to display + */ + public final void setText(String text) { + if (text == null) { + throw new IllegalArgumentException("text must not be null"); + } + field_2_hasMultibyte = StringUtil.hasMultibyte(text); + field_3_text = text; - // Check it'll fit into the space in the record - if (getDataSize() > RecordInputStream.MAX_RECORD_DATA_SIZE) { - throw new IllegalArgumentException("Header/Footer string too long (limit is " - + RecordInputStream.MAX_RECORD_DATA_SIZE + " bytes)"); - } - } + // Check it'll fit into the space in the record + if (getDataSize() > RecordInputStream.MAX_RECORD_DATA_SIZE) { + throw new IllegalArgumentException("Header/Footer string too long (limit is " + + RecordInputStream.MAX_RECORD_DATA_SIZE + " bytes)"); + } + } - /** - * get the length of the footer string - * - * @return length of the footer string - */ - private int getTextLength() { - return field_3_text.length(); - } + /** + * get the length of the footer string + * + * @return length of the footer string + */ + private int getTextLength() { + return field_3_text.length(); + } - public final String getText() { - return field_3_text; - } + public final String getText() { + return field_3_text; + } - public final void serialize(LittleEndianOutput out) { - if (getTextLength() > 0) { - out.writeShort(getTextLength()); - out.writeByte(field_2_hasMultibyte ? 0x01 : 0x00); - if (field_2_hasMultibyte) { - StringUtil.putUnicodeLE(field_3_text, out); - } else { - StringUtil.putCompressedUnicode(field_3_text, out); - } - } - } + public final void serialize(LittleEndianOutput out) { + if (getTextLength() > 0) { + out.writeShort(getTextLength()); + out.writeByte(field_2_hasMultibyte ? 0x01 : 0x00); + if (field_2_hasMultibyte) { + StringUtil.putUnicodeLE(field_3_text, out); + } else { + StringUtil.putCompressedUnicode(field_3_text, out); + } + } + } - protected final int getDataSize() { - if (getTextLength() < 1) { - return 0; - } - return 3 + getTextLength() * (field_2_hasMultibyte ? 2 : 1); - } + protected final int getDataSize() { + if (getTextLength() < 1) { + return 0; + } + return 3 + getTextLength() * (field_2_hasMultibyte ? 2 : 1); + } - @Override - public abstract HeaderFooterBase copy(); + @Override + public abstract HeaderFooterBase copy(); - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties("text", this::getText); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties("text", this::getText); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/HeaderFooterRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/HeaderFooterRecord.java index 8db7fcb238..9f6fdfccd4 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/HeaderFooterRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/HeaderFooterRecord.java @@ -32,7 +32,7 @@ public final class HeaderFooterRecord extends StandardRecord { @SuppressWarnings("MismatchedReadAndWriteOfArray") private static final byte[] BLANK_GUID = new byte[16]; - private byte[] _rawData; + private byte[] _rawData; public HeaderFooterRecord(byte[] data) { _rawData = data; @@ -43,25 +43,25 @@ public final class HeaderFooterRecord extends StandardRecord { _rawData = (other._rawData == null) ? null : other._rawData.clone(); } - /** - * construct a HeaderFooterRecord record. No fields are interpreted and the record will - * be serialized in its original form more or less - * @param in the RecordInputstream to read the record from - */ - public HeaderFooterRecord(RecordInputStream in) { - _rawData = in.readRemainder(); - } + /** + * construct a HeaderFooterRecord record. No fields are interpreted and the record will + * be serialized in its original form more or less + * @param in the RecordInputstream to read the record from + */ + public HeaderFooterRecord(RecordInputStream in) { + _rawData = in.readRemainder(); + } - /** - * spit the record out AS IS. no interpretation or identification - */ - public void serialize(LittleEndianOutput out) { - out.write(_rawData); - } + /** + * spit the record out AS IS. no interpretation or identification + */ + public void serialize(LittleEndianOutput out) { + out.write(_rawData); + } - protected int getDataSize() { - return _rawData.length; - } + protected int getDataSize() { + return _rawData.length; + } public short getSid() { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/HeaderRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/HeaderRecord.java index b3447121ad..dd6f3c0a24 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/HeaderRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/HeaderRecord.java @@ -21,31 +21,31 @@ package org.apache.poi.hssf.record; * Specifies a header for a sheet */ public final class HeaderRecord extends HeaderFooterBase { - public static final short sid = 0x0014; + public static final short sid = 0x0014; - public HeaderRecord(String text) { - super(text); - } + public HeaderRecord(String text) { + super(text); + } - public HeaderRecord(HeaderRecord other) { - super(other); - } + public HeaderRecord(HeaderRecord other) { + super(other); + } - public HeaderRecord(RecordInputStream in) { - super(in); - } + public HeaderRecord(RecordInputStream in) { + super(in); + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - @Override - public HeaderRecord copy() { - return new HeaderRecord(this); - } + @Override + public HeaderRecord copy() { + return new HeaderRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.HEADER; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.HEADER; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/HorizontalPageBreakRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/HorizontalPageBreakRecord.java index 67b16b3d0b..b67a0a2114 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/HorizontalPageBreakRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/HorizontalPageBreakRecord.java @@ -24,35 +24,35 @@ package org.apache.poi.hssf.record; */ public final class HorizontalPageBreakRecord extends PageBreakRecord { - public static final short sid = 0x001B; + public static final short sid = 0x001B; - /** - * Creates an empty horizontal page break record - */ - public HorizontalPageBreakRecord() {} + /** + * Creates an empty horizontal page break record + */ + public HorizontalPageBreakRecord() {} - public HorizontalPageBreakRecord(HorizontalPageBreakRecord other) { - super(other); - } + public HorizontalPageBreakRecord(HorizontalPageBreakRecord other) { + super(other); + } - /** - * @param in the RecordInputstream to read the record from - */ - public HorizontalPageBreakRecord(RecordInputStream in) { - super(in); - } + /** + * @param in the RecordInputstream to read the record from + */ + public HorizontalPageBreakRecord(RecordInputStream in) { + super(in); + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - @Override - public HorizontalPageBreakRecord copy() { - return new HorizontalPageBreakRecord(this); - } + @Override + public HorizontalPageBreakRecord copy() { + return new HorizontalPageBreakRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.HORIZONTAL_PAGE_BREAK; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.HORIZONTAL_PAGE_BREAK; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/IndexRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/IndexRecord.java index dd7772c845..9d17728c3d 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/IndexRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/IndexRecord.java @@ -48,7 +48,7 @@ public final class IndexRecord extends StandardRecord { public IndexRecord(RecordInputStream in) { int field_1_zero = in.readInt(); if (field_1_zero != 0) { - throw new RecordFormatException("Expected zero for field 1 but got " + field_1_zero); + throw new RecordFormatException("Expected zero for field 1 but got " + field_1_zero); } field_2_first_row = in.readInt(); field_3_last_row_add1 = in.readInt(); @@ -117,14 +117,14 @@ public final class IndexRecord extends StandardRecord { out.writeInt(getLastRowAdd1()); out.writeInt(field_4_zero); for (int k = 0; k < getNumDbcells(); k++) { - out.writeInt(getDbcellAt(k)); + out.writeInt(getDbcellAt(k)); } } @Override protected int getDataSize() { return 16 // 4 ints - + getNumDbcells() * 4; + + getNumDbcells() * 4; } /** diff --git a/poi/src/main/java/org/apache/poi/hssf/record/LabelRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/LabelRecord.java index b21286085e..2ce42a6be3 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/LabelRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/LabelRecord.java @@ -152,8 +152,8 @@ public final class LabelRecord extends Record implements CellValueRecordInterfac } /** - * NO-OP! - */ + * NO-OP! + */ @Override public void setColumn(short col) { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/LabelSSTRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/LabelSSTRecord.java index 1872845f8e..30c3871f9b 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/LabelSSTRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/LabelSSTRecord.java @@ -65,7 +65,7 @@ public final class LabelSSTRecord extends CellRecord { @Override protected String getRecordName() { - return "LABELSST"; + return "LABELSST"; } @Override diff --git a/poi/src/main/java/org/apache/poi/hssf/record/Margin.java b/poi/src/main/java/org/apache/poi/hssf/record/Margin.java index 933eb75e65..f9c198bc30 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/Margin.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/Margin.java @@ -22,18 +22,18 @@ package org.apache.poi.hssf.record; * This allows much of the code to be generic when it comes to handling margins. */ public interface Margin { - // TODO - introduce MarginBaseRecord - /** - * Get the margin field for the Margin. - * - * @return the margin - */ - double getMargin(); + // TODO - introduce MarginBaseRecord + /** + * Get the margin field for the Margin. + * + * @return the margin + */ + double getMargin(); - /** - * Set the margin field for the Margin. - * - * @param field_1_margin the margin - */ - void setMargin(double field_1_margin); + /** + * Set the margin field for the Margin. + * + * @param field_1_margin the margin + */ + void setMargin(double field_1_margin); } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/MergeCellsRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/MergeCellsRecord.java index 3978dc9c60..0207c109d5 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/MergeCellsRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/MergeCellsRecord.java @@ -48,23 +48,23 @@ public final class MergeCellsRecord extends StandardRecord { public MergeCellsRecord(CellRangeAddress[] regions, int startIndex, int numberOfRegions) { - _regions = regions; - _startIndex = startIndex; - _numberOfRegions = numberOfRegions; + _regions = regions; + _startIndex = startIndex; + _numberOfRegions = numberOfRegions; } /** * Constructs a MergedCellsRecord and sets its fields appropriately * @param in the RecordInputstream to read the record from */ public MergeCellsRecord(RecordInputStream in) { - int nRegions = in.readUShort(); - CellRangeAddress[] cras = new CellRangeAddress[nRegions]; - for (int i = 0; i < nRegions; i++) { - cras[i] = new CellRangeAddress(in); - } - _numberOfRegions = nRegions; - _startIndex = 0; - _regions = cras; + int nRegions = in.readUShort(); + CellRangeAddress[] cras = new CellRangeAddress[nRegions]; + for (int i = 0; i < nRegions; i++) { + cras[i] = new CellRangeAddress(in); + } + _numberOfRegions = nRegions; + _startIndex = 0; + _regions = cras; } /** * get the number of merged areas. If this drops down to 0 you should just go @@ -86,8 +86,8 @@ public final class MergeCellsRecord extends StandardRecord { @Override protected int getDataSize() { - return CellRangeAddressList.getEncodedSize(_numberOfRegions); - } + return CellRangeAddressList.getEncodedSize(_numberOfRegions); + } @Override public short getSid() { @@ -98,8 +98,8 @@ public final class MergeCellsRecord extends StandardRecord { public void serialize(LittleEndianOutput out) { out.writeShort(_numberOfRegions); for (int i = 0; i < _numberOfRegions; i++) { - _regions[_startIndex + i].serialize(out); - } + _regions[_startIndex + i].serialize(out); + } } @Override diff --git a/poi/src/main/java/org/apache/poi/hssf/record/MulBlankRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/MulBlankRecord.java index 0f395cc272..860c1ac2c0 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/MulBlankRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/MulBlankRecord.java @@ -29,113 +29,113 @@ import org.apache.poi.util.LittleEndianOutput; * @see BlankRecord */ public final class MulBlankRecord extends StandardRecord { - public static final short sid = 0x00BE; + public static final short sid = 0x00BE; - private final int _row; - private final int _firstCol; - private final short[] _xfs; - private final int _lastCol; + private final int _row; + private final int _firstCol; + private final short[] _xfs; + private final int _lastCol; - public MulBlankRecord(int row, int firstCol, short[] xfs) { - _row = row; - _firstCol = firstCol; - _xfs = xfs; - _lastCol = firstCol + xfs.length - 1; - } + public MulBlankRecord(int row, int firstCol, short[] xfs) { + _row = row; + _firstCol = firstCol; + _xfs = xfs; + _lastCol = firstCol + xfs.length - 1; + } - /** - * @return the row number of the cells this represents - */ - public int getRow() { - return _row; - } + /** + * @return the row number of the cells this represents + */ + public int getRow() { + return _row; + } - /** - * @return starting column (first cell this holds in the row). Zero based - */ - public int getFirstColumn() { - return _firstCol; - } + /** + * @return starting column (first cell this holds in the row). Zero based + */ + public int getFirstColumn() { + return _firstCol; + } - /** - * @return ending column (last cell this holds in the row). Zero based - */ - public int getLastColumn() { - return _lastCol; - } + /** + * @return ending column (last cell this holds in the row). Zero based + */ + public int getLastColumn() { + return _lastCol; + } - /** - * get the number of columns this contains (last-first +1) - * @return number of columns (last - first +1) - */ - public int getNumColumns() { - return _lastCol - _firstCol + 1; - } + /** + * get the number of columns this contains (last-first +1) + * @return number of columns (last - first +1) + */ + public int getNumColumns() { + return _lastCol - _firstCol + 1; + } - /** - * returns the xf index for column (coffset = column - field_2_first_col) - * @param coffset the column (coffset = column - field_2_first_col) - * @return the XF index for the column - */ - public short getXFAt(int coffset) { - return _xfs[coffset]; - } + /** + * returns the xf index for column (coffset = column - field_2_first_col) + * @param coffset the column (coffset = column - field_2_first_col) + * @return the XF index for the column + */ + public short getXFAt(int coffset) { + return _xfs[coffset]; + } - /** - * @param in the RecordInputstream to read the record from - */ - public MulBlankRecord(RecordInputStream in) { - _row = in.readUShort(); - _firstCol = in.readShort(); - _xfs = parseXFs(in); - _lastCol = in.readShort(); - } + /** + * @param in the RecordInputstream to read the record from + */ + public MulBlankRecord(RecordInputStream in) { + _row = in.readUShort(); + _firstCol = in.readShort(); + _xfs = parseXFs(in); + _lastCol = in.readShort(); + } - private static short [] parseXFs(RecordInputStream in) { - short[] retval = new short[(in.remaining() - 2) / 2]; + private static short [] parseXFs(RecordInputStream in) { + short[] retval = new short[(in.remaining() - 2) / 2]; - for (int idx = 0; idx < retval.length;idx++) { - retval[idx] = in.readShort(); - } - return retval; - } + for (int idx = 0; idx < retval.length;idx++) { + retval[idx] = in.readShort(); + } + return retval; + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - public void serialize(LittleEndianOutput out) { - out.writeShort(_row); - out.writeShort(_firstCol); - for (short xf : _xfs) { - out.writeShort(xf); - } - out.writeShort(_lastCol); - } + public void serialize(LittleEndianOutput out) { + out.writeShort(_row); + out.writeShort(_firstCol); + for (short xf : _xfs) { + out.writeShort(xf); + } + out.writeShort(_lastCol); + } - protected int getDataSize() { - // 3 short fields + array of shorts - return 6 + _xfs.length * 2; - } + protected int getDataSize() { + // 3 short fields + array of shorts + return 6 + _xfs.length * 2; + } - @Override - public MulBlankRecord copy() { - // immutable - so OK to return this - return this; - } + @Override + public MulBlankRecord copy() { + // immutable - so OK to return this + return this; + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.MUL_BLANK; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.MUL_BLANK; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "row", this::getRow, - "firstColumn", this::getFirstColumn, - "lastColumn", this::getLastColumn, - "xf", () -> _xfs - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "row", this::getRow, + "firstColumn", this::getFirstColumn, + "lastColumn", this::getLastColumn, + "xf", () -> _xfs + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/MulRKRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/MulRKRecord.java index 86ec9fc64a..86569d804c 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/MulRKRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/MulRKRecord.java @@ -33,134 +33,134 @@ import org.apache.poi.util.RecordFormatException; * @since 2.0-pre */ public final class MulRKRecord extends StandardRecord { - public static final short sid = 0x00BD; + public static final short sid = 0x00BD; - private final int field_1_row; - private final short field_2_first_col; - private final RkRec[] field_3_rks; - private final short field_4_last_col; + private final int field_1_row; + private final short field_2_first_col; + private final RkRec[] field_3_rks; + private final short field_4_last_col; - public int getRow() { - return field_1_row; - } + public int getRow() { + return field_1_row; + } - /** - * starting column (first cell this holds in the row) - * @return first column number - */ - public short getFirstColumn() { - return field_2_first_col; - } + /** + * starting column (first cell this holds in the row) + * @return first column number + */ + public short getFirstColumn() { + return field_2_first_col; + } - /** - * ending column (last cell this holds in the row) - * @return first column number - */ - public short getLastColumn() { - return field_4_last_col; - } + /** + * ending column (last cell this holds in the row) + * @return first column number + */ + public short getLastColumn() { + return field_4_last_col; + } - /** - * get the number of columns this contains (last-first +1) - * @return number of columns (last - first +1) - */ - public int getNumColumns() { - return field_4_last_col - field_2_first_col + 1; - } + /** + * get the number of columns this contains (last-first +1) + * @return number of columns (last - first +1) + */ + public int getNumColumns() { + return field_4_last_col - field_2_first_col + 1; + } - /** - * returns the xf index for column (coffset = column - field_2_first_col) - * + /** + * returns the xf index for column (coffset = column - field_2_first_col) + * * @param coffset the coffset = column - field_2_first_col * - * @return the XF index for the column - */ - public short getXFAt(int coffset) { - return field_3_rks[coffset].xf; - } + * @return the XF index for the column + */ + public short getXFAt(int coffset) { + return field_3_rks[coffset].xf; + } - /** - * returns the rk number for column (coffset = column - field_2_first_col) - * - * @param coffset the coffset = column - field_2_first_col - * - * @return the value (decoded into a double) - */ - public double getRKNumberAt(int coffset) { - return RKUtil.decodeNumber(field_3_rks[coffset].rk); - } + /** + * returns the rk number for column (coffset = column - field_2_first_col) + * + * @param coffset the coffset = column - field_2_first_col + * + * @return the value (decoded into a double) + */ + public double getRKNumberAt(int coffset) { + return RKUtil.decodeNumber(field_3_rks[coffset].rk); + } - /** - * @param in the RecordInputstream to read the record from - */ - public MulRKRecord(RecordInputStream in) { - field_1_row = in.readUShort(); - field_2_first_col = in.readShort(); - field_3_rks = RkRec.parseRKs(in); - field_4_last_col = in.readShort(); - } + /** + * @param in the RecordInputstream to read the record from + */ + public MulRKRecord(RecordInputStream in) { + field_1_row = in.readUShort(); + field_2_first_col = in.readShort(); + field_3_rks = RkRec.parseRKs(in); + field_4_last_col = in.readShort(); + } - @Override + @Override public short getSid() - { - return sid; - } + { + return sid; + } - @Override + @Override public void serialize(LittleEndianOutput out) { - throw new RecordFormatException( "Sorry, you can't serialize MulRK in this release"); - } - @Override + throw new RecordFormatException( "Sorry, you can't serialize MulRK in this release"); + } + @Override protected int getDataSize() { - throw new RecordFormatException( "Sorry, you can't serialize MulRK in this release"); - } + throw new RecordFormatException( "Sorry, you can't serialize MulRK in this release"); + } - private static final class RkRec implements GenericRecord { - public static final int ENCODED_SIZE = 6; - public final short xf; - public final int rk; + private static final class RkRec implements GenericRecord { + public static final int ENCODED_SIZE = 6; + public final short xf; + public final int rk; - private RkRec(RecordInputStream in) { - xf = in.readShort(); - rk = in.readInt(); - } + private RkRec(RecordInputStream in) { + xf = in.readShort(); + rk = in.readInt(); + } - public static RkRec[] parseRKs(RecordInputStream in) { - int nItems = (in.remaining()-2) / ENCODED_SIZE; - RkRec[] retval = new RkRec[nItems]; - for (int i=0; i> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "xf", () -> xf, - "rk", () -> rk - ); - } - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "xf", () -> xf, + "rk", () -> rk + ); + } + } - @Override - public MulRKRecord copy() { - // immutable - so OK to return this - return this; - } + @Override + public MulRKRecord copy() { + // immutable - so OK to return this + return this; + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.MUL_RK; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.MUL_RK; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "row", this::getRow, - "firstColumn", this::getFirstColumn, - "lastColumn", this::getLastColumn, - "rk", () -> field_3_rks - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "row", this::getRow, + "firstColumn", this::getFirstColumn, + "lastColumn", this::getLastColumn, + "rk", () -> field_3_rks + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/NameRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/NameRecord.java index 5a527ab04b..80d89f1ede 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/NameRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/NameRecord.java @@ -38,427 +38,427 @@ import org.apache.poi.util.StringUtil; @SuppressWarnings("unused") public final class NameRecord extends ContinuableRecord { public static final short sid = 0x0018; - /**Included for completeness sake, not implemented */ - public static final byte BUILTIN_CONSOLIDATE_AREA = 1; - /**Included for completeness sake, not implemented */ - public static final byte BUILTIN_AUTO_OPEN = 2; - /**Included for completeness sake, not implemented */ - public static final byte BUILTIN_AUTO_CLOSE = 3; - /**Included for completeness sake, not implemented */ - public static final byte BUILTIN_DATABASE = 4; - /**Included for completeness sake, not implemented */ - public static final byte BUILTIN_CRITERIA = 5; + /**Included for completeness sake, not implemented */ + public static final byte BUILTIN_CONSOLIDATE_AREA = 1; + /**Included for completeness sake, not implemented */ + public static final byte BUILTIN_AUTO_OPEN = 2; + /**Included for completeness sake, not implemented */ + public static final byte BUILTIN_AUTO_CLOSE = 3; + /**Included for completeness sake, not implemented */ + public static final byte BUILTIN_DATABASE = 4; + /**Included for completeness sake, not implemented */ + public static final byte BUILTIN_CRITERIA = 5; - public static final byte BUILTIN_PRINT_AREA = 6; - public static final byte BUILTIN_PRINT_TITLE = 7; + public static final byte BUILTIN_PRINT_AREA = 6; + public static final byte BUILTIN_PRINT_TITLE = 7; - /**Included for completeness sake, not implemented */ - public static final byte BUILTIN_RECORDER = 8; - /**Included for completeness sake, not implemented */ - public static final byte BUILTIN_DATA_FORM = 9; - /**Included for completeness sake, not implemented */ - public static final byte BUILTIN_AUTO_ACTIVATE = 10; - /**Included for completeness sake, not implemented */ - public static final byte BUILTIN_AUTO_DEACTIVATE = 11; - /**Included for completeness sake, not implemented */ - public static final byte BUILTIN_SHEET_TITLE = 12; + /**Included for completeness sake, not implemented */ + public static final byte BUILTIN_RECORDER = 8; + /**Included for completeness sake, not implemented */ + public static final byte BUILTIN_DATA_FORM = 9; + /**Included for completeness sake, not implemented */ + public static final byte BUILTIN_AUTO_ACTIVATE = 10; + /**Included for completeness sake, not implemented */ + public static final byte BUILTIN_AUTO_DEACTIVATE = 11; + /**Included for completeness sake, not implemented */ + public static final byte BUILTIN_SHEET_TITLE = 12; - public static final byte BUILTIN_FILTER_DB = 13; + public static final byte BUILTIN_FILTER_DB = 13; - private static final class Option { - public static final int OPT_HIDDEN_NAME = 0x0001; - public static final int OPT_FUNCTION_NAME = 0x0002; - public static final int OPT_COMMAND_NAME = 0x0004; - public static final int OPT_MACRO = 0x0008; - public static final int OPT_COMPLEX = 0x0010; - public static final int OPT_BUILTIN = 0x0020; - public static final int OPT_BINDATA = 0x1000; - public static boolean isFormula(int optValue) { - return (optValue & 0x0F) == 0; - } - } + private static final class Option { + public static final int OPT_HIDDEN_NAME = 0x0001; + public static final int OPT_FUNCTION_NAME = 0x0002; + public static final int OPT_COMMAND_NAME = 0x0004; + public static final int OPT_MACRO = 0x0008; + public static final int OPT_COMPLEX = 0x0010; + public static final int OPT_BUILTIN = 0x0020; + public static final int OPT_BINDATA = 0x1000; + public static boolean isFormula(int optValue) { + return (optValue & 0x0F) == 0; + } + } - private short field_1_option_flag; - private byte field_2_keyboard_shortcut; - /** One-based extern index of sheet (resolved via LinkTable). Zero if this is a global name */ - private short field_5_externSheetIndex_plus1; - /** the one based sheet number. */ - private int field_6_sheetNumber; - private boolean field_11_nameIsMultibyte; - private byte field_12_built_in_code; - private String field_12_name_text; - private Formula field_13_name_definition; - private String field_14_custom_menu_text; - private String field_15_description_text; - private String field_16_help_topic_text; - private String field_17_status_bar_text; + private short field_1_option_flag; + private byte field_2_keyboard_shortcut; + /** One-based extern index of sheet (resolved via LinkTable). Zero if this is a global name */ + private short field_5_externSheetIndex_plus1; + /** the one based sheet number. */ + private int field_6_sheetNumber; + private boolean field_11_nameIsMultibyte; + private byte field_12_built_in_code; + private String field_12_name_text; + private Formula field_13_name_definition; + private String field_14_custom_menu_text; + private String field_15_description_text; + private String field_16_help_topic_text; + private String field_17_status_bar_text; - /** Creates new NameRecord */ - public NameRecord() { - field_13_name_definition = Formula.create(Ptg.EMPTY_PTG_ARRAY); + /** Creates new NameRecord */ + public NameRecord() { + field_13_name_definition = Formula.create(Ptg.EMPTY_PTG_ARRAY); - field_12_name_text = ""; - field_14_custom_menu_text = ""; - field_15_description_text = ""; - field_16_help_topic_text = ""; - field_17_status_bar_text = ""; - } + field_12_name_text = ""; + field_14_custom_menu_text = ""; + field_15_description_text = ""; + field_16_help_topic_text = ""; + field_17_status_bar_text = ""; + } - public NameRecord(NameRecord other) { - super(other); - field_1_option_flag = other.field_1_option_flag; - field_2_keyboard_shortcut = other.field_2_keyboard_shortcut; - field_5_externSheetIndex_plus1 = other.field_5_externSheetIndex_plus1; - field_6_sheetNumber = other.field_6_sheetNumber; - field_11_nameIsMultibyte = other.field_11_nameIsMultibyte; - field_12_built_in_code = other.field_12_built_in_code; - field_12_name_text = other.field_12_name_text; - field_13_name_definition = other.field_13_name_definition; - field_14_custom_menu_text = other.field_14_custom_menu_text; - field_15_description_text = other.field_15_description_text; - field_16_help_topic_text = other.field_16_help_topic_text; - field_17_status_bar_text = other.field_17_status_bar_text; - } + public NameRecord(NameRecord other) { + super(other); + field_1_option_flag = other.field_1_option_flag; + field_2_keyboard_shortcut = other.field_2_keyboard_shortcut; + field_5_externSheetIndex_plus1 = other.field_5_externSheetIndex_plus1; + field_6_sheetNumber = other.field_6_sheetNumber; + field_11_nameIsMultibyte = other.field_11_nameIsMultibyte; + field_12_built_in_code = other.field_12_built_in_code; + field_12_name_text = other.field_12_name_text; + field_13_name_definition = other.field_13_name_definition; + field_14_custom_menu_text = other.field_14_custom_menu_text; + field_15_description_text = other.field_15_description_text; + field_16_help_topic_text = other.field_16_help_topic_text; + field_17_status_bar_text = other.field_17_status_bar_text; + } - /** - * Constructor to create a built-in named region - * @param builtin Built-in byte representation for the name record, use the public constants - * @param sheetNumber the sheet which the name applies to - */ - public NameRecord(byte builtin, int sheetNumber) - { - this(); - field_12_built_in_code = builtin; - setOptionFlag((short)(field_1_option_flag | Option.OPT_BUILTIN)); - // the extern sheets are set through references - field_6_sheetNumber = sheetNumber; - } + /** + * Constructor to create a built-in named region + * @param builtin Built-in byte representation for the name record, use the public constants + * @param sheetNumber the sheet which the name applies to + */ + public NameRecord(byte builtin, int sheetNumber) + { + this(); + field_12_built_in_code = builtin; + setOptionFlag((short)(field_1_option_flag | Option.OPT_BUILTIN)); + // the extern sheets are set through references + field_6_sheetNumber = sheetNumber; + } - /** sets the option flag for the named range - * @param flag option flag - */ - public void setOptionFlag(short flag){ - field_1_option_flag = flag; - } + /** sets the option flag for the named range + * @param flag option flag + */ + public void setOptionFlag(short flag){ + field_1_option_flag = flag; + } - /** sets the keyboard shortcut - * @param shortcut keyboard shortcut - */ - public void setKeyboardShortcut(byte shortcut){ - field_2_keyboard_shortcut = shortcut; - } + /** sets the keyboard shortcut + * @param shortcut keyboard shortcut + */ + public void setKeyboardShortcut(byte shortcut){ + field_2_keyboard_shortcut = shortcut; + } - /** - * For named ranges, and built-in names - * @return the 1-based sheet number. - */ - public int getSheetNumber() - { - return field_6_sheetNumber; - } + /** + * For named ranges, and built-in names + * @return the 1-based sheet number. + */ + public int getSheetNumber() + { + return field_6_sheetNumber; + } - /** - * @return function group - * @see FnGroupCountRecord - */ - public byte getFnGroup() { - int masked = field_1_option_flag & 0x0fc0; - return (byte) (masked >> 4); - } + /** + * @return function group + * @see FnGroupCountRecord + */ + public byte getFnGroup() { + int masked = field_1_option_flag & 0x0fc0; + return (byte) (masked >> 4); + } - public void setSheetNumber(int value) - { - field_6_sheetNumber = value; - } + public void setSheetNumber(int value) + { + field_6_sheetNumber = value; + } - /** sets the name of the named range - * @param name named range name - */ - public void setNameText(String name){ - field_12_name_text = name; - field_11_nameIsMultibyte = StringUtil.hasMultibyte(name); - } + /** sets the name of the named range + * @param name named range name + */ + public void setNameText(String name){ + field_12_name_text = name; + field_11_nameIsMultibyte = StringUtil.hasMultibyte(name); + } - /** sets the custom menu text - * @param text custom menu text - */ - public void setCustomMenuText(String text){ - field_14_custom_menu_text = text; - } + /** sets the custom menu text + * @param text custom menu text + */ + public void setCustomMenuText(String text){ + field_14_custom_menu_text = text; + } - /** sets the description text - * @param text the description text - */ - public void setDescriptionText(String text){ - field_15_description_text = text; - } + /** sets the description text + * @param text the description text + */ + public void setDescriptionText(String text){ + field_15_description_text = text; + } - /** sets the help topic text - * @param text help topix text - */ - public void setHelpTopicText(String text){ - field_16_help_topic_text = text; - } + /** sets the help topic text + * @param text help topix text + */ + public void setHelpTopicText(String text){ + field_16_help_topic_text = text; + } - /** sets the status bar text - * @param text status bar text - */ - public void setStatusBarText(String text){ - field_17_status_bar_text = text; - } + /** sets the status bar text + * @param text status bar text + */ + public void setStatusBarText(String text){ + field_17_status_bar_text = text; + } - /** gets the option flag - * @return option flag - */ - public short getOptionFlag(){ - return field_1_option_flag; - } + /** gets the option flag + * @return option flag + */ + public short getOptionFlag(){ + return field_1_option_flag; + } - /** returns the keyboard shortcut - * @return keyboard shortcut - */ - public byte getKeyboardShortcut(){ - return field_2_keyboard_shortcut ; - } + /** returns the keyboard shortcut + * @return keyboard shortcut + */ + public byte getKeyboardShortcut(){ + return field_2_keyboard_shortcut ; + } - /** - * gets the name length, in characters - * @return name length - */ - private int getNameTextLength(){ - if (isBuiltInName()) { - return 1; - } - return field_12_name_text.length(); - } + /** + * gets the name length, in characters + * @return name length + */ + private int getNameTextLength(){ + if (isBuiltInName()) { + return 1; + } + return field_12_name_text.length(); + } - /** - * @return true if name is hidden - */ - public boolean isHiddenName() { - return (field_1_option_flag & Option.OPT_HIDDEN_NAME) != 0; - } + /** + * @return true if name is hidden + */ + public boolean isHiddenName() { + return (field_1_option_flag & Option.OPT_HIDDEN_NAME) != 0; + } - public void setHidden(boolean b) { - if (b) { - field_1_option_flag |= Option.OPT_HIDDEN_NAME; - } else { - field_1_option_flag &= (~Option.OPT_HIDDEN_NAME); - } - } - /** - * @return true if name is a function - */ - public boolean isFunctionName() { - return (field_1_option_flag & Option.OPT_FUNCTION_NAME) != 0; - } + public void setHidden(boolean b) { + if (b) { + field_1_option_flag |= Option.OPT_HIDDEN_NAME; + } else { + field_1_option_flag &= (~Option.OPT_HIDDEN_NAME); + } + } + /** + * @return true if name is a function + */ + public boolean isFunctionName() { + return (field_1_option_flag & Option.OPT_FUNCTION_NAME) != 0; + } - /** - * Indicates that the defined name refers to a user-defined function. - * This attribute is used when there is an add-in or other code project associated with the file. - * - * @param function true indicates the name refers to a function. - */ - public void setFunction(boolean function){ - if (function) { - field_1_option_flag |= Option.OPT_FUNCTION_NAME; - } else { - field_1_option_flag &= (~Option.OPT_FUNCTION_NAME); - } - } + /** + * Indicates that the defined name refers to a user-defined function. + * This attribute is used when there is an add-in or other code project associated with the file. + * + * @param function true indicates the name refers to a function. + */ + public void setFunction(boolean function){ + if (function) { + field_1_option_flag |= Option.OPT_FUNCTION_NAME; + } else { + field_1_option_flag &= (~Option.OPT_FUNCTION_NAME); + } + } - /** - * @return true if name has a formula (named range or defined value) - */ - public boolean hasFormula() { - return Option.isFormula(field_1_option_flag) && field_13_name_definition.getEncodedTokenSize() > 0; - } + /** + * @return true if name has a formula (named range or defined value) + */ + public boolean hasFormula() { + return Option.isFormula(field_1_option_flag) && field_13_name_definition.getEncodedTokenSize() > 0; + } - /** - * @return true if name is a command - */ - public boolean isCommandName() { - return (field_1_option_flag & Option.OPT_COMMAND_NAME) != 0; - } - /** - * @return true if function macro or command macro - */ - public boolean isMacro() { - return (field_1_option_flag & Option.OPT_MACRO) != 0; - } - /** - * @return true if array formula or user defined - */ - public boolean isComplexFunction() { - return (field_1_option_flag & Option.OPT_COMPLEX) != 0; - } + /** + * @return true if name is a command + */ + public boolean isCommandName() { + return (field_1_option_flag & Option.OPT_COMMAND_NAME) != 0; + } + /** + * @return true if function macro or command macro + */ + public boolean isMacro() { + return (field_1_option_flag & Option.OPT_MACRO) != 0; + } + /** + * @return true if array formula or user defined + */ + public boolean isComplexFunction() { + return (field_1_option_flag & Option.OPT_COMPLEX) != 0; + } - /** - * Convenience Function to determine if the name is a built-in name - * - * @return true, if the name is a built-in name - */ - public boolean isBuiltInName() - { - return ((field_1_option_flag & Option.OPT_BUILTIN) != 0); - } + /** + * Convenience Function to determine if the name is a built-in name + * + * @return true, if the name is a built-in name + */ + public boolean isBuiltInName() + { + return ((field_1_option_flag & Option.OPT_BUILTIN) != 0); + } - /** gets the name - * @return name - */ - public String getNameText(){ + /** gets the name + * @return name + */ + public String getNameText(){ - return isBuiltInName() ? translateBuiltInName(getBuiltInName()) : field_12_name_text; - } + return isBuiltInName() ? translateBuiltInName(getBuiltInName()) : field_12_name_text; + } - /** Gets the Built In Name - * @return the built in Name - */ - public byte getBuiltInName() - { - return field_12_built_in_code; - } + /** Gets the Built In Name + * @return the built in Name + */ + public byte getBuiltInName() + { + return field_12_built_in_code; + } - /** gets the definition, reference (Formula) - * @return the name formula. never null - */ - public Ptg[] getNameDefinition() { - return field_13_name_definition.getTokens(); - } + /** gets the definition, reference (Formula) + * @return the name formula. never null + */ + public Ptg[] getNameDefinition() { + return field_13_name_definition.getTokens(); + } - public void setNameDefinition(Ptg[] ptgs) { - field_13_name_definition = Formula.create(ptgs); - } + public void setNameDefinition(Ptg[] ptgs) { + field_13_name_definition = Formula.create(ptgs); + } - /** get the custom menu text - * @return custom menu text - */ - public String getCustomMenuText(){ - return field_14_custom_menu_text; - } + /** get the custom menu text + * @return custom menu text + */ + public String getCustomMenuText(){ + return field_14_custom_menu_text; + } - /** gets the description text - * @return description text - */ - public String getDescriptionText(){ - return field_15_description_text; - } + /** gets the description text + * @return description text + */ + public String getDescriptionText(){ + return field_15_description_text; + } - /** get the help topic text - * @return gelp topic text - */ - public String getHelpTopicText(){ - return field_16_help_topic_text; - } + /** get the help topic text + * @return gelp topic text + */ + public String getHelpTopicText(){ + return field_16_help_topic_text; + } - /** gets the status bar text - * @return status bar text - */ - public String getStatusBarText(){ - return field_17_status_bar_text; - } + /** gets the status bar text + * @return status bar text + */ + public String getStatusBarText(){ + return field_17_status_bar_text; + } /** * NameRecord can span into * * @param out a data output stream */ - @Override + @Override public void serialize(ContinuableRecordOutput out) { - int field_7_length_custom_menu = field_14_custom_menu_text.length(); - int field_8_length_description_text = field_15_description_text.length(); - int field_9_length_help_topic_text = field_16_help_topic_text.length(); - int field_10_length_status_bar_text = field_17_status_bar_text.length(); + int field_7_length_custom_menu = field_14_custom_menu_text.length(); + int field_8_length_description_text = field_15_description_text.length(); + int field_9_length_help_topic_text = field_16_help_topic_text.length(); + int field_10_length_status_bar_text = field_17_status_bar_text.length(); - // size defined below - out.writeShort(getOptionFlag()); - out.writeByte(getKeyboardShortcut()); - out.writeByte(getNameTextLength()); - // Note - formula size is not immediately before encoded formula, and does not include any array constant data - out.writeShort(field_13_name_definition.getEncodedTokenSize()); - out.writeShort(field_5_externSheetIndex_plus1); - out.writeShort(field_6_sheetNumber); - out.writeByte(field_7_length_custom_menu); - out.writeByte(field_8_length_description_text); - out.writeByte(field_9_length_help_topic_text); - out.writeByte(field_10_length_status_bar_text); - out.writeByte(field_11_nameIsMultibyte ? 1 : 0); + // size defined below + out.writeShort(getOptionFlag()); + out.writeByte(getKeyboardShortcut()); + out.writeByte(getNameTextLength()); + // Note - formula size is not immediately before encoded formula, and does not include any array constant data + out.writeShort(field_13_name_definition.getEncodedTokenSize()); + out.writeShort(field_5_externSheetIndex_plus1); + out.writeShort(field_6_sheetNumber); + out.writeByte(field_7_length_custom_menu); + out.writeByte(field_8_length_description_text); + out.writeByte(field_9_length_help_topic_text); + out.writeByte(field_10_length_status_bar_text); + out.writeByte(field_11_nameIsMultibyte ? 1 : 0); - if (isBuiltInName()) { - //can send the builtin name directly in - out.writeByte(field_12_built_in_code); - } else { - String nameText = field_12_name_text; - if (field_11_nameIsMultibyte) { - StringUtil.putUnicodeLE(nameText, out); - } else { - StringUtil.putCompressedUnicode(nameText, out); - } - } - field_13_name_definition.serializeTokens(out); - field_13_name_definition.serializeArrayConstantData(out); + if (isBuiltInName()) { + //can send the builtin name directly in + out.writeByte(field_12_built_in_code); + } else { + String nameText = field_12_name_text; + if (field_11_nameIsMultibyte) { + StringUtil.putUnicodeLE(nameText, out); + } else { + StringUtil.putCompressedUnicode(nameText, out); + } + } + field_13_name_definition.serializeTokens(out); + field_13_name_definition.serializeArrayConstantData(out); - StringUtil.putCompressedUnicode( getCustomMenuText(), out); - StringUtil.putCompressedUnicode( getDescriptionText(), out); - StringUtil.putCompressedUnicode( getHelpTopicText(), out); - StringUtil.putCompressedUnicode( getStatusBarText(), out); - } - private int getNameRawSize() { - if (isBuiltInName()) { - return 1; - } - int nChars = field_12_name_text.length(); - if(field_11_nameIsMultibyte) { - return 2 * nChars; - } - return nChars; - } + StringUtil.putCompressedUnicode( getCustomMenuText(), out); + StringUtil.putCompressedUnicode( getDescriptionText(), out); + StringUtil.putCompressedUnicode( getHelpTopicText(), out); + StringUtil.putCompressedUnicode( getStatusBarText(), out); + } + private int getNameRawSize() { + if (isBuiltInName()) { + return 1; + } + int nChars = field_12_name_text.length(); + if(field_11_nameIsMultibyte) { + return 2 * nChars; + } + return nChars; + } - int getDataSize() { - return 13 // 3 shorts + 7 bytes - + getNameRawSize() - + field_14_custom_menu_text.length() - + field_15_description_text.length() - + field_16_help_topic_text.length() - + field_17_status_bar_text.length() - + field_13_name_definition.getEncodedSize(); - } + int getDataSize() { + return 13 // 3 shorts + 7 bytes + + getNameRawSize() + + field_14_custom_menu_text.length() + + field_15_description_text.length() + + field_16_help_topic_text.length() + + field_17_status_bar_text.length() + + field_13_name_definition.getEncodedSize(); + } - /** gets the extern sheet number - * @return extern sheet index - */ - public int getExternSheetNumber(){ - Ptg[] tokens = field_13_name_definition.getTokens(); - if (tokens.length == 0) { - return 0; - } + /** gets the extern sheet number + * @return extern sheet index + */ + public int getExternSheetNumber(){ + Ptg[] tokens = field_13_name_definition.getTokens(); + if (tokens.length == 0) { + return 0; + } - Ptg ptg = tokens[0]; - if (ptg.getClass() == Area3DPtg.class){ - return ((Area3DPtg) ptg).getExternSheetIndex(); + Ptg ptg = tokens[0]; + if (ptg.getClass() == Area3DPtg.class){ + return ((Area3DPtg) ptg).getExternSheetIndex(); - } - if (ptg.getClass() == Ref3DPtg.class){ - return ((Ref3DPtg) ptg).getExternSheetIndex(); - } - return 0; - } + } + if (ptg.getClass() == Ref3DPtg.class){ + return ((Ref3DPtg) ptg).getExternSheetIndex(); + } + return 0; + } - /** - * called by the constructor, should set class level fields. Should throw - * runtime exception for bad/icomplete data. - * - * @param ris the RecordInputstream to read the record from - */ - public NameRecord(RecordInputStream ris) { + /** + * called by the constructor, should set class level fields. Should throw + * runtime exception for bad/icomplete data. + * + * @param ris the RecordInputstream to read the record from + */ + public NameRecord(RecordInputStream ris) { // YK: Formula data can span into continue records, for example, // when containing a large array of strings. See Bugzilla 50244 @@ -466,151 +466,151 @@ public final class NameRecord extends ContinuableRecord { byte[] remainder = ris.readAllContinuedRemainder(); LittleEndianInput in = new LittleEndianByteArrayInputStream(remainder); - field_1_option_flag = in.readShort(); - field_2_keyboard_shortcut = in.readByte(); - int field_3_length_name_text = in.readUByte(); - int field_4_length_name_definition = in.readShort(); - field_5_externSheetIndex_plus1 = in.readShort(); - field_6_sheetNumber = in.readUShort(); - int f7_customMenuLen = in.readUByte(); - int f8_descriptionTextLen = in.readUByte(); - int f9_helpTopicTextLen = in.readUByte(); - int f10_statusBarTextLen = in.readUByte(); + field_1_option_flag = in.readShort(); + field_2_keyboard_shortcut = in.readByte(); + int field_3_length_name_text = in.readUByte(); + int field_4_length_name_definition = in.readShort(); + field_5_externSheetIndex_plus1 = in.readShort(); + field_6_sheetNumber = in.readUShort(); + int f7_customMenuLen = in.readUByte(); + int f8_descriptionTextLen = in.readUByte(); + int f9_helpTopicTextLen = in.readUByte(); + int f10_statusBarTextLen = in.readUByte(); - //store the name in byte form if it's a built-in name - field_11_nameIsMultibyte = (in.readByte() != 0); - if (isBuiltInName()) { - field_12_built_in_code = in.readByte(); - } else { - if (field_11_nameIsMultibyte) { - field_12_name_text = StringUtil.readUnicodeLE(in, field_3_length_name_text); - } else { - field_12_name_text = StringUtil.readCompressedUnicode(in, field_3_length_name_text); - } - } + //store the name in byte form if it's a built-in name + field_11_nameIsMultibyte = (in.readByte() != 0); + if (isBuiltInName()) { + field_12_built_in_code = in.readByte(); + } else { + if (field_11_nameIsMultibyte) { + field_12_name_text = StringUtil.readUnicodeLE(in, field_3_length_name_text); + } else { + field_12_name_text = StringUtil.readCompressedUnicode(in, field_3_length_name_text); + } + } - int nBytesAvailable = in.available() - (f7_customMenuLen - + f8_descriptionTextLen + f9_helpTopicTextLen + f10_statusBarTextLen); - field_13_name_definition = Formula.read(field_4_length_name_definition, in, nBytesAvailable); + int nBytesAvailable = in.available() - (f7_customMenuLen + + f8_descriptionTextLen + f9_helpTopicTextLen + f10_statusBarTextLen); + field_13_name_definition = Formula.read(field_4_length_name_definition, in, nBytesAvailable); - //Who says that this can only ever be compressed unicode??? - field_14_custom_menu_text = StringUtil.readCompressedUnicode(in, f7_customMenuLen); - field_15_description_text = StringUtil.readCompressedUnicode(in, f8_descriptionTextLen); - field_16_help_topic_text = StringUtil.readCompressedUnicode(in, f9_helpTopicTextLen); - field_17_status_bar_text = StringUtil.readCompressedUnicode(in, f10_statusBarTextLen); - } + //Who says that this can only ever be compressed unicode??? + field_14_custom_menu_text = StringUtil.readCompressedUnicode(in, f7_customMenuLen); + field_15_description_text = StringUtil.readCompressedUnicode(in, f8_descriptionTextLen); + field_16_help_topic_text = StringUtil.readCompressedUnicode(in, f9_helpTopicTextLen); + field_17_status_bar_text = StringUtil.readCompressedUnicode(in, f10_statusBarTextLen); + } - /** - * return the non static version of the id for this record. - */ - @Override + /** + * return the non static version of the id for this record. + */ + @Override public short getSid() { - return sid; - } - /* - 20 00 - 00 - 01 - 1A 00 // sz = 0x1A = 26 - 00 00 - 01 00 - 00 - 00 - 00 - 00 - 00 // unicode flag - 07 // name + return sid; + } + /* + 20 00 + 00 + 01 + 1A 00 // sz = 0x1A = 26 + 00 00 + 01 00 + 00 + 00 + 00 + 00 + 00 // unicode flag + 07 // name - 29 17 00 3B 00 00 00 00 FF FF 00 00 02 00 3B 00 //{ 26 - 00 07 00 07 00 00 00 FF 00 10 // } + 29 17 00 3B 00 00 00 00 FF FF 00 00 02 00 3B 00 //{ 26 + 00 07 00 07 00 00 00 FF 00 10 // } - 20 00 - 00 - 01 - 0B 00 // sz = 0xB = 11 - 00 00 - 01 00 - 00 - 00 - 00 - 00 - 00 // unicode flag - 07 // name + 20 00 + 00 + 01 + 0B 00 // sz = 0xB = 11 + 00 00 + 01 00 + 00 + 00 + 00 + 00 + 00 // unicode flag + 07 // name - 3B 00 00 07 00 07 00 00 00 FF 00 // { 11 } + 3B 00 00 07 00 07 00 00 00 FF 00 // { 11 } */ - /* - 18, 00, - 1B, 00, + /* + 18, 00, + 1B, 00, - 20, 00, - 00, - 01, - 0B, 00, - 00, - 00, - 00, - 00, - 00, - 07, - 3B 00 00 07 00 07 00 00 00 FF 00 ] - */ + 20, 00, + 00, + 01, + 0B, 00, + 00, + 00, + 00, + 00, + 00, + 07, + 3B 00 00 07 00 07 00 00 00 FF 00 ] + */ - /**Creates a human readable name for built in types - * @return Unknown if the built-in name cannot be translated - */ - private static String translateBuiltInName(byte name) - { - switch (name) - { - case NameRecord.BUILTIN_AUTO_ACTIVATE : return "Auto_Activate"; - case NameRecord.BUILTIN_AUTO_CLOSE : return "Auto_Close"; - case NameRecord.BUILTIN_AUTO_DEACTIVATE : return "Auto_Deactivate"; - case NameRecord.BUILTIN_AUTO_OPEN : return "Auto_Open"; - case NameRecord.BUILTIN_CONSOLIDATE_AREA : return "Consolidate_Area"; - case NameRecord.BUILTIN_CRITERIA : return "Criteria"; - case NameRecord.BUILTIN_DATABASE : return "Database"; - case NameRecord.BUILTIN_DATA_FORM : return "Data_Form"; - case NameRecord.BUILTIN_PRINT_AREA : return "Print_Area"; - case NameRecord.BUILTIN_PRINT_TITLE : return "Print_Titles"; - case NameRecord.BUILTIN_RECORDER : return "Recorder"; - case NameRecord.BUILTIN_SHEET_TITLE : return "Sheet_Title"; - case NameRecord.BUILTIN_FILTER_DB : return "_FilterDatabase"; + /**Creates a human readable name for built in types + * @return Unknown if the built-in name cannot be translated + */ + private static String translateBuiltInName(byte name) + { + switch (name) + { + case NameRecord.BUILTIN_AUTO_ACTIVATE : return "Auto_Activate"; + case NameRecord.BUILTIN_AUTO_CLOSE : return "Auto_Close"; + case NameRecord.BUILTIN_AUTO_DEACTIVATE : return "Auto_Deactivate"; + case NameRecord.BUILTIN_AUTO_OPEN : return "Auto_Open"; + case NameRecord.BUILTIN_CONSOLIDATE_AREA : return "Consolidate_Area"; + case NameRecord.BUILTIN_CRITERIA : return "Criteria"; + case NameRecord.BUILTIN_DATABASE : return "Database"; + case NameRecord.BUILTIN_DATA_FORM : return "Data_Form"; + case NameRecord.BUILTIN_PRINT_AREA : return "Print_Area"; + case NameRecord.BUILTIN_PRINT_TITLE : return "Print_Titles"; + case NameRecord.BUILTIN_RECORDER : return "Recorder"; + case NameRecord.BUILTIN_SHEET_TITLE : return "Sheet_Title"; + case NameRecord.BUILTIN_FILTER_DB : return "_FilterDatabase"; - } + } - return "Unknown"; - } + return "Unknown"; + } - @Override - public NameRecord copy() { - return new NameRecord(this); - } + @Override + public NameRecord copy() { + return new NameRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.NAME; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.NAME; + } - @Override - public Map> getGenericProperties() { - final Map> m = new LinkedHashMap<>(); - m.put("dataSize", this::getDataSize); - m.put("optionFlag", this::getOptionFlag); - m.put("keyboardShortcut", this::getKeyboardShortcut); - m.put("externSheetIndex", () -> field_5_externSheetIndex_plus1); - m.put("sheetNumber", this::getSheetNumber); - m.put("nameIsMultibyte", () -> field_11_nameIsMultibyte); - m.put("builtInName", this::getBuiltInName); - m.put("nameLength", this::getNameTextLength); - m.put("nameText", this::getNameText); - m.put("formula", this::getNameDefinition); - m.put("customMenuText", this::getCustomMenuText); - m.put("descriptionText", this::getDescriptionText); - m.put("helpTopicText", this::getHelpTopicText); - m.put("statusBarText", this::getStatusBarText); - return Collections.unmodifiableMap(m); - } + @Override + public Map> getGenericProperties() { + final Map> m = new LinkedHashMap<>(); + m.put("dataSize", this::getDataSize); + m.put("optionFlag", this::getOptionFlag); + m.put("keyboardShortcut", this::getKeyboardShortcut); + m.put("externSheetIndex", () -> field_5_externSheetIndex_plus1); + m.put("sheetNumber", this::getSheetNumber); + m.put("nameIsMultibyte", () -> field_11_nameIsMultibyte); + m.put("builtInName", this::getBuiltInName); + m.put("nameLength", this::getNameTextLength); + m.put("nameText", this::getNameText); + m.put("formula", this::getNameDefinition); + m.put("customMenuText", this::getCustomMenuText); + m.put("descriptionText", this::getDescriptionText); + m.put("helpTopicText", this::getHelpTopicText); + m.put("statusBarText", this::getStatusBarText); + return Collections.unmodifiableMap(m); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/NoteRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/NoteRecord.java index c89ac5dece..60f48f7d15 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/NoteRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/NoteRecord.java @@ -28,237 +28,237 @@ import org.apache.poi.util.StringUtil; * NOTE: Comment Associated with a Cell (0x001C) */ public final class NoteRecord extends StandardRecord { - public static final short sid = 0x001C; + public static final short sid = 0x001C; - public static final NoteRecord[] EMPTY_ARRAY = { }; + public static final NoteRecord[] EMPTY_ARRAY = { }; - /** - * Flag indicating that the comment is hidden (default) - */ - public static final short NOTE_HIDDEN = 0x0; + /** + * Flag indicating that the comment is hidden (default) + */ + public static final short NOTE_HIDDEN = 0x0; - /** - * Flag indicating that the comment is visible - */ - public static final short NOTE_VISIBLE = 0x2; + /** + * Flag indicating that the comment is visible + */ + public static final short NOTE_VISIBLE = 0x2; - private static final Byte DEFAULT_PADDING = (byte) 0; + private static final Byte DEFAULT_PADDING = (byte) 0; - private int field_1_row; - private int field_2_col; - private short field_3_flags; - private int field_4_shapeid; - private boolean field_5_hasMultibyte; - private String field_6_author; + private int field_1_row; + private int field_2_col; + private short field_3_flags; + private int field_4_shapeid; + private boolean field_5_hasMultibyte; + private String field_6_author; - /** - * Saves padding byte value to reduce delta during round-trip serialization.
- * - * The documentation is not clear about how padding should work. In any case - * Excel(2007) does something different. - */ - private Byte field_7_padding; + /** + * Saves padding byte value to reduce delta during round-trip serialization.
+ * + * The documentation is not clear about how padding should work. In any case + * Excel(2007) does something different. + */ + private Byte field_7_padding; - /** - * Construct a new NoteRecord and - * fill its data with the default values - */ - public NoteRecord() { - field_6_author = ""; - field_3_flags = 0; - field_7_padding = DEFAULT_PADDING; // seems to be always present regardless of author text - } + /** + * Construct a new NoteRecord and + * fill its data with the default values + */ + public NoteRecord() { + field_6_author = ""; + field_3_flags = 0; + field_7_padding = DEFAULT_PADDING; // seems to be always present regardless of author text + } - public NoteRecord(NoteRecord other) { - super(other); - field_1_row = other.field_1_row; - field_2_col = other.field_2_col; - field_3_flags = other.field_3_flags; - field_4_shapeid = other.field_4_shapeid; - field_5_hasMultibyte = other.field_5_hasMultibyte; - field_6_author = other.field_6_author; - field_7_padding = other.field_7_padding; - } + public NoteRecord(NoteRecord other) { + super(other); + field_1_row = other.field_1_row; + field_2_col = other.field_2_col; + field_3_flags = other.field_3_flags; + field_4_shapeid = other.field_4_shapeid; + field_5_hasMultibyte = other.field_5_hasMultibyte; + field_6_author = other.field_6_author; + field_7_padding = other.field_7_padding; + } - /** - * @return id of this record. - */ - public short getSid() { - return sid; - } + /** + * @return id of this record. + */ + public short getSid() { + return sid; + } - /** - * Read the record data from the supplied RecordInputStream - * - * @param in the RecordInputStream to read from - */ - public NoteRecord(RecordInputStream in) { - field_1_row = in.readUShort(); - field_2_col = in.readShort(); - field_3_flags = in.readShort(); - field_4_shapeid = in.readUShort(); - int length = in.readShort(); - field_5_hasMultibyte = in.readByte() != 0x00; - if (field_5_hasMultibyte) { - field_6_author = StringUtil.readUnicodeLE(in, length); - } else { - field_6_author = StringUtil.readCompressedUnicode(in, length); - } - if (in.available() == 1) { - field_7_padding = in.readByte(); - } else if (in.available() == 2 && length == 0) { - // If there's no author, may be double padded + /** + * Read the record data from the supplied RecordInputStream + * + * @param in the RecordInputStream to read from + */ + public NoteRecord(RecordInputStream in) { + field_1_row = in.readUShort(); + field_2_col = in.readShort(); + field_3_flags = in.readShort(); + field_4_shapeid = in.readUShort(); + int length = in.readShort(); + field_5_hasMultibyte = in.readByte() != 0x00; + if (field_5_hasMultibyte) { + field_6_author = StringUtil.readUnicodeLE(in, length); + } else { + field_6_author = StringUtil.readCompressedUnicode(in, length); + } + if (in.available() == 1) { + field_7_padding = in.readByte(); + } else if (in.available() == 2 && length == 0) { + // If there's no author, may be double padded field_7_padding = in.readByte(); in.readByte(); - } - } + } + } - public void serialize(LittleEndianOutput out) { - out.writeShort(field_1_row); - out.writeShort(field_2_col); - out.writeShort(field_3_flags); - out.writeShort(field_4_shapeid); - out.writeShort(field_6_author.length()); - out.writeByte(field_5_hasMultibyte ? 0x01 : 0x00); - if (field_5_hasMultibyte) { - StringUtil.putUnicodeLE(field_6_author, out); - } else { - StringUtil.putCompressedUnicode(field_6_author, out); - } - if (field_7_padding != null) { - out.writeByte(field_7_padding.intValue()); - } - } + public void serialize(LittleEndianOutput out) { + out.writeShort(field_1_row); + out.writeShort(field_2_col); + out.writeShort(field_3_flags); + out.writeShort(field_4_shapeid); + out.writeShort(field_6_author.length()); + out.writeByte(field_5_hasMultibyte ? 0x01 : 0x00); + if (field_5_hasMultibyte) { + StringUtil.putUnicodeLE(field_6_author, out); + } else { + StringUtil.putCompressedUnicode(field_6_author, out); + } + if (field_7_padding != null) { + out.writeByte(field_7_padding.intValue()); + } + } - protected int getDataSize() { - return 11 // 5 shorts + 1 byte - + field_6_author.length() * (field_5_hasMultibyte ? 2 : 1) - + (field_7_padding == null ? 0 : 1); - } + protected int getDataSize() { + return 11 // 5 shorts + 1 byte + + field_6_author.length() * (field_5_hasMultibyte ? 2 : 1) + + (field_7_padding == null ? 0 : 1); + } - /** - * Return the row that contains the comment - * - * @return the row that contains the comment - */ - public int getRow() { - return field_1_row; - } + /** + * Return the row that contains the comment + * + * @return the row that contains the comment + */ + public int getRow() { + return field_1_row; + } - /** - * Specify the row that contains the comment - * - * @param row the row that contains the comment - */ - public void setRow(int row) { - field_1_row = row; - } + /** + * Specify the row that contains the comment + * + * @param row the row that contains the comment + */ + public void setRow(int row) { + field_1_row = row; + } - /** - * Return the column that contains the comment - * - * @return the column that contains the comment - */ - public int getColumn() { - return field_2_col; - } + /** + * Return the column that contains the comment + * + * @return the column that contains the comment + */ + public int getColumn() { + return field_2_col; + } - /** - * Specify the column that contains the comment - * - * @param col the column that contains the comment - */ - public void setColumn(int col) { - field_2_col = col; - } + /** + * Specify the column that contains the comment + * + * @param col the column that contains the comment + */ + public void setColumn(int col) { + field_2_col = col; + } - /** - * Options flags. - * - * @return the options flag - * @see #NOTE_VISIBLE - * @see #NOTE_HIDDEN - */ - public short getFlags() { - return field_3_flags; - } + /** + * Options flags. + * + * @return the options flag + * @see #NOTE_VISIBLE + * @see #NOTE_HIDDEN + */ + public short getFlags() { + return field_3_flags; + } - /** - * Options flag - * - * @param flags the options flag - * @see #NOTE_VISIBLE - * @see #NOTE_HIDDEN - */ - public void setFlags(short flags) { - field_3_flags = flags; - } + /** + * Options flag + * + * @param flags the options flag + * @see #NOTE_VISIBLE + * @see #NOTE_HIDDEN + */ + public void setFlags(short flags) { + field_3_flags = flags; + } - /** - * For unit testing only! - * - * @return true, if author element uses multi byte - */ - boolean authorIsMultibyte() { - return field_5_hasMultibyte; - } + /** + * For unit testing only! + * + * @return true, if author element uses multi byte + */ + boolean authorIsMultibyte() { + return field_5_hasMultibyte; + } - /** - * Object id for OBJ record that contains the comment - * - * @return the Object id for OBJ record that contains the comment - */ - public int getShapeId() { - return field_4_shapeid; - } + /** + * Object id for OBJ record that contains the comment + * + * @return the Object id for OBJ record that contains the comment + */ + public int getShapeId() { + return field_4_shapeid; + } - /** - * Object id for OBJ record that contains the comment - * - * @param id the Object id for OBJ record that contains the comment - */ - public void setShapeId(int id) { - field_4_shapeid = id; - } + /** + * Object id for OBJ record that contains the comment + * + * @param id the Object id for OBJ record that contains the comment + */ + public void setShapeId(int id) { + field_4_shapeid = id; + } - /** - * Name of the original comment author - * - * @return the name of the original author of the comment - */ - public String getAuthor() { - return field_6_author; - } + /** + * Name of the original comment author + * + * @return the name of the original author of the comment + */ + public String getAuthor() { + return field_6_author; + } - /** - * Name of the original comment author - * - * @param author the name of the original author of the comment - */ - public void setAuthor(String author) { - field_6_author = author; - field_5_hasMultibyte = StringUtil.hasMultibyte(author); - } + /** + * Name of the original comment author + * + * @param author the name of the original author of the comment + */ + public void setAuthor(String author) { + field_6_author = author; + field_5_hasMultibyte = StringUtil.hasMultibyte(author); + } - @Override - public NoteRecord copy() { - return new NoteRecord(this); - } + @Override + public NoteRecord copy() { + return new NoteRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.NOTE; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.NOTE; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "row", this::getRow, - "column", this::getColumn, - "flags", this::getFlags, - "shapeId", this::getShapeId, - "author", this::getAuthor - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "row", this::getRow, + "column", this::getColumn, + "flags", this::getFlags, + "shapeId", this::getShapeId, + "author", this::getAuthor + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/NoteStructureSubRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/NoteStructureSubRecord.java index 3adff3856d..67256f11ac 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/NoteStructureSubRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/NoteStructureSubRecord.java @@ -85,7 +85,7 @@ public final class NoteStructureSubRecord extends SubRecord { out.write(reserved); } - @Override + @Override protected int getDataSize() { return reserved.length; } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/PageBreakRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/PageBreakRecord.java index 402c04d02c..eda43c94e2 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/PageBreakRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/PageBreakRecord.java @@ -124,7 +124,7 @@ public abstract class PageBreakRecord extends StandardRecord { } public boolean isEmpty() { - return _breaks.isEmpty(); + return _breaks.isEmpty(); } protected int getDataSize() { return 2 + _breaks.size() * Break.ENCODED_SIZE; diff --git a/poi/src/main/java/org/apache/poi/hssf/record/RKRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/RKRecord.java index 183b5e3f7d..fb7cc32cec 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/RKRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/RKRecord.java @@ -75,17 +75,17 @@ public final class RKRecord extends CellRecord { @Override protected String getRecordName() { - return "RK"; + return "RK"; } @Override protected void serializeValue(LittleEndianOutput out) { - out.writeInt(field_4_rk_number); + out.writeInt(field_4_rk_number); } @Override protected int getValueDataSize() { - return 4; + return 4; } @Override diff --git a/poi/src/main/java/org/apache/poi/hssf/record/RecalcIdRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/RecalcIdRecord.java index 2a0481c62d..c50428e829 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/RecalcIdRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/RecalcIdRecord.java @@ -56,9 +56,9 @@ public final class RecalcIdRecord extends StandardRecord { } public RecalcIdRecord(RecordInputStream in) { - in.readUShort(); // field 'rt' should have value 0x01C1, but Excel doesn't care during reading - _reserved0 = in.readUShort(); - _engineId = in.readInt(); + in.readUShort(); // field 'rt' should have value 0x01C1, but Excel doesn't care during reading + _reserved0 = in.readUShort(); + _engineId = in.readInt(); } public boolean isNeeded() { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/RecordBase.java b/poi/src/main/java/org/apache/poi/hssf/record/RecordBase.java index 40907ec7e7..55f18b921d 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/RecordBase.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/RecordBase.java @@ -21,22 +21,22 @@ package org.apache.poi.hssf.record; * Common base class of {@link Record} and {@link org.apache.poi.hssf.record.aggregates.RecordAggregate} */ public abstract class RecordBase { - /** - * called by the class that is responsible for writing this sucker. - * Subclasses should implement this so that their data is passed back in a - * byte array. - * - * @param offset to begin writing at - * @param data byte array containing instance data - * @return number of bytes written - */ - public abstract int serialize(int offset, byte[] data); + /** + * called by the class that is responsible for writing this sucker. + * Subclasses should implement this so that their data is passed back in a + * byte array. + * + * @param offset to begin writing at + * @param data byte array containing instance data + * @return number of bytes written + */ + public abstract int serialize(int offset, byte[] data); - /** - * gives the current serialized size of the record. Should include the sid - * and reclength (4 bytes). - * - * @return the record size - */ - public abstract int getRecordSize(); + /** + * gives the current serialized size of the record. Should include the sid + * and reclength (4 bytes). + * + * @return the record size + */ + public abstract int getRecordSize(); } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/RecordFactoryInputStream.java b/poi/src/main/java/org/apache/poi/hssf/record/RecordFactoryInputStream.java index a475269562..46077788b4 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/RecordFactoryInputStream.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/RecordFactoryInputStream.java @@ -41,75 +41,75 @@ import org.apache.poi.util.RecordFormatException; */ public final class RecordFactoryInputStream { - /** - * Keeps track of the sizes of the initial records up to and including {@link FilePassRecord} - * Needed for protected files because each byte is encrypted with respect to its absolute - * position from the start of the stream. - */ - private static final class StreamEncryptionInfo { - private final int _initialRecordsSize; - private final FilePassRecord _filePassRec; - private final Record _lastRecord; - private final boolean _hasBOFRecord; + /** + * Keeps track of the sizes of the initial records up to and including {@link FilePassRecord} + * Needed for protected files because each byte is encrypted with respect to its absolute + * position from the start of the stream. + */ + private static final class StreamEncryptionInfo { + private final int _initialRecordsSize; + private final FilePassRecord _filePassRec; + private final Record _lastRecord; + private final boolean _hasBOFRecord; - public StreamEncryptionInfo(RecordInputStream rs, List outputRecs) { - Record rec; - rs.nextRecord(); - int recSize = 4 + rs.remaining(); - rec = RecordFactory.createSingleRecord(rs); - outputRecs.add(rec); - FilePassRecord fpr = null; - if (rec instanceof BOFRecord) { - _hasBOFRecord = true; - - // Fetch the next record, and see if it indicates whether - // the document is encrypted or not - if (rs.hasNextRecord()) { - rs.nextRecord(); - rec = RecordFactory.createSingleRecord(rs); - recSize += rec.getRecordSize(); - outputRecs.add(rec); - - // Encrypted is normally BOF then FILEPASS - // May sometimes be BOF, WRITEPROTECT, FILEPASS - if (rec instanceof WriteProtectRecord && rs.hasNextRecord()) { - rs.nextRecord(); - rec = RecordFactory.createSingleRecord(rs); - recSize += rec.getRecordSize(); - outputRecs.add(rec); - } - - // If it's a FILEPASS, track it specifically - if (rec instanceof FilePassRecord) { - fpr = (FilePassRecord) rec; - } + public StreamEncryptionInfo(RecordInputStream rs, List outputRecs) { + Record rec; + rs.nextRecord(); + int recSize = 4 + rs.remaining(); + rec = RecordFactory.createSingleRecord(rs); + outputRecs.add(rec); + FilePassRecord fpr = null; + if (rec instanceof BOFRecord) { + _hasBOFRecord = true; + + // Fetch the next record, and see if it indicates whether + // the document is encrypted or not + if (rs.hasNextRecord()) { + rs.nextRecord(); + rec = RecordFactory.createSingleRecord(rs); + recSize += rec.getRecordSize(); + outputRecs.add(rec); + + // Encrypted is normally BOF then FILEPASS + // May sometimes be BOF, WRITEPROTECT, FILEPASS + if (rec instanceof WriteProtectRecord && rs.hasNextRecord()) { + rs.nextRecord(); + rec = RecordFactory.createSingleRecord(rs); + recSize += rec.getRecordSize(); + outputRecs.add(rec); + } + + // If it's a FILEPASS, track it specifically + if (rec instanceof FilePassRecord) { + fpr = (FilePassRecord) rec; + } - // workbook not encrypted (typical case) - if (rec instanceof EOFRecord) { - // A workbook stream is never empty, so crash instead - // of trying to keep track of nesting level - throw new IllegalStateException("Nothing between BOF and EOF"); - } - } - } else { - // Invalid in a normal workbook stream. - // However, some test cases work on sub-sections of - // the workbook stream that do not begin with BOF - _hasBOFRecord = false; - } - _initialRecordsSize = recSize; - _filePassRec = fpr; - _lastRecord = rec; - } + // workbook not encrypted (typical case) + if (rec instanceof EOFRecord) { + // A workbook stream is never empty, so crash instead + // of trying to keep track of nesting level + throw new IllegalStateException("Nothing between BOF and EOF"); + } + } + } else { + // Invalid in a normal workbook stream. + // However, some test cases work on sub-sections of + // the workbook stream that do not begin with BOF + _hasBOFRecord = false; + } + _initialRecordsSize = recSize; + _filePassRec = fpr; + _lastRecord = rec; + } - @SuppressWarnings({"squid:S2068"}) - public RecordInputStream createDecryptingStream(InputStream original) { + @SuppressWarnings({"squid:S2068"}) + public RecordInputStream createDecryptingStream(InputStream original) { String userPassword = Biff8EncryptionKey.getCurrentUserPassword(); - if (userPassword == null) { - userPassword = Decryptor.DEFAULT_PASSWORD; - } + if (userPassword == null) { + userPassword = Decryptor.DEFAULT_PASSWORD; + } - EncryptionInfo info = _filePassRec.getEncryptionInfo(); + EncryptionInfo info = _filePassRec.getEncryptionInfo(); try { if (!info.getDecryptor().verifyPassword(userPassword)) { throw new EncryptedDocumentException( @@ -120,250 +120,250 @@ public final class RecordFactoryInputStream { throw new EncryptedDocumentException(e); } - return new RecordInputStream(original, info, _initialRecordsSize); - } + return new RecordInputStream(original, info, _initialRecordsSize); + } - public boolean hasEncryption() { - return _filePassRec != null; - } + public boolean hasEncryption() { + return _filePassRec != null; + } - /** - * @return last record scanned while looking for encryption info. - * This will typically be the first or second record read. Possibly null - * if stream was empty - */ - public Record getLastRecord() { - return _lastRecord; - } + /** + * @return last record scanned while looking for encryption info. + * This will typically be the first or second record read. Possibly null + * if stream was empty + */ + public Record getLastRecord() { + return _lastRecord; + } - /** - * false in some test cases - */ - public boolean hasBOFRecord() { - return _hasBOFRecord; - } - } + /** + * false in some test cases + */ + public boolean hasBOFRecord() { + return _hasBOFRecord; + } + } - private final RecordInputStream _recStream; - private final boolean _shouldIncludeContinueRecords; + private final RecordInputStream _recStream; + private final boolean _shouldIncludeContinueRecords; - /** - * Temporarily stores a group of {@link Record}s, for future return by {@link #nextRecord()}. - * This is used at the start of the workbook stream, and also when the most recently read - * underlying record is a {@link MulRKRecord} - */ - private Record[] _unreadRecordBuffer; + /** + * Temporarily stores a group of {@link Record}s, for future return by {@link #nextRecord()}. + * This is used at the start of the workbook stream, and also when the most recently read + * underlying record is a {@link MulRKRecord} + */ + private Record[] _unreadRecordBuffer; - /** - * used to help iterating over the unread records - */ - private int _unreadRecordIndex = -1; + /** + * used to help iterating over the unread records + */ + private int _unreadRecordIndex = -1; - /** - * The most recent record that we gave to the user - */ - private Record _lastRecord; - /** - * The most recent DrawingRecord seen - */ - private DrawingRecord _lastDrawingRecord = new DrawingRecord(); + /** + * The most recent record that we gave to the user + */ + private Record _lastRecord; + /** + * The most recent DrawingRecord seen + */ + private DrawingRecord _lastDrawingRecord = new DrawingRecord(); - private int _bofDepth; + private int _bofDepth; - private boolean _lastRecordWasEOFLevelZero; + private boolean _lastRecordWasEOFLevelZero; - /** - * @param in the InputStream to read from - * - * @param shouldIncludeContinueRecords caller can pass false if loose - * {@link ContinueRecord}s should be skipped (this is sometimes useful in event based - * processing). - */ - public RecordFactoryInputStream(InputStream in, boolean shouldIncludeContinueRecords) { - RecordInputStream rs = new RecordInputStream(in); - List records = new ArrayList<>(); - StreamEncryptionInfo sei = new StreamEncryptionInfo(rs, records); - if (sei.hasEncryption()) { - rs = sei.createDecryptingStream(in); - } else { - // typical case - non-encrypted stream - } + /** + * @param in the InputStream to read from + * + * @param shouldIncludeContinueRecords caller can pass false if loose + * {@link ContinueRecord}s should be skipped (this is sometimes useful in event based + * processing). + */ + public RecordFactoryInputStream(InputStream in, boolean shouldIncludeContinueRecords) { + RecordInputStream rs = new RecordInputStream(in); + List records = new ArrayList<>(); + StreamEncryptionInfo sei = new StreamEncryptionInfo(rs, records); + if (sei.hasEncryption()) { + rs = sei.createDecryptingStream(in); + } else { + // typical case - non-encrypted stream + } - if (!records.isEmpty()) { - _unreadRecordBuffer = new Record[records.size()]; - records.toArray(_unreadRecordBuffer); - _unreadRecordIndex =0; - } - _recStream = rs; - _shouldIncludeContinueRecords = shouldIncludeContinueRecords; - _lastRecord = sei.getLastRecord(); + if (!records.isEmpty()) { + _unreadRecordBuffer = new Record[records.size()]; + records.toArray(_unreadRecordBuffer); + _unreadRecordIndex =0; + } + _recStream = rs; + _shouldIncludeContinueRecords = shouldIncludeContinueRecords; + _lastRecord = sei.getLastRecord(); - /* - * How to recognise end of stream? - * In the best case, the underlying input stream (in) ends just after the last EOF record - * Usually however, the stream is padded with an arbitrary byte count. Excel and most apps - * reliably use zeros for padding and if this were always the case, this code could just - * skip all the (zero sized) records with sid==0. However, bug 46987 shows a file with - * non-zero padding that is read OK by Excel (Excel also fixes the padding). - * - * So to properly detect the workbook end of stream, this code has to identify the last - * EOF record. This is not so easy because the worbook bof+eof pair do not bracket the - * whole stream. The worksheets follow the workbook, but it is not easy to tell how many - * sheet sub-streams should be present. Hence we are looking for an EOF record that is not - * immediately followed by a BOF record. One extra complication is that bof+eof sub- - * streams can be nested within worksheet streams and it's not clear in these cases what - * record might follow any EOF record. So we also need to keep track of the bof/eof - * nesting level. - */ - _bofDepth = sei.hasBOFRecord() ? 1 : 0; - _lastRecordWasEOFLevelZero = false; - } + /* + * How to recognise end of stream? + * In the best case, the underlying input stream (in) ends just after the last EOF record + * Usually however, the stream is padded with an arbitrary byte count. Excel and most apps + * reliably use zeros for padding and if this were always the case, this code could just + * skip all the (zero sized) records with sid==0. However, bug 46987 shows a file with + * non-zero padding that is read OK by Excel (Excel also fixes the padding). + * + * So to properly detect the workbook end of stream, this code has to identify the last + * EOF record. This is not so easy because the worbook bof+eof pair do not bracket the + * whole stream. The worksheets follow the workbook, but it is not easy to tell how many + * sheet sub-streams should be present. Hence we are looking for an EOF record that is not + * immediately followed by a BOF record. One extra complication is that bof+eof sub- + * streams can be nested within worksheet streams and it's not clear in these cases what + * record might follow any EOF record. So we also need to keep track of the bof/eof + * nesting level. + */ + _bofDepth = sei.hasBOFRecord() ? 1 : 0; + _lastRecordWasEOFLevelZero = false; + } - /** - * @return the next (complete) record from the stream, or null if there are no more. - */ - public Record nextRecord() { - Record r; - r = getNextUnreadRecord(); - if (r != null) { - // found an unread record - return r; - } - while (true) { - if (!_recStream.hasNextRecord()) { - // recStream is exhausted; - return null; - } + /** + * @return the next (complete) record from the stream, or null if there are no more. + */ + public Record nextRecord() { + Record r; + r = getNextUnreadRecord(); + if (r != null) { + // found an unread record + return r; + } + while (true) { + if (!_recStream.hasNextRecord()) { + // recStream is exhausted; + return null; + } - if (_lastRecordWasEOFLevelZero) { - // Potential place for ending the workbook stream - // Check that the next record is not BOFRecord(0x0809) - // Normally the input stream contains only zero padding after the last EOFRecord, - // but bug 46987 and 48068 suggests that the padding may be garbage. - // This code relies on the padding bytes not starting with BOFRecord.sid - if (_recStream.getNextSid() != BOFRecord.sid) { - return null; - } - // else - another sheet substream starting here - } + if (_lastRecordWasEOFLevelZero) { + // Potential place for ending the workbook stream + // Check that the next record is not BOFRecord(0x0809) + // Normally the input stream contains only zero padding after the last EOFRecord, + // but bug 46987 and 48068 suggests that the padding may be garbage. + // This code relies on the padding bytes not starting with BOFRecord.sid + if (_recStream.getNextSid() != BOFRecord.sid) { + return null; + } + // else - another sheet substream starting here + } // step underlying RecordInputStream to the next record _recStream.nextRecord(); - r = readNextRecord(); - if (r == null) { - // some record types may get skipped (e.g. DBCellRecord and ContinueRecord) - continue; - } - return r; - } - } + r = readNextRecord(); + if (r == null) { + // some record types may get skipped (e.g. DBCellRecord and ContinueRecord) + continue; + } + return r; + } + } - /** - * @return the next {@link Record} from the multiple record group as expanded from - * a recently read {@link MulRKRecord}. null if not present. - */ - private Record getNextUnreadRecord() { - if (_unreadRecordBuffer != null) { - int ix = _unreadRecordIndex; - if (ix < _unreadRecordBuffer.length) { - Record result = _unreadRecordBuffer[ix]; - _unreadRecordIndex = ix + 1; - return result; - } - _unreadRecordIndex = -1; - _unreadRecordBuffer = null; - } - return null; - } + /** + * @return the next {@link Record} from the multiple record group as expanded from + * a recently read {@link MulRKRecord}. null if not present. + */ + private Record getNextUnreadRecord() { + if (_unreadRecordBuffer != null) { + int ix = _unreadRecordIndex; + if (ix < _unreadRecordBuffer.length) { + Record result = _unreadRecordBuffer[ix]; + _unreadRecordIndex = ix + 1; + return result; + } + _unreadRecordIndex = -1; + _unreadRecordBuffer = null; + } + return null; + } - /** - * @return the next available record, or null if - * this pass didn't return a record that's - * suitable for returning (eg was a continue record). - */ - private Record readNextRecord() { + /** + * @return the next available record, or null if + * this pass didn't return a record that's + * suitable for returning (eg was a continue record). + */ + private Record readNextRecord() { - Record record = RecordFactory.createSingleRecord(_recStream); - _lastRecordWasEOFLevelZero = false; + Record record = RecordFactory.createSingleRecord(_recStream); + _lastRecordWasEOFLevelZero = false; - if (record instanceof BOFRecord) { - _bofDepth++; - return record; - } + if (record instanceof BOFRecord) { + _bofDepth++; + return record; + } - if (record instanceof EOFRecord) { - _bofDepth--; - if (_bofDepth < 1) { - _lastRecordWasEOFLevelZero = true; - } + if (record instanceof EOFRecord) { + _bofDepth--; + if (_bofDepth < 1) { + _lastRecordWasEOFLevelZero = true; + } - return record; - } + return record; + } - if (record instanceof DBCellRecord) { - // Not needed by POI. Regenerated from scratch by POI when spreadsheet is written - return null; - } + if (record instanceof DBCellRecord) { + // Not needed by POI. Regenerated from scratch by POI when spreadsheet is written + return null; + } - if (record instanceof RKRecord) { - return RecordFactory.convertToNumberRecord((RKRecord) record); - } + if (record instanceof RKRecord) { + return RecordFactory.convertToNumberRecord((RKRecord) record); + } - if (record instanceof MulRKRecord) { - Record[] records = RecordFactory.convertRKRecords((MulRKRecord) record); + if (record instanceof MulRKRecord) { + Record[] records = RecordFactory.convertRKRecords((MulRKRecord) record); - _unreadRecordBuffer = records; - _unreadRecordIndex = 1; - return records[0]; - } + _unreadRecordBuffer = records; + _unreadRecordIndex = 1; + return records[0]; + } - if (record.getSid() == DrawingGroupRecord.sid - && _lastRecord instanceof DrawingGroupRecord) { - DrawingGroupRecord lastDGRecord = (DrawingGroupRecord) _lastRecord; - lastDGRecord.join((AbstractEscherHolderRecord) record); - return null; - } - if (record.getSid() == ContinueRecord.sid) { - ContinueRecord contRec = (ContinueRecord) record; + if (record.getSid() == DrawingGroupRecord.sid + && _lastRecord instanceof DrawingGroupRecord) { + DrawingGroupRecord lastDGRecord = (DrawingGroupRecord) _lastRecord; + lastDGRecord.join((AbstractEscherHolderRecord) record); + return null; + } + if (record.getSid() == ContinueRecord.sid) { + ContinueRecord contRec = (ContinueRecord) record; - if (_lastRecord instanceof ObjRecord || _lastRecord instanceof TextObjectRecord) { - // Drawing records have a very strange continue behaviour. - //There can actually be OBJ records mixed between the continues. - _lastDrawingRecord.processContinueRecord(contRec.getData()); - //we must remember the position of the continue record. - //in the serialization procedure the original structure of records must be preserved - if (_shouldIncludeContinueRecords) { - return record; - } - return null; - } - if (_lastRecord instanceof DrawingGroupRecord) { - ((DrawingGroupRecord) _lastRecord).processContinueRecord(contRec.getData()); - return null; - } - if (_lastRecord instanceof DrawingRecord) { -// ((DrawingRecord) _lastRecord).appendContinueRecord(contRec.getData()); - return contRec; - } - if (_lastRecord instanceof UnknownRecord) { - //Gracefully handle records that we don't know about, - //that happen to be continued - return record; - } - if (_lastRecord instanceof EOFRecord) { - // This is really odd, but excel still sometimes - // outputs a file like this all the same - return record; - } - throw new RecordFormatException("Unhandled Continue Record followining " + _lastRecord.getClass()); - } - _lastRecord = record; - if (record instanceof DrawingRecord) { - _lastDrawingRecord = (DrawingRecord) record; - } - return record; - } + if (_lastRecord instanceof ObjRecord || _lastRecord instanceof TextObjectRecord) { + // Drawing records have a very strange continue behaviour. + //There can actually be OBJ records mixed between the continues. + _lastDrawingRecord.processContinueRecord(contRec.getData()); + //we must remember the position of the continue record. + //in the serialization procedure the original structure of records must be preserved + if (_shouldIncludeContinueRecords) { + return record; + } + return null; + } + if (_lastRecord instanceof DrawingGroupRecord) { + ((DrawingGroupRecord) _lastRecord).processContinueRecord(contRec.getData()); + return null; + } + if (_lastRecord instanceof DrawingRecord) { +// ((DrawingRecord) _lastRecord).appendContinueRecord(contRec.getData()); + return contRec; + } + if (_lastRecord instanceof UnknownRecord) { + //Gracefully handle records that we don't know about, + //that happen to be continued + return record; + } + if (_lastRecord instanceof EOFRecord) { + // This is really odd, but excel still sometimes + // outputs a file like this all the same + return record; + } + throw new RecordFormatException("Unhandled Continue Record followining " + _lastRecord.getClass()); + } + _lastRecord = record; + if (record instanceof DrawingRecord) { + _lastDrawingRecord = (DrawingRecord) record; + } + return record; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java b/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java index 84c5faf29c..94fc4070c7 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/RecordInputStream.java @@ -40,28 +40,28 @@ import org.apache.poi.util.RecordFormatException; public final class RecordInputStream implements LittleEndianInput { - /** Maximum size of a single record (minus the 4 byte header) without a continue*/ - public static final short MAX_RECORD_DATA_SIZE = 8224; - private static final int INVALID_SID_VALUE = -1; - //arbitrarily selected; may need to increase - private static final int MAX_RECORD_LENGTH = 100_000; - /** - * When {@link #_currentDataLength} has this value, it means that the previous BIFF record is - * finished, the next sid has been properly read, but the data size field has not been read yet. - */ - private static final int DATA_LEN_NEEDS_TO_BE_READ = -1; - private static final byte[] EMPTY_BYTE_ARRAY = { }; + /** Maximum size of a single record (minus the 4 byte header) without a continue*/ + public static final short MAX_RECORD_DATA_SIZE = 8224; + private static final int INVALID_SID_VALUE = -1; + //arbitrarily selected; may need to increase + private static final int MAX_RECORD_LENGTH = 100_000; + /** + * When {@link #_currentDataLength} has this value, it means that the previous BIFF record is + * finished, the next sid has been properly read, but the data size field has not been read yet. + */ + private static final int DATA_LEN_NEEDS_TO_BE_READ = -1; + private static final byte[] EMPTY_BYTE_ARRAY = { }; - /** - * For use in {@link BiffViewer} which may construct {@link Record}s that don't completely - * read all available data. This exception should never be thrown otherwise. - */ - public static final class LeftoverDataException extends RuntimeException { - public LeftoverDataException(int sid, int remainingByteCount) { - super("Initialisation of record 0x" + Integer.toHexString(sid).toUpperCase(Locale.ROOT) - + "(" + getRecordName(sid) + ") left " + remainingByteCount - + " bytes remaining still to be read."); - } + /** + * For use in {@link BiffViewer} which may construct {@link Record}s that don't completely + * read all available data. This exception should never be thrown otherwise. + */ + public static final class LeftoverDataException extends RuntimeException { + public LeftoverDataException(int sid, int remainingByteCount) { + super("Initialisation of record 0x" + Integer.toHexString(sid).toUpperCase(Locale.ROOT) + + "(" + getRecordName(sid) + ") left " + remainingByteCount + + " bytes remaining still to be read."); + } private static String getRecordName(int sid) { Class recordClass = RecordFactory.getRecordClass(sid); @@ -70,255 +70,255 @@ public final class RecordInputStream implements LittleEndianInput { } return recordClass.getSimpleName(); } - } + } - /** Header {@link LittleEndianInput} facet of the wrapped {@link InputStream} */ - private final BiffHeaderInput _bhi; - /** Data {@link LittleEndianInput} facet of the wrapped {@link InputStream} */ - private final LittleEndianInput _dataInput; - /** the record identifier of the BIFF record currently being read */ - private int _currentSid; - /** - * Length of the data section of the current BIFF record (always 4 less than the total record size). - * When uninitialised, this field is set to {@link #DATA_LEN_NEEDS_TO_BE_READ}. - */ - private int _currentDataLength; - /** - * The BIFF record identifier for the next record is read when just as the current record - * is finished. - * This field is only really valid during the time that ({@link #_currentDataLength} == - * {@link #DATA_LEN_NEEDS_TO_BE_READ}). At most other times its value is not really the - * 'sid of the next record'. Wwhile mid-record, this field coincidentally holds the sid - * of the current record. - */ - private int _nextSid; - /** - * index within the data section of the current BIFF record - */ - private int _currentDataOffset; - /** - * index within the data section when mark() was called - */ - private int _markedDataOffset; + /** Header {@link LittleEndianInput} facet of the wrapped {@link InputStream} */ + private final BiffHeaderInput _bhi; + /** Data {@link LittleEndianInput} facet of the wrapped {@link InputStream} */ + private final LittleEndianInput _dataInput; + /** the record identifier of the BIFF record currently being read */ + private int _currentSid; + /** + * Length of the data section of the current BIFF record (always 4 less than the total record size). + * When uninitialised, this field is set to {@link #DATA_LEN_NEEDS_TO_BE_READ}. + */ + private int _currentDataLength; + /** + * The BIFF record identifier for the next record is read when just as the current record + * is finished. + * This field is only really valid during the time that ({@link #_currentDataLength} == + * {@link #DATA_LEN_NEEDS_TO_BE_READ}). At most other times its value is not really the + * 'sid of the next record'. Wwhile mid-record, this field coincidentally holds the sid + * of the current record. + */ + private int _nextSid; + /** + * index within the data section of the current BIFF record + */ + private int _currentDataOffset; + /** + * index within the data section when mark() was called + */ + private int _markedDataOffset; - private static final class SimpleHeaderInput implements BiffHeaderInput { + private static final class SimpleHeaderInput implements BiffHeaderInput { - private final LittleEndianInput _lei; + private final LittleEndianInput _lei; - private SimpleHeaderInput(LittleEndianInput lei) { - _lei = lei; - } - @Override + private SimpleHeaderInput(LittleEndianInput lei) { + _lei = lei; + } + @Override public int available() { - return _lei.available(); - } - @Override + return _lei.available(); + } + @Override public int readDataSize() { - return _lei.readUShort(); - } - @Override + return _lei.readUShort(); + } + @Override public int readRecordSID() { - return _lei.readUShort(); - } - } + return _lei.readUShort(); + } + } - public RecordInputStream(InputStream in) throws RecordFormatException { - this (in, null, 0); - } + public RecordInputStream(InputStream in) throws RecordFormatException { + this (in, null, 0); + } - public RecordInputStream(InputStream in, EncryptionInfo key, int initialOffset) throws RecordFormatException { - if (key == null) { - _dataInput = (in instanceof LittleEndianInput) - // accessing directly is an optimisation - ? (LittleEndianInput)in - // less optimal, but should work OK just the same. Often occurs in junit tests. - : new LittleEndianInputStream(in); - _bhi = new SimpleHeaderInput(_dataInput); - } else { - Biff8DecryptingStream bds = new Biff8DecryptingStream(in, initialOffset, key); + public RecordInputStream(InputStream in, EncryptionInfo key, int initialOffset) throws RecordFormatException { + if (key == null) { + _dataInput = (in instanceof LittleEndianInput) + // accessing directly is an optimisation + ? (LittleEndianInput)in + // less optimal, but should work OK just the same. Often occurs in junit tests. + : new LittleEndianInputStream(in); + _bhi = new SimpleHeaderInput(_dataInput); + } else { + Biff8DecryptingStream bds = new Biff8DecryptingStream(in, initialOffset, key); _dataInput = bds; - _bhi = bds; - } - _nextSid = readNextSid(); - } + _bhi = bds; + } + _nextSid = readNextSid(); + } - static LittleEndianInput getLEI(InputStream is) { - if (is instanceof LittleEndianInput) { - // accessing directly is an optimisation - return (LittleEndianInput) is; - } - // less optimal, but should work OK just the same. Often occurs in junit tests. - return new LittleEndianInputStream(is); - } + static LittleEndianInput getLEI(InputStream is) { + if (is instanceof LittleEndianInput) { + // accessing directly is an optimisation + return (LittleEndianInput) is; + } + // less optimal, but should work OK just the same. Often occurs in junit tests. + return new LittleEndianInputStream(is); + } - /** - * @return the number of bytes available in the current BIFF record - * @see #remaining() - */ - @Override + /** + * @return the number of bytes available in the current BIFF record + * @see #remaining() + */ + @Override public int available() { - return remaining(); - } + return remaining(); + } - public int read(byte[] b, int off, int len) { - int limit = Math.min(len, remaining()); - if (limit == 0) { - return 0; - } - readFully(b, off,limit); - return limit; - } + public int read(byte[] b, int off, int len) { + int limit = Math.min(len, remaining()); + if (limit == 0) { + return 0; + } + readFully(b, off,limit); + return limit; + } - public short getSid() { - return (short) _currentSid; - } + public short getSid() { + return (short) _currentSid; + } - /** - * Note - this method is expected to be called only when completed reading the current BIFF - * record. - * - * @return true, if there's another record in the stream - * - * @throws LeftoverDataException if this method is called before reaching the end of the - * current record. - */ - public boolean hasNextRecord() throws LeftoverDataException { - if (_currentDataLength != -1 && _currentDataLength != _currentDataOffset) { - throw new LeftoverDataException(_currentSid, remaining()); - } - if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ) { - _nextSid = readNextSid(); - } - return _nextSid != INVALID_SID_VALUE; - } + /** + * Note - this method is expected to be called only when completed reading the current BIFF + * record. + * + * @return true, if there's another record in the stream + * + * @throws LeftoverDataException if this method is called before reaching the end of the + * current record. + */ + public boolean hasNextRecord() throws LeftoverDataException { + if (_currentDataLength != -1 && _currentDataLength != _currentDataOffset) { + throw new LeftoverDataException(_currentSid, remaining()); + } + if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ) { + _nextSid = readNextSid(); + } + return _nextSid != INVALID_SID_VALUE; + } - /** - * @return the sid of the next record or {@link #INVALID_SID_VALUE} if at end of stream - */ - private int readNextSid() { - int nAvailable = _bhi.available(); - if (nAvailable < EOFRecord.ENCODED_SIZE) { - // some scrap left over, if nAvailable > 0? - // ex45582-22397.xls has one extra byte after the last record - // Excel reads that file OK - return INVALID_SID_VALUE; - } - int result = _bhi.readRecordSID(); - if (result == INVALID_SID_VALUE) { - throw new RecordFormatException("Found invalid sid (" + result + ")"); - } - _currentDataLength = DATA_LEN_NEEDS_TO_BE_READ; - return result; - } + /** + * @return the sid of the next record or {@link #INVALID_SID_VALUE} if at end of stream + */ + private int readNextSid() { + int nAvailable = _bhi.available(); + if (nAvailable < EOFRecord.ENCODED_SIZE) { + // some scrap left over, if nAvailable > 0? + // ex45582-22397.xls has one extra byte after the last record + // Excel reads that file OK + return INVALID_SID_VALUE; + } + int result = _bhi.readRecordSID(); + if (result == INVALID_SID_VALUE) { + throw new RecordFormatException("Found invalid sid (" + result + ")"); + } + _currentDataLength = DATA_LEN_NEEDS_TO_BE_READ; + return result; + } - /** Moves to the next record in the stream. - * - * Note: The auto continue flag is reset to true - */ - public void nextRecord() throws RecordFormatException { - if (_nextSid == INVALID_SID_VALUE) { - throw new IllegalStateException("EOF - next record not available"); - } - if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ) { - throw new IllegalStateException("Cannot call nextRecord() without checking hasNextRecord() first"); - } - _currentSid = _nextSid; - _currentDataOffset = 0; - _currentDataLength = _bhi.readDataSize(); - if (_currentDataLength > MAX_RECORD_DATA_SIZE) { - throw new RecordFormatException("The content of an excel record cannot exceed " - + MAX_RECORD_DATA_SIZE + " bytes"); - } - } + /** Moves to the next record in the stream. + * + * Note: The auto continue flag is reset to true + */ + public void nextRecord() throws RecordFormatException { + if (_nextSid == INVALID_SID_VALUE) { + throw new IllegalStateException("EOF - next record not available"); + } + if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ) { + throw new IllegalStateException("Cannot call nextRecord() without checking hasNextRecord() first"); + } + _currentSid = _nextSid; + _currentDataOffset = 0; + _currentDataLength = _bhi.readDataSize(); + if (_currentDataLength > MAX_RECORD_DATA_SIZE) { + throw new RecordFormatException("The content of an excel record cannot exceed " + + MAX_RECORD_DATA_SIZE + " bytes"); + } + } - private void checkRecordPosition(int requiredByteCount) { + private void checkRecordPosition(int requiredByteCount) { - int nAvailable = remaining(); - if (nAvailable >= requiredByteCount) { - // all OK - return; - } - if (nAvailable == 0 && isContinueNext()) { - nextRecord(); - return; - } - throw new RecordFormatException("Not enough data (" + nAvailable - + ") to read requested (" + requiredByteCount +") bytes"); - } + int nAvailable = remaining(); + if (nAvailable >= requiredByteCount) { + // all OK + return; + } + if (nAvailable == 0 && isContinueNext()) { + nextRecord(); + return; + } + throw new RecordFormatException("Not enough data (" + nAvailable + + ") to read requested (" + requiredByteCount +") bytes"); + } - /** - * Reads an 8 bit, signed value - */ - @Override + /** + * Reads an 8 bit, signed value + */ + @Override public byte readByte() { - checkRecordPosition(LittleEndianConsts.BYTE_SIZE); - _currentDataOffset += LittleEndianConsts.BYTE_SIZE; - return _dataInput.readByte(); - } + checkRecordPosition(LittleEndianConsts.BYTE_SIZE); + _currentDataOffset += LittleEndianConsts.BYTE_SIZE; + return _dataInput.readByte(); + } - /** - * Reads a 16 bit, signed value - */ - @Override + /** + * Reads a 16 bit, signed value + */ + @Override public short readShort() { - checkRecordPosition(LittleEndianConsts.SHORT_SIZE); - _currentDataOffset += LittleEndianConsts.SHORT_SIZE; - return _dataInput.readShort(); - } + checkRecordPosition(LittleEndianConsts.SHORT_SIZE); + _currentDataOffset += LittleEndianConsts.SHORT_SIZE; + return _dataInput.readShort(); + } - /** - * Reads a 32 bit, signed value - */ - @Override + /** + * Reads a 32 bit, signed value + */ + @Override public int readInt() { - checkRecordPosition(LittleEndianConsts.INT_SIZE); - _currentDataOffset += LittleEndianConsts.INT_SIZE; - return _dataInput.readInt(); - } + checkRecordPosition(LittleEndianConsts.INT_SIZE); + _currentDataOffset += LittleEndianConsts.INT_SIZE; + return _dataInput.readInt(); + } - /** - * Reads a 64 bit, signed value - */ - @Override + /** + * Reads a 64 bit, signed value + */ + @Override public long readLong() { - checkRecordPosition(LittleEndianConsts.LONG_SIZE); - _currentDataOffset += LittleEndianConsts.LONG_SIZE; - return _dataInput.readLong(); - } + checkRecordPosition(LittleEndianConsts.LONG_SIZE); + _currentDataOffset += LittleEndianConsts.LONG_SIZE; + return _dataInput.readLong(); + } - /** - * Reads an 8 bit, unsigned value - */ - @Override + /** + * Reads an 8 bit, unsigned value + */ + @Override public int readUByte() { - return readByte() & 0x00FF; - } + return readByte() & 0x00FF; + } - /** - * Reads a 16 bit, unsigned value. - */ - @Override + /** + * Reads a 16 bit, unsigned value. + */ + @Override public int readUShort() { - checkRecordPosition(LittleEndianConsts.SHORT_SIZE); - _currentDataOffset += LittleEndianConsts.SHORT_SIZE; - return _dataInput.readUShort(); - } + checkRecordPosition(LittleEndianConsts.SHORT_SIZE); + _currentDataOffset += LittleEndianConsts.SHORT_SIZE; + return _dataInput.readUShort(); + } - @Override + @Override public double readDouble() { // YK: Excel doesn't write NaN but instead converts the cell type into {@link CellType#ERROR}. - return Double.longBitsToDouble(readLong()); - } + return Double.longBitsToDouble(readLong()); + } - @Override - public void readPlain(byte[] buf, int off, int len) { - readFully(buf, 0, buf.length, true); - } + @Override + public void readPlain(byte[] buf, int off, int len) { + readFully(buf, 0, buf.length, true); + } - @Override + @Override public void readFully(byte[] buf) { - readFully(buf, 0, buf.length, false); - } + readFully(buf, 0, buf.length, false); + } @Override public void readFully(byte[] buf, int off, int len) { @@ -326,126 +326,126 @@ public final class RecordInputStream implements LittleEndianInput { } private void readFully(byte[] buf, int off, int len, boolean isPlain) { - int origLen = len; - if (buf == null) { - throw new NullPointerException(); - } else if (off < 0 || len < 0 || len > buf.length - off) { - throw new IndexOutOfBoundsException(); - } + int origLen = len; + if (buf == null) { + throw new NullPointerException(); + } else if (off < 0 || len < 0 || len > buf.length - off) { + throw new IndexOutOfBoundsException(); + } - while (len > 0) { - int nextChunk = Math.min(available(),len); - if (nextChunk == 0) { - if (!hasNextRecord()) { - throw new RecordFormatException("Can't read the remaining "+len+" bytes of the requested "+origLen+" bytes. No further record exists."); - } else { - nextRecord(); - nextChunk = Math.min(available(),len); - assert(nextChunk > 0); - } - } - checkRecordPosition(nextChunk); - if (isPlain) { + while (len > 0) { + int nextChunk = Math.min(available(),len); + if (nextChunk == 0) { + if (!hasNextRecord()) { + throw new RecordFormatException("Can't read the remaining "+len+" bytes of the requested "+origLen+" bytes. No further record exists."); + } else { + nextRecord(); + nextChunk = Math.min(available(),len); + assert(nextChunk > 0); + } + } + checkRecordPosition(nextChunk); + if (isPlain) { _dataInput.readPlain(buf, off, nextChunk); - } else { + } else { _dataInput.readFully(buf, off, nextChunk); - } - _currentDataOffset+=nextChunk; - off += nextChunk; - len -= nextChunk; - } - } + } + _currentDataOffset+=nextChunk; + off += nextChunk; + len -= nextChunk; + } + } - public String readString() { - int requestedLength = readUShort(); - byte compressFlag = readByte(); - return readStringCommon(requestedLength, compressFlag == 0); - } - /** - * given a byte array of 16-bit unicode characters, compress to 8-bit and - * return a string - * - * { 0x16, 0x00 } -0x16 - * - * @param requestedLength the length of the final string - * @return the converted string - * @exception IllegalArgumentException if len is too large (i.e., - * there is not enough data in string to create a String of that - * length) - */ - public String readUnicodeLEString(int requestedLength) { - return readStringCommon(requestedLength, false); - } + public String readString() { + int requestedLength = readUShort(); + byte compressFlag = readByte(); + return readStringCommon(requestedLength, compressFlag == 0); + } + /** + * given a byte array of 16-bit unicode characters, compress to 8-bit and + * return a string + * + * { 0x16, 0x00 } -0x16 + * + * @param requestedLength the length of the final string + * @return the converted string + * @exception IllegalArgumentException if len is too large (i.e., + * there is not enough data in string to create a String of that + * length) + */ + public String readUnicodeLEString(int requestedLength) { + return readStringCommon(requestedLength, false); + } - public String readCompressedUnicode(int requestedLength) { - return readStringCommon(requestedLength, true); - } + public String readCompressedUnicode(int requestedLength) { + return readStringCommon(requestedLength, true); + } - private String readStringCommon(int requestedLength, boolean pIsCompressedEncoding) { - // Sanity check to detect garbage string lengths - if (requestedLength < 0 || requestedLength > 0x100000) { // 16 million chars? - throw new IllegalArgumentException("Bad requested string length (" + requestedLength + ")"); - } - char[] buf = new char[requestedLength]; - boolean isCompressedEncoding = pIsCompressedEncoding; - int curLen = 0; - while(true) { - int availableChars =isCompressedEncoding ? remaining() : remaining() / LittleEndianConsts.SHORT_SIZE; - if (requestedLength - curLen <= availableChars) { - // enough space in current record, so just read it out - while(curLen < requestedLength) { - char ch; - if (isCompressedEncoding) { - ch = (char)readUByte(); - } else { - ch = (char)readShort(); - } - buf[curLen] = ch; - curLen++; - } - return new String(buf); - } - // else string has been spilled into next continue record - // so read what's left of the current record - while(availableChars > 0) { - char ch; - if (isCompressedEncoding) { - ch = (char)readUByte(); - } else { - ch = (char)readShort(); - } - buf[curLen] = ch; - curLen++; - availableChars--; - } - if (!isContinueNext()) { - throw new RecordFormatException("Expected to find a ContinueRecord in order to read remaining " - + (requestedLength-curLen) + " of " + requestedLength + " chars"); - } - if(remaining() != 0) { - throw new RecordFormatException("Odd number of bytes(" + remaining() + ") left behind"); - } - nextRecord(); - // note - the compressed flag may change on the fly - byte compressFlag = readByte(); + private String readStringCommon(int requestedLength, boolean pIsCompressedEncoding) { + // Sanity check to detect garbage string lengths + if (requestedLength < 0 || requestedLength > 0x100000) { // 16 million chars? + throw new IllegalArgumentException("Bad requested string length (" + requestedLength + ")"); + } + char[] buf = new char[requestedLength]; + boolean isCompressedEncoding = pIsCompressedEncoding; + int curLen = 0; + while(true) { + int availableChars =isCompressedEncoding ? remaining() : remaining() / LittleEndianConsts.SHORT_SIZE; + if (requestedLength - curLen <= availableChars) { + // enough space in current record, so just read it out + while(curLen < requestedLength) { + char ch; + if (isCompressedEncoding) { + ch = (char)readUByte(); + } else { + ch = (char)readShort(); + } + buf[curLen] = ch; + curLen++; + } + return new String(buf); + } + // else string has been spilled into next continue record + // so read what's left of the current record + while(availableChars > 0) { + char ch; + if (isCompressedEncoding) { + ch = (char)readUByte(); + } else { + ch = (char)readShort(); + } + buf[curLen] = ch; + curLen++; + availableChars--; + } + if (!isContinueNext()) { + throw new RecordFormatException("Expected to find a ContinueRecord in order to read remaining " + + (requestedLength-curLen) + " of " + requestedLength + " chars"); + } + if(remaining() != 0) { + throw new RecordFormatException("Odd number of bytes(" + remaining() + ") left behind"); + } + nextRecord(); + // note - the compressed flag may change on the fly + byte compressFlag = readByte(); assert(compressFlag == 0 || compressFlag == 1); - isCompressedEncoding = (compressFlag == 0); - } - } + isCompressedEncoding = (compressFlag == 0); + } + } - /** Returns the remaining bytes for the current record. - * - * @return The remaining bytes of the current record. - */ - public byte[] readRemainder() { - int size = remaining(); - if (size ==0) { - return EMPTY_BYTE_ARRAY; - } - byte[] result = IOUtils.safelyAllocate(size, MAX_RECORD_LENGTH); - readFully(result); - return result; - } + /** Returns the remaining bytes for the current record. + * + * @return The remaining bytes of the current record. + */ + public byte[] readRemainder() { + int size = remaining(); + if (size ==0) { + return EMPTY_BYTE_ARRAY; + } + byte[] result = IOUtils.safelyAllocate(size, MAX_RECORD_LENGTH); + readFully(result); + return result; + } /** * Reads all byte data for the current record, including any that overlaps @@ -472,36 +472,36 @@ public final class RecordInputStream implements LittleEndianInput { return out.toByteArray(); } - /** The remaining number of bytes in the current record. - * - * @return The number of bytes remaining in the current record - */ - public int remaining() { - if (_currentDataLength == DATA_LEN_NEEDS_TO_BE_READ) { - // already read sid of next record. so current one is finished - return 0; - } - return _currentDataLength - _currentDataOffset; - } + /** The remaining number of bytes in the current record. + * + * @return The number of bytes remaining in the current record + */ + public int remaining() { + if (_currentDataLength == DATA_LEN_NEEDS_TO_BE_READ) { + // already read sid of next record. so current one is finished + return 0; + } + return _currentDataLength - _currentDataOffset; + } - /** - * - * @return {@code true} when a {@link ContinueRecord} is next. - */ - private boolean isContinueNext() { - if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ && _currentDataOffset != _currentDataLength) { - throw new IllegalStateException("Should never be called before end of current record"); - } - if (!hasNextRecord()) { - return false; - } - // At what point are records continued? - // - Often from within the char data of long strings (caller is within readStringCommon()). - // - From UnicodeString construction (many different points - call via checkRecordPosition) - // - During TextObjectRecord construction (just before the text, perhaps within the text, - // and before the formatting run data) - return _nextSid == ContinueRecord.sid; - } + /** + * + * @return {@code true} when a {@link ContinueRecord} is next. + */ + private boolean isContinueNext() { + if (_currentDataLength != DATA_LEN_NEEDS_TO_BE_READ && _currentDataOffset != _currentDataLength) { + throw new IllegalStateException("Should never be called before end of current record"); + } + if (!hasNextRecord()) { + return false; + } + // At what point are records continued? + // - Often from within the char data of long strings (caller is within readStringCommon()). + // - From UnicodeString construction (many different points - call via checkRecordPosition) + // - During TextObjectRecord construction (just before the text, perhaps within the text, + // and before the formatting run data) + return _nextSid == ContinueRecord.sid; + } /** @return sid of next record. Can be called after hasNextRecord() diff --git a/poi/src/main/java/org/apache/poi/hssf/record/RowRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/RowRecord.java index e6e0be434e..2096c37c1b 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/RowRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/RowRecord.java @@ -81,9 +81,9 @@ public final class RowRecord extends StandardRecord { public RowRecord(int rowNumber) { - if(rowNumber < 0) { - throw new IllegalArgumentException("Invalid row number (" + rowNumber + ")"); - } + if(rowNumber < 0) { + throw new IllegalArgumentException("Invalid row number (" + rowNumber + ")"); + } field_1_row_number = rowNumber; field_4_height = (short)0xFF; field_5_optimize = ( short ) 0; @@ -96,9 +96,9 @@ public final class RowRecord extends StandardRecord { public RowRecord(RecordInputStream in) { field_1_row_number = in.readUShort(); - if(field_1_row_number < 0) { - throw new IllegalArgumentException("Invalid row number " + field_1_row_number + " found in InputStream"); - } + if(field_1_row_number < 0) { + throw new IllegalArgumentException("Invalid row number " + field_1_row_number + " found in InputStream"); + } field_2_first_col = in.readShort(); field_3_last_col = in.readShort(); field_4_height = in.readShort(); @@ -209,7 +209,7 @@ public final class RowRecord extends StandardRecord { * @param index to the XF record */ public void setXFIndex(short index) { - field_8_option_flags = xfIndex.setValue(field_8_option_flags, index); + field_8_option_flags = xfIndex.setValue(field_8_option_flags, index); } /** @@ -218,7 +218,7 @@ public final class RowRecord extends StandardRecord { * @param f has thick top border */ public void setTopBorder(boolean f) { - field_8_option_flags = topBorder.setBoolean(field_8_option_flags, f); + field_8_option_flags = topBorder.setBoolean(field_8_option_flags, f); } /** @@ -228,7 +228,7 @@ public final class RowRecord extends StandardRecord { * @param f has thick bottom border */ public void setBottomBorder(boolean f) { - field_8_option_flags = bottomBorder.setBoolean(field_8_option_flags, f); + field_8_option_flags = bottomBorder.setBoolean(field_8_option_flags, f); } /** @@ -237,7 +237,7 @@ public final class RowRecord extends StandardRecord { * @param f use phoenetic guide */ public void setPhoeneticGuide(boolean f) { - field_8_option_flags = phoneticGuide.setBoolean(field_8_option_flags, f); + field_8_option_flags = phoneticGuide.setBoolean(field_8_option_flags, f); } /** @@ -353,7 +353,7 @@ public final class RowRecord extends StandardRecord { * @return index to the XF record or bogus value (undefined) if isn't formatted */ public short getXFIndex() { - return xfIndex.getShortValue((short)field_8_option_flags); + return xfIndex.getShortValue((short)field_8_option_flags); } /** @@ -362,7 +362,7 @@ public final class RowRecord extends StandardRecord { * @return has cells with a thick top border */ public boolean getTopBorder() { - return topBorder.isSet(field_8_option_flags); + return topBorder.isSet(field_8_option_flags); } /** @@ -371,7 +371,7 @@ public final class RowRecord extends StandardRecord { * @return has cells with a thick bottom border */ public boolean getBottomBorder() { - return bottomBorder.isSet(field_8_option_flags); + return bottomBorder.isSet(field_8_option_flags); } /** @@ -380,7 +380,7 @@ public final class RowRecord extends StandardRecord { * @return has phoentic guide */ public boolean getPhoeneticGuide() { - return phoneticGuide.isSet(field_8_option_flags); + return phoneticGuide.isSet(field_8_option_flags); } public void serialize(LittleEndianOutput out) { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/SSTDeserializer.java b/poi/src/main/java/org/apache/poi/hssf/record/SSTDeserializer.java index c2d7e7d8c3..b4c2d3cd73 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/SSTDeserializer.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/SSTDeserializer.java @@ -31,7 +31,7 @@ import static org.apache.logging.log4j.util.Unbox.box; */ class SSTDeserializer { - private static final Logger LOG = LogManager.getLogger(SSTDeserializer.class); + private static final Logger LOG = LogManager.getLogger(SSTDeserializer.class); private IntMapper strings; public SSTDeserializer( IntMapper strings ) diff --git a/poi/src/main/java/org/apache/poi/hssf/record/SSTSerializer.java b/poi/src/main/java/org/apache/poi/hssf/record/SSTSerializer.java index c5ef2933d6..456f14bf5d 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/SSTSerializer.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/SSTSerializer.java @@ -27,8 +27,8 @@ import org.apache.poi.util.IntMapper; */ final class SSTSerializer { - private final int _numStrings; - private final int _numUniqueStrings; + private final int _numStrings; + private final int _numUniqueStrings; private final IntMapper strings; @@ -40,8 +40,8 @@ final class SSTSerializer { public SSTSerializer( IntMapper strings, int numStrings, int numUniqueStrings ) { this.strings = strings; - _numStrings = numStrings; - _numUniqueStrings = numUniqueStrings; + _numStrings = numStrings; + _numUniqueStrings = numUniqueStrings; int infoRecs = ExtSSTRecord.getNumberOfInfoRecsForStrings(strings.size()); this.bucketAbsoluteOffsets = new int[infoRecs]; diff --git a/poi/src/main/java/org/apache/poi/hssf/record/SharedFormulaRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/SharedFormulaRecord.java index 0c4f4e6a2b..c6a3b986c5 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/SharedFormulaRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/SharedFormulaRecord.java @@ -106,9 +106,9 @@ public final class SharedFormulaRecord extends SharedValueRecordBase { public SharedFormulaRecord copy() { return new SharedFormulaRecord(this); } - public boolean isFormulaSame(SharedFormulaRecord other) { - return field_7_parsed_expr.isSame(other.field_7_parsed_expr); - } + public boolean isFormulaSame(SharedFormulaRecord other) { + return field_7_parsed_expr.isSame(other.field_7_parsed_expr); + } @Override public HSSFRecordTypes getGenericRecordType() { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/SharedValueRecordBase.java b/poi/src/main/java/org/apache/poi/hssf/record/SharedValueRecordBase.java index 3f23037d2a..ae93efdc86 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/SharedValueRecordBase.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/SharedValueRecordBase.java @@ -27,95 +27,95 @@ import org.apache.poi.util.LittleEndianOutput; */ public abstract class SharedValueRecordBase extends StandardRecord { - private CellRangeAddress8Bit _range; + private CellRangeAddress8Bit _range; - protected SharedValueRecordBase(SharedValueRecordBase other) { - super(other); - _range = (other._range == null) ? null : other._range.copy(); - } + protected SharedValueRecordBase(SharedValueRecordBase other) { + super(other); + _range = (other._range == null) ? null : other._range.copy(); + } - protected SharedValueRecordBase(CellRangeAddress8Bit range) { - if (range == null) { - throw new IllegalArgumentException("range must be supplied."); - } - _range = range; - } + protected SharedValueRecordBase(CellRangeAddress8Bit range) { + if (range == null) { + throw new IllegalArgumentException("range must be supplied."); + } + _range = range; + } - protected SharedValueRecordBase() { - this(new CellRangeAddress8Bit(0, 0, 0, 0)); - } + protected SharedValueRecordBase() { + this(new CellRangeAddress8Bit(0, 0, 0, 0)); + } - /** - * reads only the range (1 {@link CellRangeAddress8Bit}) from the stream - * - * @param in The interface for reading the record data. - */ - public SharedValueRecordBase(LittleEndianInput in) { - _range = new CellRangeAddress8Bit(in); - } + /** + * reads only the range (1 {@link CellRangeAddress8Bit}) from the stream + * + * @param in The interface for reading the record data. + */ + public SharedValueRecordBase(LittleEndianInput in) { + _range = new CellRangeAddress8Bit(in); + } - /** - * @return the range of cells that this record is shared across. Never null. - */ - public final CellRangeAddress8Bit getRange() { - return _range; - } + /** + * @return the range of cells that this record is shared across. Never null. + */ + public final CellRangeAddress8Bit getRange() { + return _range; + } - public final int getFirstRow() { - return _range.getFirstRow(); - } + public final int getFirstRow() { + return _range.getFirstRow(); + } - public final int getLastRow() { - return _range.getLastRow(); - } + public final int getLastRow() { + return _range.getLastRow(); + } - public final int getFirstColumn() { - return (short) _range.getFirstColumn(); - } + public final int getFirstColumn() { + return (short) _range.getFirstColumn(); + } - public final int getLastColumn() { - return (short) _range.getLastColumn(); - } + public final int getLastColumn() { + return (short) _range.getLastColumn(); + } - protected int getDataSize() { - return CellRangeAddress8Bit.ENCODED_SIZE + getExtraDataSize(); - } + protected int getDataSize() { + return CellRangeAddress8Bit.ENCODED_SIZE + getExtraDataSize(); + } - protected abstract int getExtraDataSize(); + protected abstract int getExtraDataSize(); - protected abstract void serializeExtraData(LittleEndianOutput out); + protected abstract void serializeExtraData(LittleEndianOutput out); - public void serialize(LittleEndianOutput out) { - _range.serialize(out); - serializeExtraData(out); - } + public void serialize(LittleEndianOutput out) { + _range.serialize(out); + serializeExtraData(out); + } - /** + /** * @param rowIx the row index * @param colIx the column index * - * @return {@code true} if (rowIx, colIx) is within the range of this shared value object. + * @return {@code true} if (rowIx, colIx) is within the range of this shared value object. * * @see #getRange() - */ - public final boolean isInRange(int rowIx, int colIx) { - CellRangeAddress8Bit r = _range; - return r.getFirstRow() <= rowIx - && r.getLastRow() >= rowIx - && r.getFirstColumn() <= colIx - && r.getLastColumn() >= colIx; - } - /** - * @param rowIx the row index - * @param colIx the column index - * - * @return {@code true} if (rowIx, colIx) describes the first cell in this shared value - * object's range - * - * @see #getRange() - */ - public final boolean isFirstCell(int rowIx, int colIx) { - CellRangeAddress8Bit r = getRange(); - return r.getFirstRow() == rowIx && r.getFirstColumn() == colIx; - } + */ + public final boolean isInRange(int rowIx, int colIx) { + CellRangeAddress8Bit r = _range; + return r.getFirstRow() <= rowIx + && r.getLastRow() >= rowIx + && r.getFirstColumn() <= colIx + && r.getLastColumn() >= colIx; + } + /** + * @param rowIx the row index + * @param colIx the column index + * + * @return {@code true} if (rowIx, colIx) describes the first cell in this shared value + * object's range + * + * @see #getRange() + */ + public final boolean isFirstCell(int rowIx, int colIx) { + CellRangeAddress8Bit r = getRange(); + return r.getFirstRow() == rowIx && r.getFirstColumn() == colIx; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/StringRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/StringRecord.java index efd86f1f79..ae63b774a4 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/StringRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/StringRecord.java @@ -31,10 +31,10 @@ import org.apache.poi.util.StringUtil; * Stores the cached result of a text formula */ public final class StringRecord extends ContinuableRecord { - public static final short sid = 0x0207; + public static final short sid = 0x0207; - private boolean _is16bitUnicode; - private String _text; + private boolean _is16bitUnicode; + private String _text; public StringRecord() {} diff --git a/poi/src/main/java/org/apache/poi/hssf/record/StyleRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/StyleRecord.java index 8f14499d80..0d6a9a81ca 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/StyleRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/StyleRecord.java @@ -31,174 +31,174 @@ import org.apache.poi.util.StringUtil; * Describes a builtin to the gui or user defined style */ public final class StyleRecord extends StandardRecord { - public static final short sid = 0x0293; + public static final short sid = 0x0293; - private static final BitField styleIndexMask = BitFieldFactory.getInstance(0x0FFF); - private static final BitField isBuiltinFlag = BitFieldFactory.getInstance(0x8000); + private static final BitField styleIndexMask = BitFieldFactory.getInstance(0x0FFF); + private static final BitField isBuiltinFlag = BitFieldFactory.getInstance(0x8000); - /** shared by both user defined and built-in styles */ - private int field_1_xf_index; + /** shared by both user defined and built-in styles */ + private int field_1_xf_index; - // only for built in styles - private int field_2_builtin_style; - private int field_3_outline_style_level; + // only for built in styles + private int field_2_builtin_style; + private int field_3_outline_style_level; - // only for user defined styles - private boolean field_3_stringHasMultibyte; - private String field_4_name; + // only for user defined styles + private boolean field_3_stringHasMultibyte; + private String field_4_name; - /** - * creates a new style record, initially set to 'built-in' - */ - public StyleRecord() { - field_1_xf_index = isBuiltinFlag.set(0); - } + /** + * creates a new style record, initially set to 'built-in' + */ + public StyleRecord() { + field_1_xf_index = isBuiltinFlag.set(0); + } - public StyleRecord(StyleRecord other) { - super(other); - field_1_xf_index = other.field_1_xf_index; - field_2_builtin_style = other.field_2_builtin_style; - field_3_outline_style_level = other.field_3_outline_style_level; - field_3_stringHasMultibyte = other.field_3_stringHasMultibyte; - field_4_name = other.field_4_name; - } + public StyleRecord(StyleRecord other) { + super(other); + field_1_xf_index = other.field_1_xf_index; + field_2_builtin_style = other.field_2_builtin_style; + field_3_outline_style_level = other.field_3_outline_style_level; + field_3_stringHasMultibyte = other.field_3_stringHasMultibyte; + field_4_name = other.field_4_name; + } - public StyleRecord(RecordInputStream in) { - field_1_xf_index = in.readShort(); - if (isBuiltin()) { - field_2_builtin_style = in.readByte(); - field_3_outline_style_level = in.readByte(); - } else { - int field_2_name_length = in.readShort(); + public StyleRecord(RecordInputStream in) { + field_1_xf_index = in.readShort(); + if (isBuiltin()) { + field_2_builtin_style = in.readByte(); + field_3_outline_style_level = in.readByte(); + } else { + int field_2_name_length = in.readShort(); - if(in.remaining() < 1) { - // Some files from Crystal Reports lack the is16BitUnicode byte - // the remaining fields, which is naughty - if (field_2_name_length != 0) { - throw new RecordFormatException("Ran out of data reading style record"); - } - // guess this is OK if the string length is zero - field_4_name = ""; - } else { + if(in.remaining() < 1) { + // Some files from Crystal Reports lack the is16BitUnicode byte + // the remaining fields, which is naughty + if (field_2_name_length != 0) { + throw new RecordFormatException("Ran out of data reading style record"); + } + // guess this is OK if the string length is zero + field_4_name = ""; + } else { - field_3_stringHasMultibyte = in.readByte() != 0x00; - if (field_3_stringHasMultibyte) { - field_4_name = StringUtil.readUnicodeLE(in, field_2_name_length); - } else { - field_4_name = StringUtil.readCompressedUnicode(in, field_2_name_length); - } - } - } - } + field_3_stringHasMultibyte = in.readByte() != 0x00; + if (field_3_stringHasMultibyte) { + field_4_name = StringUtil.readUnicodeLE(in, field_2_name_length); + } else { + field_4_name = StringUtil.readCompressedUnicode(in, field_2_name_length); + } + } + } + } - /** - * set the actual index of the style extended format record - * @param xfIndex of the xf record - */ - public void setXFIndex(int xfIndex) { - field_1_xf_index = styleIndexMask.setValue(field_1_xf_index, xfIndex); - } + /** + * set the actual index of the style extended format record + * @param xfIndex of the xf record + */ + public void setXFIndex(int xfIndex) { + field_1_xf_index = styleIndexMask.setValue(field_1_xf_index, xfIndex); + } - /** - * get the actual index of the style extended format record - * @see #getXFIndex() - * @return index of the xf record - */ - public int getXFIndex() { - return styleIndexMask.getValue(field_1_xf_index); - } + /** + * get the actual index of the style extended format record + * @see #getXFIndex() + * @return index of the xf record + */ + public int getXFIndex() { + return styleIndexMask.getValue(field_1_xf_index); + } - /** - * set the style's name - * @param name of the style - */ - public void setName(String name) { - field_4_name = name; - field_3_stringHasMultibyte = StringUtil.hasMultibyte(name); - field_1_xf_index = isBuiltinFlag.clear(field_1_xf_index); - } + /** + * set the style's name + * @param name of the style + */ + public void setName(String name) { + field_4_name = name; + field_3_stringHasMultibyte = StringUtil.hasMultibyte(name); + field_1_xf_index = isBuiltinFlag.clear(field_1_xf_index); + } - /** - * if this is a builtin style set the number of the built in style - * @param builtinStyleId style number (0-7) - * - */ - public void setBuiltinStyle(int builtinStyleId) { - field_1_xf_index = isBuiltinFlag.set(field_1_xf_index); - field_2_builtin_style = builtinStyleId; - } + /** + * if this is a builtin style set the number of the built in style + * @param builtinStyleId style number (0-7) + * + */ + public void setBuiltinStyle(int builtinStyleId) { + field_1_xf_index = isBuiltinFlag.set(field_1_xf_index); + field_2_builtin_style = builtinStyleId; + } - /** - * set the row or column level of the style (if builtin 1||2) - * - * @param level The outline-level - */ - public void setOutlineStyleLevel(int level) { - field_3_outline_style_level = level & 0x00FF; - } + /** + * set the row or column level of the style (if builtin 1||2) + * + * @param level The outline-level + */ + public void setOutlineStyleLevel(int level) { + field_3_outline_style_level = level & 0x00FF; + } - public boolean isBuiltin(){ - return isBuiltinFlag.isSet(field_1_xf_index); - } + public boolean isBuiltin(){ + return isBuiltinFlag.isSet(field_1_xf_index); + } - /** - * get the style's name - * @return name of the style - */ - public String getName() { - return field_4_name; - } + /** + * get the style's name + * @return name of the style + */ + public String getName() { + return field_4_name; + } - @Override - protected int getDataSize() { - if (isBuiltin()) { - return 4; // short, byte, byte - } - return 2 // short xf index - + 3 // str len + flag - + field_4_name.length() * (field_3_stringHasMultibyte ? 2 : 1); - } + @Override + protected int getDataSize() { + if (isBuiltin()) { + return 4; // short, byte, byte + } + return 2 // short xf index + + 3 // str len + flag + + field_4_name.length() * (field_3_stringHasMultibyte ? 2 : 1); + } - @Override - public void serialize(LittleEndianOutput out) { - out.writeShort(field_1_xf_index); - if (isBuiltin()) { - out.writeByte(field_2_builtin_style); - out.writeByte(field_3_outline_style_level); - } else { - out.writeShort(field_4_name.length()); - out.writeByte(field_3_stringHasMultibyte ? 0x01 : 0x00); - if (field_3_stringHasMultibyte) { - StringUtil.putUnicodeLE(getName(), out); - } else { - StringUtil.putCompressedUnicode(getName(), out); - } - } - } + @Override + public void serialize(LittleEndianOutput out) { + out.writeShort(field_1_xf_index); + if (isBuiltin()) { + out.writeByte(field_2_builtin_style); + out.writeByte(field_3_outline_style_level); + } else { + out.writeShort(field_4_name.length()); + out.writeByte(field_3_stringHasMultibyte ? 0x01 : 0x00); + if (field_3_stringHasMultibyte) { + StringUtil.putUnicodeLE(getName(), out); + } else { + StringUtil.putCompressedUnicode(getName(), out); + } + } + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public StyleRecord copy() { - return new StyleRecord(this); - } + @Override + public StyleRecord copy() { + return new StyleRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.STYLE; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.STYLE; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "xfIndex", this::getXFIndex, - "type", () -> isBuiltin() ? "built-in" : "user-defined", - "builtin_style", () -> field_2_builtin_style, - "outline_level", () -> field_3_outline_style_level, - "name", this::getName - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "xfIndex", this::getXFIndex, + "type", () -> isBuiltin() ? "built-in" : "user-defined", + "builtin_style", () -> field_2_builtin_style, + "outline_level", () -> field_3_outline_style_level, + "name", this::getName + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java index e67a9f2ca9..6138fcbb71 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/SubRecord.java @@ -38,61 +38,61 @@ import org.apache.poi.util.LittleEndianOutputStream; */ public abstract class SubRecord implements Duplicatable, GenericRecord { - public enum SubRecordTypes { - UNKNOWN(-1, UnknownSubRecord::new), - END(0x0000, EndSubRecord::new), - GROUP_MARKER(0x0006, GroupMarkerSubRecord::new), - FT_CF(0x0007, FtCfSubRecord::new), - FT_PIO_GRBIT(0x0008, FtPioGrbitSubRecord::new), - EMBEDDED_OBJECT_REF(0x0009, EmbeddedObjectRefSubRecord::new), - FT_CBLS(0x000C, FtCblsSubRecord::new), - NOTE_STRUCTURE(0x000D, NoteStructureSubRecord::new), - LBS_DATA(0x0013, LbsDataSubRecord::new), - COMMON_OBJECT_DATA(0x0015, CommonObjectDataSubRecord::new), - ; + public enum SubRecordTypes { + UNKNOWN(-1, UnknownSubRecord::new), + END(0x0000, EndSubRecord::new), + GROUP_MARKER(0x0006, GroupMarkerSubRecord::new), + FT_CF(0x0007, FtCfSubRecord::new), + FT_PIO_GRBIT(0x0008, FtPioGrbitSubRecord::new), + EMBEDDED_OBJECT_REF(0x0009, EmbeddedObjectRefSubRecord::new), + FT_CBLS(0x000C, FtCblsSubRecord::new), + NOTE_STRUCTURE(0x000D, NoteStructureSubRecord::new), + LBS_DATA(0x0013, LbsDataSubRecord::new), + COMMON_OBJECT_DATA(0x0015, CommonObjectDataSubRecord::new), + ; - @FunctionalInterface - public interface RecordConstructor { - /** - * read a sub-record from the supplied stream - * - * @param in the stream to read from - * @param cmoOt the objectType field of the containing CommonObjectDataSubRecord, - * we need it to propagate to next sub-records as it defines what data follows - * @return the created sub-record - */ - T apply(LittleEndianInput in, int size, int cmoOt); - } + @FunctionalInterface + public interface RecordConstructor { + /** + * read a sub-record from the supplied stream + * + * @param in the stream to read from + * @param cmoOt the objectType field of the containing CommonObjectDataSubRecord, + * we need it to propagate to next sub-records as it defines what data follows + * @return the created sub-record + */ + T apply(LittleEndianInput in, int size, int cmoOt); + } - private static final Map LOOKUP = - Arrays.stream(values()).collect(Collectors.toMap(SubRecordTypes::getSid, Function.identity())); + private static final Map LOOKUP = + Arrays.stream(values()).collect(Collectors.toMap(SubRecordTypes::getSid, Function.identity())); - public final short sid; - public final RecordConstructor recordConstructor; + public final short sid; + public final RecordConstructor recordConstructor; - SubRecordTypes(int sid, RecordConstructor recordConstructor) { - this.sid = (short)sid; - this.recordConstructor = recordConstructor; - } + SubRecordTypes(int sid, RecordConstructor recordConstructor) { + this.sid = (short)sid; + this.recordConstructor = recordConstructor; + } - public static SubRecordTypes forSID(int sid) { - return LOOKUP.getOrDefault((short)sid, UNKNOWN); - } + public static SubRecordTypes forSID(int sid) { + return LOOKUP.getOrDefault((short)sid, UNKNOWN); + } - public short getSid() { - return sid; - } - } + public short getSid() { + return sid; + } + } - //arbitrarily selected; may need to increase - private static final int MAX_RECORD_LENGTH = 1_000_000; + //arbitrarily selected; may need to increase + private static final int MAX_RECORD_LENGTH = 1_000_000; - protected SubRecord() {} + protected SubRecord() {} - protected SubRecord(SubRecord other) {} + protected SubRecord(SubRecord other) {} - /** + /** * read a sub-record from the supplied stream * * @param in the stream to read from @@ -101,35 +101,35 @@ public abstract class SubRecord implements Duplicatable, GenericRecord { * @return the created sub-record */ public static SubRecord createSubRecord(LittleEndianInput in, int cmoOt) { - int sid = in.readUShort(); - // Often (but not always) the datasize for the sub-record - int size = in.readUShort(); - SubRecordTypes srt = SubRecordTypes.forSID(sid); - return srt.recordConstructor.apply(in, size, srt == SubRecordTypes.UNKNOWN ? sid : cmoOt); - } + int sid = in.readUShort(); + // Often (but not always) the datasize for the sub-record + int size = in.readUShort(); + SubRecordTypes srt = SubRecordTypes.forSID(sid); + return srt.recordConstructor.apply(in, size, srt == SubRecordTypes.UNKNOWN ? sid : cmoOt); + } - @Override - public final String toString() { - return GenericRecordJsonWriter.marshal(this); - } + @Override + public final String toString() { + return GenericRecordJsonWriter.marshal(this); + } - /** - * @return the size of the data for this record (which is always 4 bytes less than the total - * record size). Note however, that ushort encoded after the record sid is usually but not - * always the data size. - */ - protected abstract int getDataSize(); - public byte[] serialize() { - int size = getDataSize() + 4; - UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(size); - serialize(new LittleEndianOutputStream(baos)); - if (baos.size() != size) { - throw new RuntimeException("write size mismatch"); - } - return baos.toByteArray(); - } + /** + * @return the size of the data for this record (which is always 4 bytes less than the total + * record size). Note however, that ushort encoded after the record sid is usually but not + * always the data size. + */ + protected abstract int getDataSize(); + public byte[] serialize() { + int size = getDataSize() + 4; + UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(size); + serialize(new LittleEndianOutputStream(baos)); + if (baos.size() != size) { + throw new RuntimeException("write size mismatch"); + } + return baos.toByteArray(); + } - public abstract void serialize(LittleEndianOutput out); + public abstract void serialize(LittleEndianOutput out); /** @@ -146,48 +146,48 @@ public abstract class SubRecord implements Duplicatable, GenericRecord { private static final class UnknownSubRecord extends SubRecord { - private final int _sid; - private final byte[] _data; + private final int _sid; + private final byte[] _data; - public UnknownSubRecord(LittleEndianInput in, int size, int sid) { - _sid = sid; - byte[] buf = IOUtils.safelyAllocate(size, MAX_RECORD_LENGTH); - in.readFully(buf); - _data = buf; - } - @Override - protected int getDataSize() { - return _data.length; - } - @Override - public void serialize(LittleEndianOutput out) { - out.writeShort(_sid); - out.writeShort(_data.length); - out.write(_data); - } + public UnknownSubRecord(LittleEndianInput in, int size, int sid) { + _sid = sid; + byte[] buf = IOUtils.safelyAllocate(size, MAX_RECORD_LENGTH); + in.readFully(buf); + _data = buf; + } + @Override + protected int getDataSize() { + return _data.length; + } + @Override + public void serialize(LittleEndianOutput out) { + out.writeShort(_sid); + out.writeShort(_data.length); + out.write(_data); + } - @Override - public UnknownSubRecord copy() { - return this; - } + @Override + public UnknownSubRecord copy() { + return this; + } - @Override - public SubRecordTypes getGenericRecordType() { - return SubRecordTypes.UNKNOWN; - } + @Override + public SubRecordTypes getGenericRecordType() { + return SubRecordTypes.UNKNOWN; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "sid", () -> _sid, - "data", () -> _data - ); - } - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "sid", () -> _sid, + "data", () -> _data + ); + } + } - @Override - public abstract SubRecord copy(); + @Override + public abstract SubRecord copy(); - @Override - public abstract SubRecordTypes getGenericRecordType(); + @Override + public abstract SubRecordTypes getGenericRecordType(); } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/SupBookRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/SupBookRecord.java index 2d610ac981..8c79429e8c 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/SupBookRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/SupBookRecord.java @@ -200,39 +200,39 @@ public final class SupBookRecord extends StandardRecord { } private static String decodeFileName(String encodedUrl) { /* see "MICROSOFT OFFICE EXCEL 97-2007 BINARY FILE FORMAT SPECIFICATION" */ - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); for(int i=1; i> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "range", this::getRange, - "flags", getBitsAsString(this::getFlags, - new BitField[]{alwaysCalc, calcOnOpen, rowOrColInpCell, oneOrTwoVar, rowDeleted, colDeleted}, - new String[]{"ALWAYS_CALC","CALC_ON_OPEN","ROW_OR_COL_INP_CELL","ONE_OR_TWO_VAR","ROW_DELETED","COL_DELETED"}), - "reserved", () -> field_6_res, - "rowInput", () -> cr(field_7_rowInputRow, field_8_colInputRow), - "colInput", () -> cr(field_9_rowInputCol, field_10_colInputCol) - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "range", this::getRange, + "flags", getBitsAsString(this::getFlags, + new BitField[]{alwaysCalc, calcOnOpen, rowOrColInpCell, oneOrTwoVar, rowDeleted, colDeleted}, + new String[]{"ALWAYS_CALC","CALC_ON_OPEN","ROW_OR_COL_INP_CELL","ONE_OR_TWO_VAR","ROW_DELETED","COL_DELETED"}), + "reserved", () -> field_6_res, + "rowInput", () -> cr(field_7_rowInputRow, field_8_colInputRow), + "colInput", () -> cr(field_9_rowInputCol, field_10_colInputCol) + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/TableStylesRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/TableStylesRecord.java index b1ffccc513..557a3e9418 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/TableStylesRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/TableStylesRecord.java @@ -28,83 +28,83 @@ import org.apache.poi.util.StringUtil; * TABLESTYLES (0x088E) */ public final class TableStylesRecord extends StandardRecord { - public static final short sid = 0x088E; + public static final short sid = 0x088E; - private int rt; - private int grbitFrt; - private final byte[] unused = new byte[8]; - private int cts; + private int rt; + private int grbitFrt; + private final byte[] unused = new byte[8]; + private int cts; - private String rgchDefListStyle; - private String rgchDefPivotStyle; + private String rgchDefListStyle; + private String rgchDefPivotStyle; - public TableStylesRecord(TableStylesRecord other) { - super(other); - rt = other.rt; - grbitFrt = other.grbitFrt; - System.arraycopy(other.unused, 0, unused, 0, unused.length); - cts = other.cts; - rgchDefListStyle = other.rgchDefListStyle; - rgchDefPivotStyle = other.rgchDefPivotStyle; - } + public TableStylesRecord(TableStylesRecord other) { + super(other); + rt = other.rt; + grbitFrt = other.grbitFrt; + System.arraycopy(other.unused, 0, unused, 0, unused.length); + cts = other.cts; + rgchDefListStyle = other.rgchDefListStyle; + rgchDefPivotStyle = other.rgchDefPivotStyle; + } - public TableStylesRecord(RecordInputStream in) { - rt = in.readUShort(); - grbitFrt = in.readUShort(); - in.readFully(unused); - cts = in.readInt(); - int cchDefListStyle = in.readUShort(); - int cchDefPivotStyle = in.readUShort(); + public TableStylesRecord(RecordInputStream in) { + rt = in.readUShort(); + grbitFrt = in.readUShort(); + in.readFully(unused); + cts = in.readInt(); + int cchDefListStyle = in.readUShort(); + int cchDefPivotStyle = in.readUShort(); - rgchDefListStyle = in.readUnicodeLEString(cchDefListStyle); - rgchDefPivotStyle = in.readUnicodeLEString(cchDefPivotStyle); - } + rgchDefListStyle = in.readUnicodeLEString(cchDefListStyle); + rgchDefPivotStyle = in.readUnicodeLEString(cchDefPivotStyle); + } - @Override - protected void serialize(LittleEndianOutput out) { - out.writeShort(rt); - out.writeShort(grbitFrt); - out.write(unused); - out.writeInt(cts); + @Override + protected void serialize(LittleEndianOutput out) { + out.writeShort(rt); + out.writeShort(grbitFrt); + out.write(unused); + out.writeInt(cts); - out.writeShort(rgchDefListStyle.length()); - out.writeShort(rgchDefPivotStyle.length()); + out.writeShort(rgchDefListStyle.length()); + out.writeShort(rgchDefPivotStyle.length()); - StringUtil.putUnicodeLE(rgchDefListStyle, out); - StringUtil.putUnicodeLE(rgchDefPivotStyle, out); - } + StringUtil.putUnicodeLE(rgchDefListStyle, out); + StringUtil.putUnicodeLE(rgchDefPivotStyle, out); + } - @Override - protected int getDataSize() { - return 2 + 2 + 8 + 4 + 2 + 2 - + (2*rgchDefListStyle.length()) + (2*rgchDefPivotStyle.length()); - } + @Override + protected int getDataSize() { + return 2 + 2 + 8 + 4 + 2 + 2 + + (2*rgchDefListStyle.length()) + (2*rgchDefPivotStyle.length()); + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public TableStylesRecord copy() { - return new TableStylesRecord(this); - } + @Override + public TableStylesRecord copy() { + return new TableStylesRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.TABLE_STYLES; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.TABLE_STYLES; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "rt", () -> rt, - "grbitFrt", () -> grbitFrt, - "unused", () -> unused, - "cts", () -> cts, - "rgchDefListStyle", () -> rgchDefListStyle, - "rgchDefPivotStyle", () -> rgchDefPivotStyle - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "rt", () -> rt, + "grbitFrt", () -> grbitFrt, + "unused", () -> unused, + "cts", () -> cts, + "rgchDefListStyle", () -> rgchDefListStyle, + "rgchDefPivotStyle", () -> rgchDefPivotStyle + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/TextObjectRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/TextObjectRecord.java index 8beeb3a621..c399bd64f9 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/TextObjectRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/TextObjectRecord.java @@ -38,306 +38,306 @@ import org.apache.poi.util.RecordFormatException; * contains the formatting runs. */ public final class TextObjectRecord extends ContinuableRecord { - public static final short sid = 0x01B6; + public static final short sid = 0x01B6; - private static final int FORMAT_RUN_ENCODED_SIZE = 8; // 2 shorts and 4 bytes reserved + private static final int FORMAT_RUN_ENCODED_SIZE = 8; // 2 shorts and 4 bytes reserved - private static final BitField HorizontalTextAlignment = BitFieldFactory.getInstance(0x000E); - private static final BitField VerticalTextAlignment = BitFieldFactory.getInstance(0x0070); - private static final BitField textLocked = BitFieldFactory.getInstance(0x0200); + private static final BitField HorizontalTextAlignment = BitFieldFactory.getInstance(0x000E); + private static final BitField VerticalTextAlignment = BitFieldFactory.getInstance(0x0070); + private static final BitField textLocked = BitFieldFactory.getInstance(0x0200); - public static final short HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED = 1; - public static final short HORIZONTAL_TEXT_ALIGNMENT_CENTERED = 2; - public static final short HORIZONTAL_TEXT_ALIGNMENT_RIGHT_ALIGNED = 3; - public static final short HORIZONTAL_TEXT_ALIGNMENT_JUSTIFIED = 4; - public static final short VERTICAL_TEXT_ALIGNMENT_TOP = 1; - public static final short VERTICAL_TEXT_ALIGNMENT_CENTER = 2; - public static final short VERTICAL_TEXT_ALIGNMENT_BOTTOM = 3; - public static final short VERTICAL_TEXT_ALIGNMENT_JUSTIFY = 4; + public static final short HORIZONTAL_TEXT_ALIGNMENT_LEFT_ALIGNED = 1; + public static final short HORIZONTAL_TEXT_ALIGNMENT_CENTERED = 2; + public static final short HORIZONTAL_TEXT_ALIGNMENT_RIGHT_ALIGNED = 3; + public static final short HORIZONTAL_TEXT_ALIGNMENT_JUSTIFIED = 4; + public static final short VERTICAL_TEXT_ALIGNMENT_TOP = 1; + public static final short VERTICAL_TEXT_ALIGNMENT_CENTER = 2; + public static final short VERTICAL_TEXT_ALIGNMENT_BOTTOM = 3; + public static final short VERTICAL_TEXT_ALIGNMENT_JUSTIFY = 4; - public static final short TEXT_ORIENTATION_NONE = 0; - public static final short TEXT_ORIENTATION_TOP_TO_BOTTOM = 1; - public static final short TEXT_ORIENTATION_ROT_RIGHT = 2; - public static final short TEXT_ORIENTATION_ROT_LEFT = 3; + public static final short TEXT_ORIENTATION_NONE = 0; + public static final short TEXT_ORIENTATION_TOP_TO_BOTTOM = 1; + public static final short TEXT_ORIENTATION_ROT_RIGHT = 2; + public static final short TEXT_ORIENTATION_ROT_LEFT = 3; - private int field_1_options; - private int field_2_textOrientation; - private int field_3_reserved4; - private int field_4_reserved5; - private int field_5_reserved6; - private int field_8_reserved7; + private int field_1_options; + private int field_2_textOrientation; + private int field_3_reserved4; + private int field_4_reserved5; + private int field_5_reserved6; + private int field_8_reserved7; - private HSSFRichTextString _text; + private HSSFRichTextString _text; - /* - * Note - the next three fields are very similar to those on - * EmbededObjectRefSubRecord(ftPictFmla 0x0009) - * - * some observed values for the 4 bytes preceding the formula: C0 5E 86 03 - * C0 11 AC 02 80 F1 8A 03 D4 F0 8A 03 - */ - private int _unknownPreFormulaInt; - /** expect tRef, tRef3D, tArea, tArea3D or tName */ - private OperandPtg _linkRefPtg; - /** - * Not clear if needed . Excel seems to be OK if this byte is not present. - * Value is often the same as the earlier firstColumn byte. */ - private Byte _unknownPostFormulaByte; + /* + * Note - the next three fields are very similar to those on + * EmbededObjectRefSubRecord(ftPictFmla 0x0009) + * + * some observed values for the 4 bytes preceding the formula: C0 5E 86 03 + * C0 11 AC 02 80 F1 8A 03 D4 F0 8A 03 + */ + private int _unknownPreFormulaInt; + /** expect tRef, tRef3D, tArea, tArea3D or tName */ + private OperandPtg _linkRefPtg; + /** + * Not clear if needed . Excel seems to be OK if this byte is not present. + * Value is often the same as the earlier firstColumn byte. */ + private Byte _unknownPostFormulaByte; - public TextObjectRecord() {} + public TextObjectRecord() {} - public TextObjectRecord(TextObjectRecord other) { - super(other); - field_1_options = other.field_1_options; - field_2_textOrientation = other.field_2_textOrientation; - field_3_reserved4 = other.field_3_reserved4; - field_4_reserved5 = other.field_4_reserved5; - field_5_reserved6 = other.field_5_reserved6; - field_8_reserved7 = other.field_8_reserved7; + public TextObjectRecord(TextObjectRecord other) { + super(other); + field_1_options = other.field_1_options; + field_2_textOrientation = other.field_2_textOrientation; + field_3_reserved4 = other.field_3_reserved4; + field_4_reserved5 = other.field_4_reserved5; + field_5_reserved6 = other.field_5_reserved6; + field_8_reserved7 = other.field_8_reserved7; - _text = other._text; + _text = other._text; - if (other._linkRefPtg != null) { - _unknownPreFormulaInt = other._unknownPreFormulaInt; - _linkRefPtg = other._linkRefPtg.copy(); - _unknownPostFormulaByte = other._unknownPostFormulaByte; - } - } + if (other._linkRefPtg != null) { + _unknownPreFormulaInt = other._unknownPreFormulaInt; + _linkRefPtg = other._linkRefPtg.copy(); + _unknownPostFormulaByte = other._unknownPostFormulaByte; + } + } - public TextObjectRecord(RecordInputStream in) { - field_1_options = in.readUShort(); - field_2_textOrientation = in.readUShort(); - field_3_reserved4 = in.readUShort(); - field_4_reserved5 = in.readUShort(); - field_5_reserved6 = in.readUShort(); - int field_6_textLength = in.readUShort(); - int field_7_formattingDataLength = in.readUShort(); - field_8_reserved7 = in.readInt(); + public TextObjectRecord(RecordInputStream in) { + field_1_options = in.readUShort(); + field_2_textOrientation = in.readUShort(); + field_3_reserved4 = in.readUShort(); + field_4_reserved5 = in.readUShort(); + field_5_reserved6 = in.readUShort(); + int field_6_textLength = in.readUShort(); + int field_7_formattingDataLength = in.readUShort(); + field_8_reserved7 = in.readInt(); - if (in.remaining() > 0) { - // Text Objects can have simple reference formulas - // (This bit not mentioned in the MS document) - if (in.remaining() < 11) { - throw new RecordFormatException("Not enough remaining data for a link formula"); - } - int formulaSize = in.readUShort(); - _unknownPreFormulaInt = in.readInt(); - Ptg[] ptgs = Ptg.readTokens(formulaSize, in); - if (ptgs.length != 1) { - throw new RecordFormatException("Read " + ptgs.length - + " tokens but expected exactly 1"); - } - _linkRefPtg = (OperandPtg) ptgs[0]; - _unknownPostFormulaByte = in.remaining() > 0 ? in.readByte() : null; - } else { - _linkRefPtg = null; - } - if (in.remaining() > 0) { - throw new RecordFormatException("Unused " + in.remaining() + " bytes at end of record"); - } + if (in.remaining() > 0) { + // Text Objects can have simple reference formulas + // (This bit not mentioned in the MS document) + if (in.remaining() < 11) { + throw new RecordFormatException("Not enough remaining data for a link formula"); + } + int formulaSize = in.readUShort(); + _unknownPreFormulaInt = in.readInt(); + Ptg[] ptgs = Ptg.readTokens(formulaSize, in); + if (ptgs.length != 1) { + throw new RecordFormatException("Read " + ptgs.length + + " tokens but expected exactly 1"); + } + _linkRefPtg = (OperandPtg) ptgs[0]; + _unknownPostFormulaByte = in.remaining() > 0 ? in.readByte() : null; + } else { + _linkRefPtg = null; + } + if (in.remaining() > 0) { + throw new RecordFormatException("Unused " + in.remaining() + " bytes at end of record"); + } - String text; - if (field_6_textLength > 0) { - text = readRawString(in, field_6_textLength); - } else { - text = ""; - } - _text = new HSSFRichTextString(text); + String text; + if (field_6_textLength > 0) { + text = readRawString(in, field_6_textLength); + } else { + text = ""; + } + _text = new HSSFRichTextString(text); - if (field_7_formattingDataLength > 0) { - processFontRuns(in, _text, field_7_formattingDataLength); - } - } + if (field_7_formattingDataLength > 0) { + processFontRuns(in, _text, field_7_formattingDataLength); + } + } - private static String readRawString(RecordInputStream in, int textLength) { - byte compressByte = in.readByte(); - boolean isCompressed = (compressByte & 0x01) == 0; - if (isCompressed) { - return in.readCompressedUnicode(textLength); - } - return in.readUnicodeLEString(textLength); - } + private static String readRawString(RecordInputStream in, int textLength) { + byte compressByte = in.readByte(); + boolean isCompressed = (compressByte & 0x01) == 0; + if (isCompressed) { + return in.readCompressedUnicode(textLength); + } + return in.readUnicodeLEString(textLength); + } - private static void processFontRuns(RecordInputStream in, HSSFRichTextString str, - int formattingRunDataLength) { - if (formattingRunDataLength % FORMAT_RUN_ENCODED_SIZE != 0) { - throw new RecordFormatException("Bad format run data length " + formattingRunDataLength - + ")"); - } - int nRuns = formattingRunDataLength / FORMAT_RUN_ENCODED_SIZE; - for (int i = 0; i < nRuns; i++) { - short index = in.readShort(); - short iFont = in.readShort(); - in.readInt(); // skip reserved. - str.applyFont(index, str.length(), iFont); - } - } + private static void processFontRuns(RecordInputStream in, HSSFRichTextString str, + int formattingRunDataLength) { + if (formattingRunDataLength % FORMAT_RUN_ENCODED_SIZE != 0) { + throw new RecordFormatException("Bad format run data length " + formattingRunDataLength + + ")"); + } + int nRuns = formattingRunDataLength / FORMAT_RUN_ENCODED_SIZE; + for (int i = 0; i < nRuns; i++) { + short index = in.readShort(); + short iFont = in.readShort(); + in.readInt(); // skip reserved. + str.applyFont(index, str.length(), iFont); + } + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - private void serializeTXORecord(ContinuableRecordOutput out) { + private void serializeTXORecord(ContinuableRecordOutput out) { - out.writeShort(field_1_options); - out.writeShort(field_2_textOrientation); - out.writeShort(field_3_reserved4); - out.writeShort(field_4_reserved5); - out.writeShort(field_5_reserved6); - out.writeShort(_text.length()); - out.writeShort(getFormattingDataLength()); - out.writeInt(field_8_reserved7); + out.writeShort(field_1_options); + out.writeShort(field_2_textOrientation); + out.writeShort(field_3_reserved4); + out.writeShort(field_4_reserved5); + out.writeShort(field_5_reserved6); + out.writeShort(_text.length()); + out.writeShort(getFormattingDataLength()); + out.writeInt(field_8_reserved7); - if (_linkRefPtg != null) { - int formulaSize = _linkRefPtg.getSize(); - out.writeShort(formulaSize); - out.writeInt(_unknownPreFormulaInt); - _linkRefPtg.write(out); - if (_unknownPostFormulaByte != null) { - out.writeByte(_unknownPostFormulaByte); - } - } - } + if (_linkRefPtg != null) { + int formulaSize = _linkRefPtg.getSize(); + out.writeShort(formulaSize); + out.writeInt(_unknownPreFormulaInt); + _linkRefPtg.write(out); + if (_unknownPostFormulaByte != null) { + out.writeByte(_unknownPostFormulaByte); + } + } + } - private void serializeTrailingRecords(ContinuableRecordOutput out) { - out.writeContinue(); - out.writeStringData(_text.getString()); - out.writeContinue(); - writeFormatData(out, _text); - } + private void serializeTrailingRecords(ContinuableRecordOutput out) { + out.writeContinue(); + out.writeStringData(_text.getString()); + out.writeContinue(); + writeFormatData(out, _text); + } - protected void serialize(ContinuableRecordOutput out) { + protected void serialize(ContinuableRecordOutput out) { - serializeTXORecord(out); - if (_text.getString().length() > 0) { - serializeTrailingRecords(out); - } - } + serializeTXORecord(out); + if (_text.getString().length() > 0) { + serializeTrailingRecords(out); + } + } - private int getFormattingDataLength() { - if (_text.length() < 1) { - // important - no formatting data if text is empty - return 0; - } - return (_text.numFormattingRuns() + 1) * FORMAT_RUN_ENCODED_SIZE; - } + private int getFormattingDataLength() { + if (_text.length() < 1) { + // important - no formatting data if text is empty + return 0; + } + return (_text.numFormattingRuns() + 1) * FORMAT_RUN_ENCODED_SIZE; + } - private static void writeFormatData(ContinuableRecordOutput out , HSSFRichTextString str) { - int nRuns = str.numFormattingRuns(); - for (int i = 0; i < nRuns; i++) { - out.writeShort(str.getIndexOfFormattingRun(i)); - int fontIndex = str.getFontOfFormattingRun(i); - out.writeShort(fontIndex == HSSFRichTextString.NO_FONT ? 0 : fontIndex); - out.writeInt(0); // skip reserved - } - out.writeShort(str.length()); - out.writeShort(0); - out.writeInt(0); // skip reserved - } + private static void writeFormatData(ContinuableRecordOutput out , HSSFRichTextString str) { + int nRuns = str.numFormattingRuns(); + for (int i = 0; i < nRuns; i++) { + out.writeShort(str.getIndexOfFormattingRun(i)); + int fontIndex = str.getFontOfFormattingRun(i); + out.writeShort(fontIndex == HSSFRichTextString.NO_FONT ? 0 : fontIndex); + out.writeInt(0); // skip reserved + } + out.writeShort(str.length()); + out.writeShort(0); + out.writeInt(0); // skip reserved + } - /** - * Sets the Horizontal text alignment field value. - * - * @param value The horizontal alignment, use one of the HORIZONTAL_TEXT_ALIGNMENT_... constants in this class - */ - public void setHorizontalTextAlignment(int value) { - field_1_options = HorizontalTextAlignment.setValue(field_1_options, value); - } + /** + * Sets the Horizontal text alignment field value. + * + * @param value The horizontal alignment, use one of the HORIZONTAL_TEXT_ALIGNMENT_... constants in this class + */ + public void setHorizontalTextAlignment(int value) { + field_1_options = HorizontalTextAlignment.setValue(field_1_options, value); + } - /** - * @return the Horizontal text alignment field value. - */ - public int getHorizontalTextAlignment() { - return HorizontalTextAlignment.getValue(field_1_options); - } + /** + * @return the Horizontal text alignment field value. + */ + public int getHorizontalTextAlignment() { + return HorizontalTextAlignment.getValue(field_1_options); + } - /** - * Sets the Vertical text alignment field value. - * - * @param value The vertical alignment, use one of the VERTIUCAL_TEST_ALIGNMENT_... constants in this class - */ - public void setVerticalTextAlignment(int value) { - field_1_options = VerticalTextAlignment.setValue(field_1_options, value); - } + /** + * Sets the Vertical text alignment field value. + * + * @param value The vertical alignment, use one of the VERTIUCAL_TEST_ALIGNMENT_... constants in this class + */ + public void setVerticalTextAlignment(int value) { + field_1_options = VerticalTextAlignment.setValue(field_1_options, value); + } - /** - * @return the Vertical text alignment field value. - */ - public int getVerticalTextAlignment() { - return VerticalTextAlignment.getValue(field_1_options); - } + /** + * @return the Vertical text alignment field value. + */ + public int getVerticalTextAlignment() { + return VerticalTextAlignment.getValue(field_1_options); + } - /** - * Sets the text locked field value. - * - * @param value If the text should be locked - */ - public void setTextLocked(boolean value) { - field_1_options = textLocked.setBoolean(field_1_options, value); - } + /** + * Sets the text locked field value. + * + * @param value If the text should be locked + */ + public void setTextLocked(boolean value) { + field_1_options = textLocked.setBoolean(field_1_options, value); + } - /** - * @return the text locked field value. - */ - public boolean isTextLocked() { - return textLocked.isSet(field_1_options); - } + /** + * @return the text locked field value. + */ + public boolean isTextLocked() { + return textLocked.isSet(field_1_options); + } - /** - * Get the text orientation field for the TextObjectBase record. - * - * @return One of TEXT_ORIENTATION_NONE TEXT_ORIENTATION_TOP_TO_BOTTOM - * TEXT_ORIENTATION_ROT_RIGHT TEXT_ORIENTATION_ROT_LEFT - */ - public int getTextOrientation() { - return field_2_textOrientation; - } + /** + * Get the text orientation field for the TextObjectBase record. + * + * @return One of TEXT_ORIENTATION_NONE TEXT_ORIENTATION_TOP_TO_BOTTOM + * TEXT_ORIENTATION_ROT_RIGHT TEXT_ORIENTATION_ROT_LEFT + */ + public int getTextOrientation() { + return field_2_textOrientation; + } - /** - * Set the text orientation field for the TextObjectBase record. - * - * @param textOrientation - * One of TEXT_ORIENTATION_NONE TEXT_ORIENTATION_TOP_TO_BOTTOM - * TEXT_ORIENTATION_ROT_RIGHT TEXT_ORIENTATION_ROT_LEFT - */ - public void setTextOrientation(int textOrientation) { - this.field_2_textOrientation = textOrientation; - } + /** + * Set the text orientation field for the TextObjectBase record. + * + * @param textOrientation + * One of TEXT_ORIENTATION_NONE TEXT_ORIENTATION_TOP_TO_BOTTOM + * TEXT_ORIENTATION_ROT_RIGHT TEXT_ORIENTATION_ROT_LEFT + */ + public void setTextOrientation(int textOrientation) { + this.field_2_textOrientation = textOrientation; + } - public HSSFRichTextString getStr() { - return _text; - } + public HSSFRichTextString getStr() { + return _text; + } - public void setStr(HSSFRichTextString str) { - _text = str; - } + public void setStr(HSSFRichTextString str) { + _text = str; + } - public Ptg getLinkRefPtg() { - return _linkRefPtg; - } + public Ptg getLinkRefPtg() { + return _linkRefPtg; + } - @Override - public TextObjectRecord copy() { - return new TextObjectRecord(this); - } + @Override + public TextObjectRecord copy() { + return new TextObjectRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.TEXT_OBJECT; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.TEXT_OBJECT; + } - @Override - public Map> getGenericProperties() { - final Map> m = new LinkedHashMap<>(); - m.put("isHorizontal", this::getHorizontalTextAlignment); - m.put("isVertical", this::getVerticalTextAlignment); - m.put("textLocked", this::isTextLocked); - m.put("textOrientation", this::getTextOrientation); - m.put("string", this::getStr); - m.put("reserved4", () -> field_3_reserved4); - m.put("reserved5", () -> field_4_reserved5); - m.put("reserved6", () -> field_5_reserved6); - m.put("reserved7", () -> field_8_reserved7); - return Collections.unmodifiableMap(m); - } + @Override + public Map> getGenericProperties() { + final Map> m = new LinkedHashMap<>(); + m.put("isHorizontal", this::getHorizontalTextAlignment); + m.put("isVertical", this::getVerticalTextAlignment); + m.put("textLocked", this::isTextLocked); + m.put("textOrientation", this::getTextOrientation); + m.put("string", this::getStr); + m.put("reserved4", () -> field_3_reserved4); + m.put("reserved5", () -> field_4_reserved5); + m.put("reserved6", () -> field_5_reserved6); + m.put("reserved7", () -> field_8_reserved7); + return Collections.unmodifiableMap(m); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/UncalcedRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/UncalcedRecord.java index f53118d8b1..c274ae7a14 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/UncalcedRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/UncalcedRecord.java @@ -28,51 +28,51 @@ import org.apache.poi.util.LittleEndianOutput; * been recalculated before the document was saved. */ public final class UncalcedRecord extends StandardRecord { - public static final short sid = 0x005E; + public static final short sid = 0x005E; private short _reserved; - public UncalcedRecord() { + public UncalcedRecord() { _reserved = 0; - } + } - public UncalcedRecord(UncalcedRecord other) { - super(other); - _reserved = other._reserved; - } + public UncalcedRecord(UncalcedRecord other) { + super(other); + _reserved = other._reserved; + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - public UncalcedRecord(RecordInputStream in) { - _reserved = in.readShort(); // unused - } + public UncalcedRecord(RecordInputStream in) { + _reserved = in.readShort(); // unused + } - public void serialize(LittleEndianOutput out) { - out.writeShort(_reserved); - } + public void serialize(LittleEndianOutput out) { + out.writeShort(_reserved); + } - protected int getDataSize() { - return 2; - } + protected int getDataSize() { + return 2; + } - public static int getStaticRecordSize() { - return 6; - } + public static int getStaticRecordSize() { + return 6; + } - @Override - public UncalcedRecord copy() { - return new UncalcedRecord(this); - } + @Override + public UncalcedRecord copy() { + return new UncalcedRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.UNCALCED; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.UNCALCED; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties("reserved", () -> _reserved); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties("reserved", () -> _reserved); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/UserSViewBegin.java b/poi/src/main/java/org/apache/poi/hssf/record/UserSViewBegin.java index b283673eec..fd55f4b958 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/UserSViewBegin.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/UserSViewBegin.java @@ -45,25 +45,25 @@ public final class UserSViewBegin extends StandardRecord { _rawData = data; } - /** - * construct an UserSViewBegin record. No fields are interpreted and the record will - * be serialized in its original form more or less - * @param in the RecordInputstream to read the record from - */ - public UserSViewBegin(RecordInputStream in) { - _rawData = in.readRemainder(); - } + /** + * construct an UserSViewBegin record. No fields are interpreted and the record will + * be serialized in its original form more or less + * @param in the RecordInputstream to read the record from + */ + public UserSViewBegin(RecordInputStream in) { + _rawData = in.readRemainder(); + } - /** - * spit the record out AS IS. no interpretation or identification - */ - public void serialize(LittleEndianOutput out) { - out.write(_rawData); - } + /** + * spit the record out AS IS. no interpretation or identification + */ + public void serialize(LittleEndianOutput out) { + out.write(_rawData); + } - protected int getDataSize() { - return _rawData.length; - } + protected int getDataSize() { + return _rawData.length; + } public short getSid() { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/UserSViewEnd.java b/poi/src/main/java/org/apache/poi/hssf/record/UserSViewEnd.java index 4acfa89a2e..ffb6cc3ff2 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/UserSViewEnd.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/UserSViewEnd.java @@ -29,7 +29,7 @@ import org.apache.poi.util.LittleEndianOutput; public final class UserSViewEnd extends StandardRecord { public static final short sid = 0x01AB; - private byte[] _rawData; + private byte[] _rawData; public UserSViewEnd(UserSViewEnd other) { super(other); @@ -40,25 +40,25 @@ public final class UserSViewEnd extends StandardRecord { _rawData = data; } - /** - * construct an UserSViewEnd record. No fields are interpreted and the record will - * be serialized in its original form more or less - * @param in the RecordInputstream to read the record from - */ - public UserSViewEnd(RecordInputStream in) { - _rawData = in.readRemainder(); - } + /** + * construct an UserSViewEnd record. No fields are interpreted and the record will + * be serialized in its original form more or less + * @param in the RecordInputstream to read the record from + */ + public UserSViewEnd(RecordInputStream in) { + _rawData = in.readRemainder(); + } - /** - * spit the record out AS IS. no interpretation or identification - */ - public void serialize(LittleEndianOutput out) { - out.write(_rawData); - } + /** + * spit the record out AS IS. no interpretation or identification + */ + public void serialize(LittleEndianOutput out) { + out.write(_rawData); + } - protected int getDataSize() { - return _rawData.length; - } + protected int getDataSize() { + return _rawData.length; + } public short getSid() { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/VCenterRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/VCenterRecord.java index 4090730e9b..439ddb0e2b 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/VCenterRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/VCenterRecord.java @@ -51,7 +51,7 @@ public final class VCenterRecord extends StandardRecord { public void setVCenter(boolean hc) { - field_1_vcenter = hc ? 1 : 0; + field_1_vcenter = hc ? 1 : 0; } /** diff --git a/poi/src/main/java/org/apache/poi/hssf/record/VerticalPageBreakRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/VerticalPageBreakRecord.java index bd28b190c2..3dff044ae0 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/VerticalPageBreakRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/VerticalPageBreakRecord.java @@ -24,35 +24,35 @@ package org.apache.poi.hssf.record; */ public final class VerticalPageBreakRecord extends PageBreakRecord { - public static final short sid = 0x001A; + public static final short sid = 0x001A; - /** - * Creates an empty vertical page break record - */ - public VerticalPageBreakRecord() {} + /** + * Creates an empty vertical page break record + */ + public VerticalPageBreakRecord() {} - public VerticalPageBreakRecord(VerticalPageBreakRecord other) { - super(other); - } + public VerticalPageBreakRecord(VerticalPageBreakRecord other) { + super(other); + } - /** - * @param in the RecordInputstream to read the record from - */ - public VerticalPageBreakRecord(RecordInputStream in) { - super(in); - } + /** + * @param in the RecordInputstream to read the record from + */ + public VerticalPageBreakRecord(RecordInputStream in) { + super(in); + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - @Override - public VerticalPageBreakRecord copy() { - return new VerticalPageBreakRecord(this); - } + @Override + public VerticalPageBreakRecord copy() { + return new VerticalPageBreakRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.VERTICAL_PAGE_BREAK; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.VERTICAL_PAGE_BREAK; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/WindowOneRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/WindowOneRecord.java index 8adcd475bb..5652020757 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/WindowOneRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/WindowOneRecord.java @@ -196,8 +196,8 @@ public final class WindowOneRecord extends StandardRecord { // end bitfields public void setActiveSheetIndex(int index) { - field_6_active_sheet = index; - } + field_6_active_sheet = index; + } /** * Sets the first visible sheet in the worksheet tab-bar. This method does not @@ -338,7 +338,7 @@ public final class WindowOneRecord extends StandardRecord { * @return the index of the currently displayed sheet */ public int getActiveSheetIndex() { - return field_6_active_sheet; + return field_6_active_sheet; } /** diff --git a/poi/src/main/java/org/apache/poi/hssf/record/WriteAccessRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/WriteAccessRecord.java index 6607d85487..6c54028ffe 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/WriteAccessRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/WriteAccessRecord.java @@ -34,135 +34,135 @@ import org.apache.poi.util.StringUtil; * login, on Windoze its the name you typed when you installed the thing) */ public final class WriteAccessRecord extends StandardRecord { - public static final short sid = 0x005C; + public static final short sid = 0x005C; - private static final byte PAD_CHAR = (byte) ' '; - private static final int DATA_SIZE = 112; - /** this record is always padded to a constant length */ - private static final byte[] PADDING = new byte[DATA_SIZE]; - static { - Arrays.fill(PADDING, PAD_CHAR); - } + private static final byte PAD_CHAR = (byte) ' '; + private static final int DATA_SIZE = 112; + /** this record is always padded to a constant length */ + private static final byte[] PADDING = new byte[DATA_SIZE]; + static { + Arrays.fill(PADDING, PAD_CHAR); + } - private String field_1_username; + private String field_1_username; - public WriteAccessRecord() { - setUsername(""); - } + public WriteAccessRecord() { + setUsername(""); + } - public WriteAccessRecord(WriteAccessRecord other) { - super(other); - field_1_username = other.field_1_username; - } + public WriteAccessRecord(WriteAccessRecord other) { + super(other); + field_1_username = other.field_1_username; + } - public WriteAccessRecord(RecordInputStream in) { - if (in.remaining() > DATA_SIZE) { - throw new RecordFormatException("Expected data size (" + DATA_SIZE + ") but got (" - + in.remaining() + ")"); - } - // The string is always 112 characters (padded with spaces), therefore - // this record can not be continued. + public WriteAccessRecord(RecordInputStream in) { + if (in.remaining() > DATA_SIZE) { + throw new RecordFormatException("Expected data size (" + DATA_SIZE + ") but got (" + + in.remaining() + ")"); + } + // The string is always 112 characters (padded with spaces), therefore + // this record can not be continued. - int nChars = in.readUShort(); - int is16BitFlag = in.readUByte(); - if (nChars > DATA_SIZE || (is16BitFlag & 0xFE) != 0) { - // String header looks wrong (probably missing) - // OOO doc says this is optional anyway. - // reconstruct data - byte[] data = new byte[3 + in.remaining()]; - LittleEndian.putUShort(data, 0, nChars); - LittleEndian.putByte(data, 2, is16BitFlag); - in.readFully(data, 3, data.length-3); - String rawValue = new String(data, StringUtil.UTF8); - setUsername(rawValue.trim()); - return; - } + int nChars = in.readUShort(); + int is16BitFlag = in.readUByte(); + if (nChars > DATA_SIZE || (is16BitFlag & 0xFE) != 0) { + // String header looks wrong (probably missing) + // OOO doc says this is optional anyway. + // reconstruct data + byte[] data = new byte[3 + in.remaining()]; + LittleEndian.putUShort(data, 0, nChars); + LittleEndian.putByte(data, 2, is16BitFlag); + in.readFully(data, 3, data.length-3); + String rawValue = new String(data, StringUtil.UTF8); + setUsername(rawValue.trim()); + return; + } - String rawText; - if ((is16BitFlag & 0x01) == 0x00) { - rawText = StringUtil.readCompressedUnicode(in, nChars); - } else { - rawText = StringUtil.readUnicodeLE(in, nChars); - } - field_1_username = rawText.trim(); + String rawText; + if ((is16BitFlag & 0x01) == 0x00) { + rawText = StringUtil.readCompressedUnicode(in, nChars); + } else { + rawText = StringUtil.readUnicodeLE(in, nChars); + } + field_1_username = rawText.trim(); - // consume padding - int padSize = in.remaining(); - while (padSize > 0) { - // in some cases this seems to be garbage (non spaces) - in.readUByte(); - padSize--; - } - } + // consume padding + int padSize = in.remaining(); + while (padSize > 0) { + // in some cases this seems to be garbage (non spaces) + in.readUByte(); + padSize--; + } + } - /** - * set the username for the user that created the report. HSSF uses the - * logged in user. - * - * @param username of the user who is logged in (probably "tomcat" or "apache") - */ - public void setUsername(String username) { - boolean is16bit = StringUtil.hasMultibyte(username); - int encodedByteCount = 3 + username.length() * (is16bit ? 2 : 1); - int paddingSize = DATA_SIZE - encodedByteCount; - if (paddingSize < 0) { - throw new IllegalArgumentException("Name is too long: " + username); - } + /** + * set the username for the user that created the report. HSSF uses the + * logged in user. + * + * @param username of the user who is logged in (probably "tomcat" or "apache") + */ + public void setUsername(String username) { + boolean is16bit = StringUtil.hasMultibyte(username); + int encodedByteCount = 3 + username.length() * (is16bit ? 2 : 1); + int paddingSize = DATA_SIZE - encodedByteCount; + if (paddingSize < 0) { + throw new IllegalArgumentException("Name is too long: " + username); + } - field_1_username = username; - } + field_1_username = username; + } - /** - * get the username for the user that created the report. HSSF uses the - * logged in user. On natively created M$ Excel sheet this would be the name - * you typed in when you installed it in most cases. - * - * @return username of the user who is logged in (probably "tomcat" or "apache") - */ - public String getUsername() { - return field_1_username; - } + /** + * get the username for the user that created the report. HSSF uses the + * logged in user. On natively created M$ Excel sheet this would be the name + * you typed in when you installed it in most cases. + * + * @return username of the user who is logged in (probably "tomcat" or "apache") + */ + public String getUsername() { + return field_1_username; + } - @Override - public void serialize(LittleEndianOutput out) { - String username = getUsername(); - boolean is16bit = StringUtil.hasMultibyte(username); + @Override + public void serialize(LittleEndianOutput out) { + String username = getUsername(); + boolean is16bit = StringUtil.hasMultibyte(username); - out.writeShort(username.length()); - out.writeByte(is16bit ? 0x01 : 0x00); - if (is16bit) { - StringUtil.putUnicodeLE(username, out); - } else { - StringUtil.putCompressedUnicode(username, out); - } - int encodedByteCount = 3 + username.length() * (is16bit ? 2 : 1); - int paddingSize = DATA_SIZE - encodedByteCount; - out.write(PADDING, 0, paddingSize); - } + out.writeShort(username.length()); + out.writeByte(is16bit ? 0x01 : 0x00); + if (is16bit) { + StringUtil.putUnicodeLE(username, out); + } else { + StringUtil.putCompressedUnicode(username, out); + } + int encodedByteCount = 3 + username.length() * (is16bit ? 2 : 1); + int paddingSize = DATA_SIZE - encodedByteCount; + out.write(PADDING, 0, paddingSize); + } - @Override - protected int getDataSize() { - return DATA_SIZE; - } + @Override + protected int getDataSize() { + return DATA_SIZE; + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public WriteAccessRecord copy() { - return new WriteAccessRecord(this); - } + @Override + public WriteAccessRecord copy() { + return new WriteAccessRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.WRITE_ACCESS; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.WRITE_ACCESS; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties("username", this::getUsername); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties("username", this::getUsername); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ChartSubstreamRecordAggregate.java b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ChartSubstreamRecordAggregate.java index 79820aae71..7b508cb82b 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ChartSubstreamRecordAggregate.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ChartSubstreamRecordAggregate.java @@ -29,54 +29,54 @@ import org.apache.poi.hssf.record.*; */ public final class ChartSubstreamRecordAggregate extends RecordAggregate { - private final BOFRecord _bofRec; - /** - * All the records between BOF and EOF - */ - private final List _recs; - private PageSettingsBlock _psBlock; + private final BOFRecord _bofRec; + /** + * All the records between BOF and EOF + */ + private final List _recs; + private PageSettingsBlock _psBlock; - public ChartSubstreamRecordAggregate(RecordStream rs) { - _bofRec = (BOFRecord) rs.getNext(); - List temp = new ArrayList<>(); - while (rs.peekNextClass() != EOFRecord.class) { - if (PageSettingsBlock.isComponentRecord(rs.peekNextSid())) { - if (_psBlock != null) { - if (rs.peekNextSid() == HeaderFooterRecord.sid) { - // test samples: 45538_classic_Footer.xls, 45538_classic_Header.xls - _psBlock.addLateHeaderFooter((HeaderFooterRecord)rs.getNext()); - continue; - } - throw new IllegalStateException( - "Found more than one PageSettingsBlock in chart sub-stream, had sid: " + rs.peekNextSid()); - } - _psBlock = new PageSettingsBlock(rs); - temp.add(_psBlock); - continue; - } - temp.add(rs.getNext()); - } - _recs = temp; - org.apache.poi.hssf.record.Record eof = rs.getNext(); // no need to save EOF in field - if (!(eof instanceof EOFRecord)) { - throw new IllegalStateException("Bad chart EOF"); - } - } + public ChartSubstreamRecordAggregate(RecordStream rs) { + _bofRec = (BOFRecord) rs.getNext(); + List temp = new ArrayList<>(); + while (rs.peekNextClass() != EOFRecord.class) { + if (PageSettingsBlock.isComponentRecord(rs.peekNextSid())) { + if (_psBlock != null) { + if (rs.peekNextSid() == HeaderFooterRecord.sid) { + // test samples: 45538_classic_Footer.xls, 45538_classic_Header.xls + _psBlock.addLateHeaderFooter((HeaderFooterRecord)rs.getNext()); + continue; + } + throw new IllegalStateException( + "Found more than one PageSettingsBlock in chart sub-stream, had sid: " + rs.peekNextSid()); + } + _psBlock = new PageSettingsBlock(rs); + temp.add(_psBlock); + continue; + } + temp.add(rs.getNext()); + } + _recs = temp; + org.apache.poi.hssf.record.Record eof = rs.getNext(); // no need to save EOF in field + if (!(eof instanceof EOFRecord)) { + throw new IllegalStateException("Bad chart EOF"); + } + } - @Override + @Override public void visitContainedRecords(RecordVisitor rv) { - if (_recs.isEmpty()) { - return; - } - rv.visitRecord(_bofRec); - for (int i = 0; i < _recs.size(); i++) { - RecordBase rb = _recs.get(i); - if (rb instanceof RecordAggregate) { - ((RecordAggregate) rb).visitContainedRecords(rv); - } else { - rv.visitRecord((org.apache.poi.hssf.record.Record) rb); - } - } - rv.visitRecord(EOFRecord.instance); - } + if (_recs.isEmpty()) { + return; + } + rv.visitRecord(_bofRec); + for (int i = 0; i < _recs.size(); i++) { + RecordBase rb = _recs.get(i); + if (rb instanceof RecordAggregate) { + ((RecordAggregate) rb).visitContainedRecords(rv); + } else { + rv.visitRecord((org.apache.poi.hssf.record.Record) rb); + } + } + rv.visitRecord(EOFRecord.instance); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ColumnInfoRecordsAggregate.java b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ColumnInfoRecordsAggregate.java index e7b85625fa..8f9e24c9fb 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ColumnInfoRecordsAggregate.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ColumnInfoRecordsAggregate.java @@ -25,519 +25,519 @@ import org.apache.poi.hssf.model.RecordStream; import org.apache.poi.hssf.record.ColumnInfoRecord; public final class ColumnInfoRecordsAggregate extends RecordAggregate implements Duplicatable { - /** - * List of {@link ColumnInfoRecord}s assumed to be in order - */ - private final List records = new ArrayList<>(); + /** + * List of {@link ColumnInfoRecord}s assumed to be in order + */ + private final List records = new ArrayList<>(); - /** - * Creates an empty aggregate - */ - public ColumnInfoRecordsAggregate() {} + /** + * Creates an empty aggregate + */ + public ColumnInfoRecordsAggregate() {} - public ColumnInfoRecordsAggregate(ColumnInfoRecordsAggregate other) { - other.records.stream().map(ColumnInfoRecord::copy).forEach(records::add); - } + public ColumnInfoRecordsAggregate(ColumnInfoRecordsAggregate other) { + other.records.stream().map(ColumnInfoRecord::copy).forEach(records::add); + } - public ColumnInfoRecordsAggregate(RecordStream rs) { - this(); + public ColumnInfoRecordsAggregate(RecordStream rs) { + this(); - boolean isInOrder = true; - ColumnInfoRecord cirPrev = null; - while (rs.peekNextClass() == ColumnInfoRecord.class) { - ColumnInfoRecord cir = (ColumnInfoRecord) rs.getNext(); - records.add(cir); - if (cirPrev != null && compareColInfos(cirPrev, cir) > 0) { - isInOrder = false; - } - cirPrev = cir; - } - if (records.size() < 1) { - throw new RuntimeException("No column info records found"); - } - if (!isInOrder) { - records.sort(ColumnInfoRecordsAggregate::compareColInfos); - } - } + boolean isInOrder = true; + ColumnInfoRecord cirPrev = null; + while (rs.peekNextClass() == ColumnInfoRecord.class) { + ColumnInfoRecord cir = (ColumnInfoRecord) rs.getNext(); + records.add(cir); + if (cirPrev != null && compareColInfos(cirPrev, cir) > 0) { + isInOrder = false; + } + cirPrev = cir; + } + if (records.size() < 1) { + throw new RuntimeException("No column info records found"); + } + if (!isInOrder) { + records.sort(ColumnInfoRecordsAggregate::compareColInfos); + } + } - @Override - public ColumnInfoRecordsAggregate copy() { - return new ColumnInfoRecordsAggregate(this); - } + @Override + public ColumnInfoRecordsAggregate copy() { + return new ColumnInfoRecordsAggregate(this); + } - /** - * Inserts a column into the aggregate (at the end of the list). - */ - public void insertColumn(ColumnInfoRecord col) { - records.add(col); - records.sort(ColumnInfoRecordsAggregate::compareColInfos); - } + /** + * Inserts a column into the aggregate (at the end of the list). + */ + public void insertColumn(ColumnInfoRecord col) { + records.add(col); + records.sort(ColumnInfoRecordsAggregate::compareColInfos); + } - /** - * Inserts a column into the aggregate (at the position specified by - * {@code idx}. - */ - private void insertColumn(int idx, ColumnInfoRecord col) { - records.add(idx, col); - } + /** + * Inserts a column into the aggregate (at the position specified by + * {@code idx}. + */ + private void insertColumn(int idx, ColumnInfoRecord col) { + records.add(idx, col); + } - /* package */ int getNumColumns() { - return records.size(); - } + /* package */ int getNumColumns() { + return records.size(); + } - @Override - public void visitContainedRecords(RecordVisitor rv) { - int nItems = records.size(); - if (nItems < 1) { - return; - } - ColumnInfoRecord cirPrev = null; - for (ColumnInfoRecord cir : records) { - rv.visitRecord(cir); - if (cirPrev != null && compareColInfos(cirPrev, cir) > 0) { - // Excel probably wouldn't mind, but there is much logic in this class - // that assumes the column info records are kept in order - throw new RuntimeException("Column info records are out of order"); - } - cirPrev = cir; - } - } + @Override + public void visitContainedRecords(RecordVisitor rv) { + int nItems = records.size(); + if (nItems < 1) { + return; + } + ColumnInfoRecord cirPrev = null; + for (ColumnInfoRecord cir : records) { + rv.visitRecord(cir); + if (cirPrev != null && compareColInfos(cirPrev, cir) > 0) { + // Excel probably wouldn't mind, but there is much logic in this class + // that assumes the column info records are kept in order + throw new RuntimeException("Column info records are out of order"); + } + cirPrev = cir; + } + } - private int findStartOfColumnOutlineGroup(int pIdx) { - // Find the start of the group. - ColumnInfoRecord columnInfo = records.get(pIdx); - int level = columnInfo.getOutlineLevel(); - int idx = pIdx; - while (idx != 0) { - ColumnInfoRecord prevColumnInfo = records.get(idx - 1); - if (!prevColumnInfo.isAdjacentBefore(columnInfo)) { - break; - } - if (prevColumnInfo.getOutlineLevel() < level) { - break; - } - idx--; - columnInfo = prevColumnInfo; - } + private int findStartOfColumnOutlineGroup(int pIdx) { + // Find the start of the group. + ColumnInfoRecord columnInfo = records.get(pIdx); + int level = columnInfo.getOutlineLevel(); + int idx = pIdx; + while (idx != 0) { + ColumnInfoRecord prevColumnInfo = records.get(idx - 1); + if (!prevColumnInfo.isAdjacentBefore(columnInfo)) { + break; + } + if (prevColumnInfo.getOutlineLevel() < level) { + break; + } + idx--; + columnInfo = prevColumnInfo; + } - return idx; - } + return idx; + } - private int findEndOfColumnOutlineGroup(int colInfoIndex) { - // Find the end of the group. - ColumnInfoRecord columnInfo = records.get(colInfoIndex); - int level = columnInfo.getOutlineLevel(); - int idx = colInfoIndex; - while (idx < records.size() - 1) { - ColumnInfoRecord nextColumnInfo = records.get(idx + 1); - if (!columnInfo.isAdjacentBefore(nextColumnInfo)) { - break; - } - if (nextColumnInfo.getOutlineLevel() < level) { - break; - } - idx++; - columnInfo = nextColumnInfo; - } - return idx; - } + private int findEndOfColumnOutlineGroup(int colInfoIndex) { + // Find the end of the group. + ColumnInfoRecord columnInfo = records.get(colInfoIndex); + int level = columnInfo.getOutlineLevel(); + int idx = colInfoIndex; + while (idx < records.size() - 1) { + ColumnInfoRecord nextColumnInfo = records.get(idx + 1); + if (!columnInfo.isAdjacentBefore(nextColumnInfo)) { + break; + } + if (nextColumnInfo.getOutlineLevel() < level) { + break; + } + idx++; + columnInfo = nextColumnInfo; + } + return idx; + } - private ColumnInfoRecord getColInfo(int idx) { - return records.get( idx ); - } + private ColumnInfoRecord getColInfo(int idx) { + return records.get( idx ); + } - /** - * 'Collapsed' state is stored in a single column col info record immediately after the outline group - * @return true, if the column is collapsed, false otherwise. - */ - private boolean isColumnGroupCollapsed(int idx) { - int endOfOutlineGroupIdx = findEndOfColumnOutlineGroup(idx); - int nextColInfoIx = endOfOutlineGroupIdx+1; - if (nextColInfoIx >= records.size()) { - return false; - } - ColumnInfoRecord nextColInfo = getColInfo(nextColInfoIx); - if (!getColInfo(endOfOutlineGroupIdx).isAdjacentBefore(nextColInfo)) { - return false; - } - return nextColInfo.getCollapsed(); - } + /** + * 'Collapsed' state is stored in a single column col info record immediately after the outline group + * @return true, if the column is collapsed, false otherwise. + */ + private boolean isColumnGroupCollapsed(int idx) { + int endOfOutlineGroupIdx = findEndOfColumnOutlineGroup(idx); + int nextColInfoIx = endOfOutlineGroupIdx+1; + if (nextColInfoIx >= records.size()) { + return false; + } + ColumnInfoRecord nextColInfo = getColInfo(nextColInfoIx); + if (!getColInfo(endOfOutlineGroupIdx).isAdjacentBefore(nextColInfo)) { + return false; + } + return nextColInfo.getCollapsed(); + } - private boolean isColumnGroupHiddenByParent(int idx) { - // Look out outline details of end - int endLevel = 0; - boolean endHidden = false; - int endOfOutlineGroupIdx = findEndOfColumnOutlineGroup( idx ); - if (endOfOutlineGroupIdx < records.size()) { - ColumnInfoRecord nextInfo = getColInfo(endOfOutlineGroupIdx + 1); - if (getColInfo(endOfOutlineGroupIdx).isAdjacentBefore(nextInfo)) { - endLevel = nextInfo.getOutlineLevel(); - endHidden = nextInfo.getHidden(); - } - } - // Look out outline details of start - int startLevel = 0; - boolean startHidden = false; - int startOfOutlineGroupIdx = findStartOfColumnOutlineGroup( idx ); - if (startOfOutlineGroupIdx > 0) { - ColumnInfoRecord prevInfo = getColInfo(startOfOutlineGroupIdx - 1); - if (prevInfo.isAdjacentBefore(getColInfo(startOfOutlineGroupIdx))) { - startLevel = prevInfo.getOutlineLevel(); - startHidden = prevInfo.getHidden(); - } - } - if (endLevel > startLevel) { - return endHidden; - } - return startHidden; - } + private boolean isColumnGroupHiddenByParent(int idx) { + // Look out outline details of end + int endLevel = 0; + boolean endHidden = false; + int endOfOutlineGroupIdx = findEndOfColumnOutlineGroup( idx ); + if (endOfOutlineGroupIdx < records.size()) { + ColumnInfoRecord nextInfo = getColInfo(endOfOutlineGroupIdx + 1); + if (getColInfo(endOfOutlineGroupIdx).isAdjacentBefore(nextInfo)) { + endLevel = nextInfo.getOutlineLevel(); + endHidden = nextInfo.getHidden(); + } + } + // Look out outline details of start + int startLevel = 0; + boolean startHidden = false; + int startOfOutlineGroupIdx = findStartOfColumnOutlineGroup( idx ); + if (startOfOutlineGroupIdx > 0) { + ColumnInfoRecord prevInfo = getColInfo(startOfOutlineGroupIdx - 1); + if (prevInfo.isAdjacentBefore(getColInfo(startOfOutlineGroupIdx))) { + startLevel = prevInfo.getOutlineLevel(); + startHidden = prevInfo.getHidden(); + } + } + if (endLevel > startLevel) { + return endHidden; + } + return startHidden; + } - public void collapseColumn(int columnIndex) { - int colInfoIx = findColInfoIdx(columnIndex, 0); - if (colInfoIx == -1) { - return; - } + public void collapseColumn(int columnIndex) { + int colInfoIx = findColInfoIdx(columnIndex, 0); + if (colInfoIx == -1) { + return; + } - // Find the start of the group. - int groupStartColInfoIx = findStartOfColumnOutlineGroup(colInfoIx); - ColumnInfoRecord columnInfo = getColInfo(groupStartColInfoIx); + // Find the start of the group. + int groupStartColInfoIx = findStartOfColumnOutlineGroup(colInfoIx); + ColumnInfoRecord columnInfo = getColInfo(groupStartColInfoIx); - // Hide all the columns until the end of the group - int lastColIx = setGroupHidden(groupStartColInfoIx, columnInfo.getOutlineLevel(), true); + // Hide all the columns until the end of the group + int lastColIx = setGroupHidden(groupStartColInfoIx, columnInfo.getOutlineLevel(), true); - // Write collapse field - setColumn(lastColIx + 1, null, null, null, null, Boolean.TRUE); - } - /** - * Sets all adjacent columns of the same outline level to the specified hidden status. - * @param pIdx the col info index of the start of the outline group - * @return the column index of the last column in the outline group - */ - private int setGroupHidden(int pIdx, int level, boolean hidden) { - int idx = pIdx; - ColumnInfoRecord columnInfo = getColInfo(idx); - while (idx < records.size()) { - columnInfo.setHidden(hidden); - if (idx + 1 < records.size()) { - ColumnInfoRecord nextColumnInfo = getColInfo(idx + 1); - if (!columnInfo.isAdjacentBefore(nextColumnInfo)) { - break; - } - if (nextColumnInfo.getOutlineLevel() < level) { - break; - } - columnInfo = nextColumnInfo; - } - idx++; - } - return columnInfo.getLastColumn(); - } + // Write collapse field + setColumn(lastColIx + 1, null, null, null, null, Boolean.TRUE); + } + /** + * Sets all adjacent columns of the same outline level to the specified hidden status. + * @param pIdx the col info index of the start of the outline group + * @return the column index of the last column in the outline group + */ + private int setGroupHidden(int pIdx, int level, boolean hidden) { + int idx = pIdx; + ColumnInfoRecord columnInfo = getColInfo(idx); + while (idx < records.size()) { + columnInfo.setHidden(hidden); + if (idx + 1 < records.size()) { + ColumnInfoRecord nextColumnInfo = getColInfo(idx + 1); + if (!columnInfo.isAdjacentBefore(nextColumnInfo)) { + break; + } + if (nextColumnInfo.getOutlineLevel() < level) { + break; + } + columnInfo = nextColumnInfo; + } + idx++; + } + return columnInfo.getLastColumn(); + } - public void expandColumn(int columnIndex) { - int idx = findColInfoIdx(columnIndex, 0); - if (idx == -1) { - return; - } + public void expandColumn(int columnIndex) { + int idx = findColInfoIdx(columnIndex, 0); + if (idx == -1) { + return; + } - // If it is already expanded do nothing. - if (!isColumnGroupCollapsed(idx)) { - return; - } + // If it is already expanded do nothing. + if (!isColumnGroupCollapsed(idx)) { + return; + } - // Find the start/end of the group. - int startIdx = findStartOfColumnOutlineGroup(idx); - int endIdx = findEndOfColumnOutlineGroup(idx); + // Find the start/end of the group. + int startIdx = findStartOfColumnOutlineGroup(idx); + int endIdx = findEndOfColumnOutlineGroup(idx); - // expand: - // colapsed bit must be unset - // hidden bit gets unset _if_ surrounding groups are expanded you can determine - // this by looking at the hidden bit of the enclosing group. You will have - // to look at the start and the end of the current group to determine which - // is the enclosing group - // hidden bit only is altered for this outline level. ie. don't uncollapse contained groups - ColumnInfoRecord columnInfo = getColInfo(endIdx); - if (!isColumnGroupHiddenByParent(idx)) { - int outlineLevel = columnInfo.getOutlineLevel(); - for (int i = startIdx; i <= endIdx; i++) { - ColumnInfoRecord ci = getColInfo(i); - if (outlineLevel == ci.getOutlineLevel()) - ci.setHidden(false); - } - } + // expand: + // colapsed bit must be unset + // hidden bit gets unset _if_ surrounding groups are expanded you can determine + // this by looking at the hidden bit of the enclosing group. You will have + // to look at the start and the end of the current group to determine which + // is the enclosing group + // hidden bit only is altered for this outline level. ie. don't uncollapse contained groups + ColumnInfoRecord columnInfo = getColInfo(endIdx); + if (!isColumnGroupHiddenByParent(idx)) { + int outlineLevel = columnInfo.getOutlineLevel(); + for (int i = startIdx; i <= endIdx; i++) { + ColumnInfoRecord ci = getColInfo(i); + if (outlineLevel == ci.getOutlineLevel()) + ci.setHidden(false); + } + } - // Write collapse flag (stored in a single col info record after this outline group) - setColumn(columnInfo.getLastColumn() + 1, null, null, null, null, Boolean.FALSE); - } + // Write collapse flag (stored in a single col info record after this outline group) + setColumn(columnInfo.getLastColumn() + 1, null, null, null, null, Boolean.FALSE); + } - private static ColumnInfoRecord copyColInfo(ColumnInfoRecord ci) { - return ci.copy(); - } + private static ColumnInfoRecord copyColInfo(ColumnInfoRecord ci) { + return ci.copy(); + } - public void setColumn(int targetColumnIx, Short xfIndex, Integer width, - Integer level, Boolean hidden, Boolean collapsed) { - ColumnInfoRecord ci = null; - int k; - for (k = 0; k < records.size(); k++) { - ColumnInfoRecord tci = records.get(k); - if (tci.containsColumn(targetColumnIx)) { - ci = tci; - break; - } - if (tci.getFirstColumn() > targetColumnIx) { - // call column infos after k are for later columns - break; // exit now so k will be the correct insert pos - } - } + public void setColumn(int targetColumnIx, Short xfIndex, Integer width, + Integer level, Boolean hidden, Boolean collapsed) { + ColumnInfoRecord ci = null; + int k; + for (k = 0; k < records.size(); k++) { + ColumnInfoRecord tci = records.get(k); + if (tci.containsColumn(targetColumnIx)) { + ci = tci; + break; + } + if (tci.getFirstColumn() > targetColumnIx) { + // call column infos after k are for later columns + break; // exit now so k will be the correct insert pos + } + } - if (ci == null) { - // okay so there ISN'T a column info record that covers this column so lets create one! - ColumnInfoRecord nci = new ColumnInfoRecord(); + if (ci == null) { + // okay so there ISN'T a column info record that covers this column so lets create one! + ColumnInfoRecord nci = new ColumnInfoRecord(); - nci.setFirstColumn(targetColumnIx); - nci.setLastColumn(targetColumnIx); - setColumnInfoFields( nci, xfIndex, width, level, hidden, collapsed ); - insertColumn(k, nci); - attemptMergeColInfoRecords(k); - return; - } + nci.setFirstColumn(targetColumnIx); + nci.setLastColumn(targetColumnIx); + setColumnInfoFields( nci, xfIndex, width, level, hidden, collapsed ); + insertColumn(k, nci); + attemptMergeColInfoRecords(k); + return; + } - boolean styleChanged = xfIndex != null && ci.getXFIndex() != xfIndex.shortValue(); - boolean widthChanged = width != null && ci.getColumnWidth() != width.shortValue(); - boolean levelChanged = level != null && ci.getOutlineLevel() != level.intValue(); - boolean hiddenChanged = hidden != null && ci.getHidden() != hidden.booleanValue(); - boolean collapsedChanged = collapsed != null && ci.getCollapsed() != collapsed.booleanValue(); + boolean styleChanged = xfIndex != null && ci.getXFIndex() != xfIndex.shortValue(); + boolean widthChanged = width != null && ci.getColumnWidth() != width.shortValue(); + boolean levelChanged = level != null && ci.getOutlineLevel() != level.intValue(); + boolean hiddenChanged = hidden != null && ci.getHidden() != hidden.booleanValue(); + boolean collapsedChanged = collapsed != null && ci.getCollapsed() != collapsed.booleanValue(); - boolean columnChanged = styleChanged || widthChanged || levelChanged || hiddenChanged || collapsedChanged; - if (!columnChanged) { - // do nothing...nothing changed. - return; - } + boolean columnChanged = styleChanged || widthChanged || levelChanged || hiddenChanged || collapsedChanged; + if (!columnChanged) { + // do nothing...nothing changed. + return; + } - if (ci.getFirstColumn() == targetColumnIx && ci.getLastColumn() == targetColumnIx) { - // ColumnInfo ci for a single column, the target column - setColumnInfoFields(ci, xfIndex, width, level, hidden, collapsed); - attemptMergeColInfoRecords(k); - return; - } + if (ci.getFirstColumn() == targetColumnIx && ci.getLastColumn() == targetColumnIx) { + // ColumnInfo ci for a single column, the target column + setColumnInfoFields(ci, xfIndex, width, level, hidden, collapsed); + attemptMergeColInfoRecords(k); + return; + } - if (ci.getFirstColumn() == targetColumnIx || ci.getLastColumn() == targetColumnIx) { - // The target column is at either end of the multi-column ColumnInfo ci - // we'll just divide the info and create a new one - if (ci.getFirstColumn() == targetColumnIx) { - ci.setFirstColumn(targetColumnIx + 1); - } else { - ci.setLastColumn(targetColumnIx - 1); - k++; // adjust insert pos to insert after - } - ColumnInfoRecord nci = copyColInfo(ci); + if (ci.getFirstColumn() == targetColumnIx || ci.getLastColumn() == targetColumnIx) { + // The target column is at either end of the multi-column ColumnInfo ci + // we'll just divide the info and create a new one + if (ci.getFirstColumn() == targetColumnIx) { + ci.setFirstColumn(targetColumnIx + 1); + } else { + ci.setLastColumn(targetColumnIx - 1); + k++; // adjust insert pos to insert after + } + ColumnInfoRecord nci = copyColInfo(ci); - nci.setFirstColumn(targetColumnIx); - nci.setLastColumn(targetColumnIx); - setColumnInfoFields( nci, xfIndex, width, level, hidden, collapsed ); + nci.setFirstColumn(targetColumnIx); + nci.setLastColumn(targetColumnIx); + setColumnInfoFields( nci, xfIndex, width, level, hidden, collapsed ); - insertColumn(k, nci); - attemptMergeColInfoRecords(k); - } else { - //split to 3 records + insertColumn(k, nci); + attemptMergeColInfoRecords(k); + } else { + //split to 3 records ColumnInfoRecord ciMid = copyColInfo(ci); - ColumnInfoRecord ciEnd = copyColInfo(ci); - int lastcolumn = ci.getLastColumn(); + ColumnInfoRecord ciEnd = copyColInfo(ci); + int lastcolumn = ci.getLastColumn(); - ci.setLastColumn(targetColumnIx - 1); + ci.setLastColumn(targetColumnIx - 1); - ciMid.setFirstColumn(targetColumnIx); - ciMid.setLastColumn(targetColumnIx); - setColumnInfoFields(ciMid, xfIndex, width, level, hidden, collapsed); - insertColumn(++k, ciMid); + ciMid.setFirstColumn(targetColumnIx); + ciMid.setLastColumn(targetColumnIx); + setColumnInfoFields(ciMid, xfIndex, width, level, hidden, collapsed); + insertColumn(++k, ciMid); - ciEnd.setFirstColumn(targetColumnIx+1); - ciEnd.setLastColumn(lastcolumn); - insertColumn(++k, ciEnd); - // no need to attemptMergeColInfoRecords because we - // know both on each side are different - } - } + ciEnd.setFirstColumn(targetColumnIx+1); + ciEnd.setLastColumn(lastcolumn); + insertColumn(++k, ciEnd); + // no need to attemptMergeColInfoRecords because we + // know both on each side are different + } + } - /** - * Sets all non null fields into the {@code ci} parameter. - */ - private static void setColumnInfoFields(ColumnInfoRecord ci, Short xfStyle, Integer width, - Integer level, Boolean hidden, Boolean collapsed) { - if (xfStyle != null) { - ci.setXFIndex(xfStyle.shortValue()); - } - if (width != null) { - ci.setColumnWidth(width.intValue()); - } - if (level != null) { - ci.setOutlineLevel( level.shortValue() ); - } - if (hidden != null) { - ci.setHidden( hidden.booleanValue() ); - } - if (collapsed != null) { - ci.setCollapsed( collapsed.booleanValue() ); - } - } + /** + * Sets all non null fields into the {@code ci} parameter. + */ + private static void setColumnInfoFields(ColumnInfoRecord ci, Short xfStyle, Integer width, + Integer level, Boolean hidden, Boolean collapsed) { + if (xfStyle != null) { + ci.setXFIndex(xfStyle.shortValue()); + } + if (width != null) { + ci.setColumnWidth(width.intValue()); + } + if (level != null) { + ci.setOutlineLevel( level.shortValue() ); + } + if (hidden != null) { + ci.setHidden( hidden.booleanValue() ); + } + if (collapsed != null) { + ci.setCollapsed( collapsed.booleanValue() ); + } + } - private int findColInfoIdx(int columnIx, int fromColInfoIdx) { - if (columnIx < 0) { - throw new IllegalArgumentException( "column parameter out of range: " + columnIx ); - } - if (fromColInfoIdx < 0) { - throw new IllegalArgumentException( "fromIdx parameter out of range: " + fromColInfoIdx ); - } + private int findColInfoIdx(int columnIx, int fromColInfoIdx) { + if (columnIx < 0) { + throw new IllegalArgumentException( "column parameter out of range: " + columnIx ); + } + if (fromColInfoIdx < 0) { + throw new IllegalArgumentException( "fromIdx parameter out of range: " + fromColInfoIdx ); + } - for (int k = fromColInfoIdx; k < records.size(); k++) { - ColumnInfoRecord ci = getColInfo(k); - if (ci.containsColumn(columnIx)) { - return k; - } - if (ci.getFirstColumn() > columnIx) { - break; - } - } - return -1; - } + for (int k = fromColInfoIdx; k < records.size(); k++) { + ColumnInfoRecord ci = getColInfo(k); + if (ci.containsColumn(columnIx)) { + return k; + } + if (ci.getFirstColumn() > columnIx) { + break; + } + } + return -1; + } - /** - * Attempts to merge the col info record at the specified index - * with either or both of its neighbours - */ - private void attemptMergeColInfoRecords(int colInfoIx) { - int nRecords = records.size(); - if (colInfoIx < 0 || colInfoIx >= nRecords) { - throw new IllegalArgumentException("colInfoIx " + colInfoIx - + " is out of range (0.." + (nRecords-1) + ")"); - } - ColumnInfoRecord currentCol = getColInfo(colInfoIx); - int nextIx = colInfoIx+1; - if (nextIx < nRecords) { - if (mergeColInfoRecords(currentCol, getColInfo(nextIx))) { - records.remove(nextIx); - } - } - if (colInfoIx > 0) { - if (mergeColInfoRecords(getColInfo(colInfoIx - 1), currentCol)) { - records.remove(colInfoIx); - } - } - } - /** - * merges two column info records (if they are adjacent and have the same formatting, etc) - * @return {@code false} if the two column records could not be merged - */ - private static boolean mergeColInfoRecords(ColumnInfoRecord ciA, ColumnInfoRecord ciB) { - if (ciA.isAdjacentBefore(ciB) && ciA.formatMatches(ciB)) { - ciA.setLastColumn(ciB.getLastColumn()); - return true; - } - return false; - } - /** - * Creates an outline group for the specified columns, by setting the level - * field for each col info record in the range. {@link ColumnInfoRecord}s - * may be created, split or merged as a result of this operation. - * - * @param fromColumnIx - * group from this column (inclusive) - * @param toColumnIx - * group to this column (inclusive) - * @param indent - * if {@code true} the group will be indented by one - * level, if {@code false} indenting will be decreased by - * one level. - */ - public void groupColumnRange(int fromColumnIx, int toColumnIx, boolean indent) { + /** + * Attempts to merge the col info record at the specified index + * with either or both of its neighbours + */ + private void attemptMergeColInfoRecords(int colInfoIx) { + int nRecords = records.size(); + if (colInfoIx < 0 || colInfoIx >= nRecords) { + throw new IllegalArgumentException("colInfoIx " + colInfoIx + + " is out of range (0.." + (nRecords-1) + ")"); + } + ColumnInfoRecord currentCol = getColInfo(colInfoIx); + int nextIx = colInfoIx+1; + if (nextIx < nRecords) { + if (mergeColInfoRecords(currentCol, getColInfo(nextIx))) { + records.remove(nextIx); + } + } + if (colInfoIx > 0) { + if (mergeColInfoRecords(getColInfo(colInfoIx - 1), currentCol)) { + records.remove(colInfoIx); + } + } + } + /** + * merges two column info records (if they are adjacent and have the same formatting, etc) + * @return {@code false} if the two column records could not be merged + */ + private static boolean mergeColInfoRecords(ColumnInfoRecord ciA, ColumnInfoRecord ciB) { + if (ciA.isAdjacentBefore(ciB) && ciA.formatMatches(ciB)) { + ciA.setLastColumn(ciB.getLastColumn()); + return true; + } + return false; + } + /** + * Creates an outline group for the specified columns, by setting the level + * field for each col info record in the range. {@link ColumnInfoRecord}s + * may be created, split or merged as a result of this operation. + * + * @param fromColumnIx + * group from this column (inclusive) + * @param toColumnIx + * group to this column (inclusive) + * @param indent + * if {@code true} the group will be indented by one + * level, if {@code false} indenting will be decreased by + * one level. + */ + public void groupColumnRange(int fromColumnIx, int toColumnIx, boolean indent) { - int colInfoSearchStartIdx = 0; // optimization to speed up the search for col infos - for (int i = fromColumnIx; i <= toColumnIx; i++) { - int level = 1; - int colInfoIdx = findColInfoIdx(i, colInfoSearchStartIdx); - if (colInfoIdx != -1) { - level = getColInfo(colInfoIdx).getOutlineLevel(); - if (indent) { - level++; - } else { - level--; - } - level = Math.max(0, level); - level = Math.min(7, level); - colInfoSearchStartIdx = Math.max(0, colInfoIdx - 1); // -1 just in case this column is collapsed later. - } - setColumn(i, null, null, Integer.valueOf(level), null, null); - } - } + int colInfoSearchStartIdx = 0; // optimization to speed up the search for col infos + for (int i = fromColumnIx; i <= toColumnIx; i++) { + int level = 1; + int colInfoIdx = findColInfoIdx(i, colInfoSearchStartIdx); + if (colInfoIdx != -1) { + level = getColInfo(colInfoIdx).getOutlineLevel(); + if (indent) { + level++; + } else { + level--; + } + level = Math.max(0, level); + level = Math.min(7, level); + colInfoSearchStartIdx = Math.max(0, colInfoIdx - 1); // -1 just in case this column is collapsed later. + } + setColumn(i, null, null, Integer.valueOf(level), null, null); + } + } - /** - * Finds the {@code ColumnInfoRecord} which contains the specified columnIndex - * @param columnIndex index of the column (not the index of the ColumnInfoRecord) - * @return {@code null} if no column info found for the specified column - */ - public ColumnInfoRecord findColumnInfo(int columnIndex) { - int nInfos = records.size(); - for(int i=0; i< nInfos; i++) { - ColumnInfoRecord ci = getColInfo(i); - if (ci.containsColumn(columnIndex)) { - return ci; - } - } - return null; - } + /** + * Finds the {@code ColumnInfoRecord} which contains the specified columnIndex + * @param columnIndex index of the column (not the index of the ColumnInfoRecord) + * @return {@code null} if no column info found for the specified column + */ + public ColumnInfoRecord findColumnInfo(int columnIndex) { + int nInfos = records.size(); + for(int i=0; i< nInfos; i++) { + ColumnInfoRecord ci = getColInfo(i); + if (ci.containsColumn(columnIndex)) { + return ci; + } + } + return null; + } - public int getMaxOutlineLevel() { - int result = 0; - int count=records.size(); - for (int i=0; i _cfHeaders = new ArrayList<>(); + private final List _cfHeaders = new ArrayList<>(); - /** - * Creates an empty ConditionalFormattingTable - */ - public ConditionalFormattingTable() {} + /** + * Creates an empty ConditionalFormattingTable + */ + public ConditionalFormattingTable() {} - public ConditionalFormattingTable(RecordStream rs) { - while (rs.peekNextRecord() instanceof CFHeaderBase) { - _cfHeaders.add(CFRecordsAggregate.createCFAggregate(rs)); - } - } + public ConditionalFormattingTable(RecordStream rs) { + while (rs.peekNextRecord() instanceof CFHeaderBase) { + _cfHeaders.add(CFRecordsAggregate.createCFAggregate(rs)); + } + } - @Override + @Override public void visitContainedRecords(RecordVisitor rv) { - for (CFRecordsAggregate subAgg : _cfHeaders) { - subAgg.visitContainedRecords(rv); - } - } + for (CFRecordsAggregate subAgg : _cfHeaders) { + subAgg.visitContainedRecords(rv); + } + } - /** - * @return index of the newly added CF header aggregate - */ - public int add(CFRecordsAggregate cfAggregate) { - cfAggregate.getHeader().setID(_cfHeaders.size()); - _cfHeaders.add(cfAggregate); - return _cfHeaders.size() - 1; - } + /** + * @return index of the newly added CF header aggregate + */ + public int add(CFRecordsAggregate cfAggregate) { + cfAggregate.getHeader().setID(_cfHeaders.size()); + _cfHeaders.add(cfAggregate); + return _cfHeaders.size() - 1; + } - public int size() { - return _cfHeaders.size(); - } + public int size() { + return _cfHeaders.size(); + } - public CFRecordsAggregate get(int index) { - checkIndex(index); - return _cfHeaders.get(index); - } + public CFRecordsAggregate get(int index) { + checkIndex(index); + return _cfHeaders.get(index); + } - public void remove(int index) { - checkIndex(index); - _cfHeaders.remove(index); - } + public void remove(int index) { + checkIndex(index); + _cfHeaders.remove(index); + } - private void checkIndex(int index) { - if (index < 0 || index >= _cfHeaders.size()) { - throw new IllegalArgumentException("Specified CF index " + index - + " is outside the allowable range (0.." + (_cfHeaders.size() - 1) + ")"); - } - } + private void checkIndex(int index) { + if (index < 0 || index >= _cfHeaders.size()) { + throw new IllegalArgumentException("Specified CF index " + index + + " is outside the allowable range (0.." + (_cfHeaders.size() - 1) + ")"); + } + } - public void updateFormulasAfterCellShift(FormulaShifter shifter, int externSheetIndex) { - for (int i = 0; i < _cfHeaders.size(); i++) { - CFRecordsAggregate subAgg = _cfHeaders.get(i); - boolean shouldKeep = subAgg.updateFormulasAfterCellShift(shifter, externSheetIndex); - if (!shouldKeep) { - _cfHeaders.remove(i); - i--; - } - } - } + public void updateFormulasAfterCellShift(FormulaShifter shifter, int externSheetIndex) { + for (int i = 0; i < _cfHeaders.size(); i++) { + CFRecordsAggregate subAgg = _cfHeaders.get(i); + boolean shouldKeep = subAgg.updateFormulasAfterCellShift(shifter, externSheetIndex); + if (!shouldKeep) { + _cfHeaders.remove(i); + i--; + } + } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/CustomViewSettingsRecordAggregate.java b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/CustomViewSettingsRecordAggregate.java index 7aa5bd8e25..75ea21f79a 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/CustomViewSettingsRecordAggregate.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/CustomViewSettingsRecordAggregate.java @@ -29,22 +29,22 @@ import org.apache.poi.hssf.record.*; */ public final class CustomViewSettingsRecordAggregate extends RecordAggregate { - private final org.apache.poi.hssf.record.Record _begin; - private final org.apache.poi.hssf.record.Record _end; - /** - * All the records between BOF and EOF - */ - private final List _recs; - private PageSettingsBlock _psBlock; + private final org.apache.poi.hssf.record.Record _begin; + private final org.apache.poi.hssf.record.Record _end; + /** + * All the records between BOF and EOF + */ + private final List _recs; + private PageSettingsBlock _psBlock; - public CustomViewSettingsRecordAggregate(RecordStream rs) { - _begin = rs.getNext(); - if (_begin.getSid() != UserSViewBegin.sid) { - throw new IllegalStateException("Bad begin record"); - } - List temp = new ArrayList<>(); - while (rs.peekNextSid() != UserSViewEnd.sid) { - if (PageSettingsBlock.isComponentRecord(rs.peekNextSid())) { + public CustomViewSettingsRecordAggregate(RecordStream rs) { + _begin = rs.getNext(); + if (_begin.getSid() != UserSViewBegin.sid) { + throw new IllegalStateException("Bad begin record"); + } + List temp = new ArrayList<>(); + while (rs.peekNextSid() != UserSViewEnd.sid) { + if (PageSettingsBlock.isComponentRecord(rs.peekNextSid())) { if (_psBlock != null) { if (rs.peekNextSid() == HeaderFooterRecord.sid) { // test samples: 45538_classic_Footer.xls, 45538_classic_Header.xls @@ -54,39 +54,39 @@ public final class CustomViewSettingsRecordAggregate extends RecordAggregate { throw new IllegalStateException( "Found more than one PageSettingsBlock in chart sub-stream, had sid: " + rs.peekNextSid()); } - _psBlock = new PageSettingsBlock(rs); - temp.add(_psBlock); - continue; - } - temp.add(rs.getNext()); - } - _recs = temp; - _end = rs.getNext(); // no need to save EOF in field - if (_end.getSid() != UserSViewEnd.sid) { - throw new IllegalStateException("Bad custom view settings end record"); - } - } + _psBlock = new PageSettingsBlock(rs); + temp.add(_psBlock); + continue; + } + temp.add(rs.getNext()); + } + _recs = temp; + _end = rs.getNext(); // no need to save EOF in field + if (_end.getSid() != UserSViewEnd.sid) { + throw new IllegalStateException("Bad custom view settings end record"); + } + } - @Override + @Override public void visitContainedRecords(RecordVisitor rv) { - if (_recs.isEmpty()) { - return; - } - rv.visitRecord(_begin); - for (int i = 0; i < _recs.size(); i++) { - RecordBase rb = _recs.get(i); - if (rb instanceof RecordAggregate) { - ((RecordAggregate) rb).visitContainedRecords(rv); - } else { - rv.visitRecord((org.apache.poi.hssf.record.Record) rb); - } - } - rv.visitRecord(_end); - } + if (_recs.isEmpty()) { + return; + } + rv.visitRecord(_begin); + for (int i = 0; i < _recs.size(); i++) { + RecordBase rb = _recs.get(i); + if (rb instanceof RecordAggregate) { + ((RecordAggregate) rb).visitContainedRecords(rv); + } else { + rv.visitRecord((org.apache.poi.hssf.record.Record) rb); + } + } + rv.visitRecord(_end); + } - public static boolean isBeginRecord(int sid) { - return sid == UserSViewBegin.sid; - } + public static boolean isBeginRecord(int sid) { + return sid == UserSViewBegin.sid; + } public void append(RecordBase r){ _recs.add(r); diff --git a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/DataValidityTable.java b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/DataValidityTable.java index d533a7bc91..ff29fa12e7 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/DataValidityTable.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/DataValidityTable.java @@ -30,38 +30,38 @@ import org.apache.poi.hssf.record.DVRecord; */ public final class DataValidityTable extends RecordAggregate { - private final DVALRecord _headerRec; - /** - * The list of data validations for the current sheet. - * Note - this may be empty (contrary to OOO documentation) - */ - private final List _validationList; + private final DVALRecord _headerRec; + /** + * The list of data validations for the current sheet. + * Note - this may be empty (contrary to OOO documentation) + */ + private final List _validationList; - public DataValidityTable(RecordStream rs) { - _headerRec = (DVALRecord) rs.getNext(); - List temp = new ArrayList<>(); - while (rs.peekNextClass() == DVRecord.class) { - temp.add((DVRecord) rs.getNext()); - } - _validationList = temp; - } + public DataValidityTable(RecordStream rs) { + _headerRec = (DVALRecord) rs.getNext(); + List temp = new ArrayList<>(); + while (rs.peekNextClass() == DVRecord.class) { + temp.add((DVRecord) rs.getNext()); + } + _validationList = temp; + } - public DataValidityTable() { - _headerRec = new DVALRecord(); - _validationList = new ArrayList<>(); - } + public DataValidityTable() { + _headerRec = new DVALRecord(); + _validationList = new ArrayList<>(); + } - @Override + @Override public void visitContainedRecords(RecordVisitor rv) { - if (_validationList.isEmpty()) { - return; - } - rv.visitRecord(_headerRec); - _validationList.forEach(rv::visitRecord); - } + if (_validationList.isEmpty()) { + return; + } + rv.visitRecord(_headerRec); + _validationList.forEach(rv::visitRecord); + } - public void addDataValidation(DVRecord dvRecord) { - _validationList.add(dvRecord); - _headerRec.setDVRecNo(_validationList.size()); - } + public void addDataValidation(DVRecord dvRecord) { + _validationList.add(dvRecord); + _headerRec.setDVRecNo(_validationList.size()); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/FormulaRecordAggregate.java b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/FormulaRecordAggregate.java index 200365ee43..76d88a28d2 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/FormulaRecordAggregate.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/FormulaRecordAggregate.java @@ -38,235 +38,235 @@ import org.apache.poi.util.RecordFormatException; */ public final class FormulaRecordAggregate extends RecordAggregate implements CellValueRecordInterface { - private final FormulaRecord _formulaRecord; - private SharedValueManager _sharedValueManager; - /** caches the calculated result of the formula */ - private StringRecord _stringRecord; - private SharedFormulaRecord _sharedFormulaRecord; + private final FormulaRecord _formulaRecord; + private SharedValueManager _sharedValueManager; + /** caches the calculated result of the formula */ + private StringRecord _stringRecord; + private SharedFormulaRecord _sharedFormulaRecord; - /** - * @param stringRec may be null if this formula does not have a cached text - * value. - * @param svm the {@link SharedValueManager} for the current sheet - */ - public FormulaRecordAggregate(FormulaRecord formulaRec, StringRecord stringRec, SharedValueManager svm) { - if (svm == null) { - throw new IllegalArgumentException("sfm must not be null"); - } - if (formulaRec.hasCachedResultString()) { - if (stringRec == null) { - throw new RecordFormatException("Formula record flag is set but String record was not found"); - } - _stringRecord = stringRec; - } else { - // Usually stringRec is null here (in agreement with what the formula rec says). - // In the case where an extra StringRecord is erroneously present, Excel (2007) - // ignores it (see bug 46213). - _stringRecord = null; - } + /** + * @param stringRec may be null if this formula does not have a cached text + * value. + * @param svm the {@link SharedValueManager} for the current sheet + */ + public FormulaRecordAggregate(FormulaRecord formulaRec, StringRecord stringRec, SharedValueManager svm) { + if (svm == null) { + throw new IllegalArgumentException("sfm must not be null"); + } + if (formulaRec.hasCachedResultString()) { + if (stringRec == null) { + throw new RecordFormatException("Formula record flag is set but String record was not found"); + } + _stringRecord = stringRec; + } else { + // Usually stringRec is null here (in agreement with what the formula rec says). + // In the case where an extra StringRecord is erroneously present, Excel (2007) + // ignores it (see bug 46213). + _stringRecord = null; + } - _formulaRecord = formulaRec; - _sharedValueManager = svm; - if (formulaRec.isSharedFormula()) { - CellReference firstCell = formulaRec.getFormula().getExpReference(); - if (firstCell == null) { - handleMissingSharedFormulaRecord(formulaRec); - } else { - _sharedFormulaRecord = svm.linkSharedFormulaRecord(firstCell, this); - } - } - } + _formulaRecord = formulaRec; + _sharedValueManager = svm; + if (formulaRec.isSharedFormula()) { + CellReference firstCell = formulaRec.getFormula().getExpReference(); + if (firstCell == null) { + handleMissingSharedFormulaRecord(formulaRec); + } else { + _sharedFormulaRecord = svm.linkSharedFormulaRecord(firstCell, this); + } + } + } - /** - * Sometimes the shared formula flag "seems" to be erroneously set (because the corresponding - * {@link SharedFormulaRecord} does not exist). Normally this would leave no way of determining - * the {@link Ptg} tokens for the formula. However as it turns out in these - * cases, Excel encodes the unshared {@link Ptg} tokens in the right place (inside the {@link - * FormulaRecord}). So the the only thing that needs to be done is to ignore the erroneous - * shared formula flag.
- * - * This method may also be used for setting breakpoints to help diagnose issues regarding the - * abnormally-set 'shared formula' flags. - * (see TestValueRecordsAggregate.testSpuriousSharedFormulaFlag()).

- */ - private static void handleMissingSharedFormulaRecord(FormulaRecord formula) { - // make sure 'unshared' formula is actually available - Ptg firstToken = formula.getParsedExpression()[0]; - if (firstToken instanceof ExpPtg) { - throw new RecordFormatException( - "SharedFormulaRecord not found for FormulaRecord with (isSharedFormula=true)"); - } - // could log an info message here since this is a fairly unusual occurrence. - formula.setSharedFormula(false); // no point leaving the flag erroneously set - } + /** + * Sometimes the shared formula flag "seems" to be erroneously set (because the corresponding + * {@link SharedFormulaRecord} does not exist). Normally this would leave no way of determining + * the {@link Ptg} tokens for the formula. However as it turns out in these + * cases, Excel encodes the unshared {@link Ptg} tokens in the right place (inside the {@link + * FormulaRecord}). So the the only thing that needs to be done is to ignore the erroneous + * shared formula flag.
+ * + * This method may also be used for setting breakpoints to help diagnose issues regarding the + * abnormally-set 'shared formula' flags. + * (see TestValueRecordsAggregate.testSpuriousSharedFormulaFlag()).

+ */ + private static void handleMissingSharedFormulaRecord(FormulaRecord formula) { + // make sure 'unshared' formula is actually available + Ptg firstToken = formula.getParsedExpression()[0]; + if (firstToken instanceof ExpPtg) { + throw new RecordFormatException( + "SharedFormulaRecord not found for FormulaRecord with (isSharedFormula=true)"); + } + // could log an info message here since this is a fairly unusual occurrence. + formula.setSharedFormula(false); // no point leaving the flag erroneously set + } - public FormulaRecord getFormulaRecord() { - return _formulaRecord; - } + public FormulaRecord getFormulaRecord() { + return _formulaRecord; + } - /** - * debug only - * TODO - encapsulate - */ - public StringRecord getStringRecord() { - return _stringRecord; - } + /** + * debug only + * TODO - encapsulate + */ + public StringRecord getStringRecord() { + return _stringRecord; + } - public short getXFIndex() { - return _formulaRecord.getXFIndex(); - } + public short getXFIndex() { + return _formulaRecord.getXFIndex(); + } - public void setXFIndex(short xf) { - _formulaRecord.setXFIndex(xf); - } + public void setXFIndex(short xf) { + _formulaRecord.setXFIndex(xf); + } - public void setColumn(short col) { - _formulaRecord.setColumn(col); - } + public void setColumn(short col) { + _formulaRecord.setColumn(col); + } - public void setRow(int row) { - _formulaRecord.setRow(row); - } + public void setRow(int row) { + _formulaRecord.setRow(row); + } - public short getColumn() { - return _formulaRecord.getColumn(); - } + public short getColumn() { + return _formulaRecord.getColumn(); + } - public int getRow() { - return _formulaRecord.getRow(); - } + public int getRow() { + return _formulaRecord.getRow(); + } - public String toString() { - return _formulaRecord.toString(); - } + public String toString() { + return _formulaRecord.toString(); + } - @Override + @Override public void visitContainedRecords(RecordVisitor rv) { - rv.visitRecord(_formulaRecord); - Record sharedFormulaRecord = _sharedValueManager.getRecordForFirstCell(this); - if (sharedFormulaRecord != null) { - rv.visitRecord(sharedFormulaRecord); - } - if (_formulaRecord.hasCachedResultString() && _stringRecord != null) { - rv.visitRecord(_stringRecord); - } - } + rv.visitRecord(_formulaRecord); + Record sharedFormulaRecord = _sharedValueManager.getRecordForFirstCell(this); + if (sharedFormulaRecord != null) { + rv.visitRecord(sharedFormulaRecord); + } + if (_formulaRecord.hasCachedResultString() && _stringRecord != null) { + rv.visitRecord(_stringRecord); + } + } - public String getStringValue() { - if(_stringRecord==null) { - return null; - } - return _stringRecord.getString(); - } + public String getStringValue() { + if(_stringRecord==null) { + return null; + } + return _stringRecord.getString(); + } - public void setCachedStringResult(String value) { + public void setCachedStringResult(String value) { - // Save the string into a String Record, creating one if required - if(_stringRecord == null) { - _stringRecord = new StringRecord(); - } - _stringRecord.setString(value); - if (value.length() < 1) { - _formulaRecord.setCachedResultTypeEmptyString(); - } else { - _formulaRecord.setCachedResultTypeString(); - } - } - public void setCachedBooleanResult(boolean value) { - _stringRecord = null; - _formulaRecord.setCachedResultBoolean(value); - } - public void setCachedErrorResult(int errorCode) { - _stringRecord = null; - _formulaRecord.setCachedResultErrorCode(errorCode); - } - public void setCachedErrorResult(FormulaError error) { - setCachedErrorResult(error.getCode()); - } - public void setCachedDoubleResult(double value) { - _stringRecord = null; - _formulaRecord.setValue(value); - } + // Save the string into a String Record, creating one if required + if(_stringRecord == null) { + _stringRecord = new StringRecord(); + } + _stringRecord.setString(value); + if (value.length() < 1) { + _formulaRecord.setCachedResultTypeEmptyString(); + } else { + _formulaRecord.setCachedResultTypeString(); + } + } + public void setCachedBooleanResult(boolean value) { + _stringRecord = null; + _formulaRecord.setCachedResultBoolean(value); + } + public void setCachedErrorResult(int errorCode) { + _stringRecord = null; + _formulaRecord.setCachedResultErrorCode(errorCode); + } + public void setCachedErrorResult(FormulaError error) { + setCachedErrorResult(error.getCode()); + } + public void setCachedDoubleResult(double value) { + _stringRecord = null; + _formulaRecord.setValue(value); + } - public Ptg[] getFormulaTokens() { - if (_sharedFormulaRecord != null) { - return _sharedFormulaRecord.getFormulaTokens(_formulaRecord); - } - CellReference expRef = _formulaRecord.getFormula().getExpReference(); - if (expRef != null) { - ArrayRecord arec = _sharedValueManager.getArrayRecord(expRef.getRow(), expRef.getCol()); - return arec.getFormulaTokens(); - } - return _formulaRecord.getParsedExpression(); - } + public Ptg[] getFormulaTokens() { + if (_sharedFormulaRecord != null) { + return _sharedFormulaRecord.getFormulaTokens(_formulaRecord); + } + CellReference expRef = _formulaRecord.getFormula().getExpReference(); + if (expRef != null) { + ArrayRecord arec = _sharedValueManager.getArrayRecord(expRef.getRow(), expRef.getCol()); + return arec.getFormulaTokens(); + } + return _formulaRecord.getParsedExpression(); + } - /** - * Also checks for a related shared formula and unlinks it if found - */ - public void setParsedExpression(Ptg[] ptgs) { - notifyFormulaChanging(); - _formulaRecord.setParsedExpression(ptgs); - } + /** + * Also checks for a related shared formula and unlinks it if found + */ + public void setParsedExpression(Ptg[] ptgs) { + notifyFormulaChanging(); + _formulaRecord.setParsedExpression(ptgs); + } - public void unlinkSharedFormula() { - SharedFormulaRecord sfr = _sharedFormulaRecord; - if (sfr == null) { - throw new IllegalStateException("Formula not linked to shared formula"); - } - Ptg[] ptgs = sfr.getFormulaTokens(_formulaRecord); - _formulaRecord.setParsedExpression(ptgs); - //Now its not shared! - _formulaRecord.setSharedFormula(false); - _sharedFormulaRecord = null; - } - /** - * Should be called by any code which is either deleting this formula cell, or changing - * its type. This method gives the aggregate a chance to unlink any shared formula - * that may be involved with this cell formula. - */ - public void notifyFormulaChanging() { - if (_sharedFormulaRecord != null) { - _sharedValueManager.unlink(_sharedFormulaRecord); - } - } - public boolean isPartOfArrayFormula() { - if (_sharedFormulaRecord != null) { - return false; - } + public void unlinkSharedFormula() { + SharedFormulaRecord sfr = _sharedFormulaRecord; + if (sfr == null) { + throw new IllegalStateException("Formula not linked to shared formula"); + } + Ptg[] ptgs = sfr.getFormulaTokens(_formulaRecord); + _formulaRecord.setParsedExpression(ptgs); + //Now its not shared! + _formulaRecord.setSharedFormula(false); + _sharedFormulaRecord = null; + } + /** + * Should be called by any code which is either deleting this formula cell, or changing + * its type. This method gives the aggregate a chance to unlink any shared formula + * that may be involved with this cell formula. + */ + public void notifyFormulaChanging() { + if (_sharedFormulaRecord != null) { + _sharedValueManager.unlink(_sharedFormulaRecord); + } + } + public boolean isPartOfArrayFormula() { + if (_sharedFormulaRecord != null) { + return false; + } CellReference expRef = _formulaRecord.getFormula().getExpReference(); ArrayRecord arec = expRef == null ? null : _sharedValueManager.getArrayRecord(expRef.getRow(), expRef.getCol()); - return arec != null; - } + return arec != null; + } - public CellRangeAddress getArrayFormulaRange() { - if (_sharedFormulaRecord != null) { - throw new IllegalStateException("not an array formula cell."); - } - CellReference expRef = _formulaRecord.getFormula().getExpReference(); - if (expRef == null) { - throw new IllegalStateException("not an array formula cell."); - } - ArrayRecord arec = _sharedValueManager.getArrayRecord(expRef.getRow(), expRef.getCol()); - if (arec == null) { - throw new IllegalStateException("ArrayRecord was not found for the locator " + expRef.formatAsString()); - } - CellRangeAddress8Bit a = arec.getRange(); - return new CellRangeAddress(a.getFirstRow(), a.getLastRow(), a.getFirstColumn(),a.getLastColumn()); - } + public CellRangeAddress getArrayFormulaRange() { + if (_sharedFormulaRecord != null) { + throw new IllegalStateException("not an array formula cell."); + } + CellReference expRef = _formulaRecord.getFormula().getExpReference(); + if (expRef == null) { + throw new IllegalStateException("not an array formula cell."); + } + ArrayRecord arec = _sharedValueManager.getArrayRecord(expRef.getRow(), expRef.getCol()); + if (arec == null) { + throw new IllegalStateException("ArrayRecord was not found for the locator " + expRef.formatAsString()); + } + CellRangeAddress8Bit a = arec.getRange(); + return new CellRangeAddress(a.getFirstRow(), a.getLastRow(), a.getFirstColumn(),a.getLastColumn()); + } - public void setArrayFormula(CellRangeAddress r, Ptg[] ptgs) { + public void setArrayFormula(CellRangeAddress r, Ptg[] ptgs) { - ArrayRecord arr = new ArrayRecord(Formula.create(ptgs), new CellRangeAddress8Bit(r.getFirstRow(), r.getLastRow(), r.getFirstColumn(), r.getLastColumn())); - _sharedValueManager.addArrayRecord(arr); - } - /** - * Removes an array formula - * @return the range of the array formula containing the specified cell. Never null - */ - public CellRangeAddress removeArrayFormula(int rowIndex, int columnIndex) { - CellRangeAddress8Bit a = _sharedValueManager.removeArrayFormula(rowIndex, columnIndex); + ArrayRecord arr = new ArrayRecord(Formula.create(ptgs), new CellRangeAddress8Bit(r.getFirstRow(), r.getLastRow(), r.getFirstColumn(), r.getLastColumn())); + _sharedValueManager.addArrayRecord(arr); + } + /** + * Removes an array formula + * @return the range of the array formula containing the specified cell. Never null + */ + public CellRangeAddress removeArrayFormula(int rowIndex, int columnIndex) { + CellRangeAddress8Bit a = _sharedValueManager.removeArrayFormula(rowIndex, columnIndex); // at this point FormulaRecordAggregate#isPartOfArrayFormula() should return false _formulaRecord.setParsedExpression(null); return new CellRangeAddress(a.getFirstRow(), a.getLastRow(), a.getFirstColumn(), a.getLastColumn()); - } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/MergedCellsTable.java b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/MergedCellsTable.java index a3550106e8..446f469ca2 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/MergedCellsTable.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/MergedCellsTable.java @@ -26,106 +26,106 @@ import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddressList; public final class MergedCellsTable extends RecordAggregate { - // enforced by the 8224 byte limit - private static final int MAX_MERGED_REGIONS = 1027; + // enforced by the 8224 byte limit + private static final int MAX_MERGED_REGIONS = 1027; - private final List _mergedRegions; + private final List _mergedRegions; - /** - * Creates an empty aggregate - */ - public MergedCellsTable() { - _mergedRegions = new ArrayList<>(); - } + /** + * Creates an empty aggregate + */ + public MergedCellsTable() { + _mergedRegions = new ArrayList<>(); + } - /** - * reads zero or more consecutive {@link MergeCellsRecord}s - */ - public void read(RecordStream rs) { + /** + * reads zero or more consecutive {@link MergeCellsRecord}s + */ + public void read(RecordStream rs) { while (rs.peekNextClass() == MergeCellsRecord.class) { - MergeCellsRecord mcr = (MergeCellsRecord) rs.getNext(); - int nRegions = mcr.getNumAreas(); - for (int i = 0; i < nRegions; i++) { - CellRangeAddress cra = mcr.getAreaAt(i); - _mergedRegions.add(cra); - } - } - } + MergeCellsRecord mcr = (MergeCellsRecord) rs.getNext(); + int nRegions = mcr.getNumAreas(); + for (int i = 0; i < nRegions; i++) { + CellRangeAddress cra = mcr.getAreaAt(i); + _mergedRegions.add(cra); + } + } + } - @Override - public int getRecordSize() { - // a bit cheaper than the default impl - int nRegions = _mergedRegions.size(); - if (nRegions < 1) { - // no need to write a single empty MergeCellsRecord - return 0; - } - int nMergedCellsRecords = nRegions / MAX_MERGED_REGIONS; - int nLeftoverMergedRegions = nRegions % MAX_MERGED_REGIONS; + @Override + public int getRecordSize() { + // a bit cheaper than the default impl + int nRegions = _mergedRegions.size(); + if (nRegions < 1) { + // no need to write a single empty MergeCellsRecord + return 0; + } + int nMergedCellsRecords = nRegions / MAX_MERGED_REGIONS; + int nLeftoverMergedRegions = nRegions % MAX_MERGED_REGIONS; return nMergedCellsRecords * (4 + CellRangeAddressList.getEncodedSize(MAX_MERGED_REGIONS)) + 4 + CellRangeAddressList.getEncodedSize(nLeftoverMergedRegions); - } + } - @Override + @Override public void visitContainedRecords(RecordVisitor rv) { - int nRegions = _mergedRegions.size(); - if (nRegions < 1) { - // no need to write a single empty MergeCellsRecord - return; - } + int nRegions = _mergedRegions.size(); + if (nRegions < 1) { + // no need to write a single empty MergeCellsRecord + return; + } - int nFullMergedCellsRecords = nRegions / MAX_MERGED_REGIONS; - int nLeftoverMergedRegions = nRegions % MAX_MERGED_REGIONS; - CellRangeAddress[] cras = new CellRangeAddress[nRegions]; - _mergedRegions.toArray(cras); + int nFullMergedCellsRecords = nRegions / MAX_MERGED_REGIONS; + int nLeftoverMergedRegions = nRegions % MAX_MERGED_REGIONS; + CellRangeAddress[] cras = new CellRangeAddress[nRegions]; + _mergedRegions.toArray(cras); - for (int i = 0; i < nFullMergedCellsRecords; i++) { - int startIx = i * MAX_MERGED_REGIONS; - rv.visitRecord(new MergeCellsRecord(cras, startIx, MAX_MERGED_REGIONS)); - } - if (nLeftoverMergedRegions > 0) { - int startIx = nFullMergedCellsRecords * MAX_MERGED_REGIONS; - rv.visitRecord(new MergeCellsRecord(cras, startIx, nLeftoverMergedRegions)); - } - } - public void addRecords(MergeCellsRecord[] mcrs) { - for (MergeCellsRecord mcr : mcrs) { - addMergeCellsRecord(mcr); - } - } + for (int i = 0; i < nFullMergedCellsRecords; i++) { + int startIx = i * MAX_MERGED_REGIONS; + rv.visitRecord(new MergeCellsRecord(cras, startIx, MAX_MERGED_REGIONS)); + } + if (nLeftoverMergedRegions > 0) { + int startIx = nFullMergedCellsRecords * MAX_MERGED_REGIONS; + rv.visitRecord(new MergeCellsRecord(cras, startIx, nLeftoverMergedRegions)); + } + } + public void addRecords(MergeCellsRecord[] mcrs) { + for (MergeCellsRecord mcr : mcrs) { + addMergeCellsRecord(mcr); + } + } - private void addMergeCellsRecord(MergeCellsRecord mcr) { - int nRegions = mcr.getNumAreas(); - for (int i = 0; i < nRegions; i++) { - CellRangeAddress cra = mcr.getAreaAt(i); - _mergedRegions.add(cra); - } - } + private void addMergeCellsRecord(MergeCellsRecord mcr) { + int nRegions = mcr.getNumAreas(); + for (int i = 0; i < nRegions; i++) { + CellRangeAddress cra = mcr.getAreaAt(i); + _mergedRegions.add(cra); + } + } - public CellRangeAddress get(int index) { - checkIndex(index); - return _mergedRegions.get(index); - } + public CellRangeAddress get(int index) { + checkIndex(index); + return _mergedRegions.get(index); + } - public void remove(int index) { - checkIndex(index); - _mergedRegions.remove(index); - } + public void remove(int index) { + checkIndex(index); + _mergedRegions.remove(index); + } - private void checkIndex(int index) { - if (index < 0 || index >= _mergedRegions.size()) { - throw new IllegalArgumentException("Specified CF index " + index - + " is outside the allowable range (0.." + (_mergedRegions.size() - 1) + ")"); - } - } + private void checkIndex(int index) { + if (index < 0 || index >= _mergedRegions.size()) { + throw new IllegalArgumentException("Specified CF index " + index + + " is outside the allowable range (0.." + (_mergedRegions.size() - 1) + ")"); + } + } - public void addArea(int rowFrom, int colFrom, int rowTo, int colTo) { - _mergedRegions.add(new CellRangeAddress(rowFrom, rowTo, colFrom, colTo)); - } + public void addArea(int rowFrom, int colFrom, int rowTo, int colTo) { + _mergedRegions.add(new CellRangeAddress(rowFrom, rowTo, colFrom, colTo)); + } - public int getNumberOfMergedRegions() { - return _mergedRegions.size(); - } + public int getNumberOfMergedRegions() { + return _mergedRegions.size(); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/PageSettingsBlock.java b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/PageSettingsBlock.java index c8d931f349..623a9cac73 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/PageSettingsBlock.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/PageSettingsBlock.java @@ -6,7 +6,7 @@ (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 + 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, diff --git a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/RecordAggregate.java b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/RecordAggregate.java index 79148c175e..48253d526e 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/RecordAggregate.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/RecordAggregate.java @@ -27,94 +27,94 @@ import org.apache.poi.hssf.record.RecordBase; */ public abstract class RecordAggregate extends RecordBase { - /** - * Visit each of the atomic BIFF records contained in this RecordAggregate in the order - * that they should be written to file. Implementors may or may not return the actual - * {@link Record}s being used to manage POI's internal implementation. Callers should not - * assume either way, and therefore only attempt to modify those {@link Record}s after cloning - * - * @param rv The visitor to use for callbacks while walking this object - */ - public abstract void visitContainedRecords(RecordVisitor rv); + /** + * Visit each of the atomic BIFF records contained in this RecordAggregate in the order + * that they should be written to file. Implementors may or may not return the actual + * {@link Record}s being used to manage POI's internal implementation. Callers should not + * assume either way, and therefore only attempt to modify those {@link Record}s after cloning + * + * @param rv The visitor to use for callbacks while walking this object + */ + public abstract void visitContainedRecords(RecordVisitor rv); - @Override - public final int serialize(int offset, byte[] data) { - SerializingRecordVisitor srv = new SerializingRecordVisitor(data, offset); - visitContainedRecords(srv); - return srv.countBytesWritten(); - } - @Override - public int getRecordSize() { - RecordSizingVisitor rsv = new RecordSizingVisitor(); - visitContainedRecords(rsv); - return rsv.getTotalSize(); - } + @Override + public final int serialize(int offset, byte[] data) { + SerializingRecordVisitor srv = new SerializingRecordVisitor(data, offset); + visitContainedRecords(srv); + return srv.countBytesWritten(); + } + @Override + public int getRecordSize() { + RecordSizingVisitor rsv = new RecordSizingVisitor(); + visitContainedRecords(rsv); + return rsv.getTotalSize(); + } - public interface RecordVisitor { - /** - * Implementors may call non-mutating methods on Record r. - * @param r must not be {@code null} - */ - void visitRecord(org.apache.poi.hssf.record.Record r); - } + public interface RecordVisitor { + /** + * Implementors may call non-mutating methods on Record r. + * @param r must not be {@code null} + */ + void visitRecord(org.apache.poi.hssf.record.Record r); + } - private static final class SerializingRecordVisitor implements RecordVisitor { + private static final class SerializingRecordVisitor implements RecordVisitor { - private final byte[] _data; - private final int _startOffset; - private int _countBytesWritten; + private final byte[] _data; + private final int _startOffset; + private int _countBytesWritten; - public SerializingRecordVisitor(byte[] data, int startOffset) { - _data = data; - _startOffset = startOffset; - _countBytesWritten = 0; - } - public int countBytesWritten() { - return _countBytesWritten; - } - @Override - public void visitRecord(org.apache.poi.hssf.record.Record r) { - int currentOffset = _startOffset + _countBytesWritten; - _countBytesWritten += r.serialize(currentOffset, _data); - } - } - private static final class RecordSizingVisitor implements RecordVisitor { + public SerializingRecordVisitor(byte[] data, int startOffset) { + _data = data; + _startOffset = startOffset; + _countBytesWritten = 0; + } + public int countBytesWritten() { + return _countBytesWritten; + } + @Override + public void visitRecord(org.apache.poi.hssf.record.Record r) { + int currentOffset = _startOffset + _countBytesWritten; + _countBytesWritten += r.serialize(currentOffset, _data); + } + } + private static final class RecordSizingVisitor implements RecordVisitor { - private int _totalSize; + private int _totalSize; - public RecordSizingVisitor() { - _totalSize = 0; - } - public int getTotalSize() { - return _totalSize; - } - @Override - public void visitRecord(org.apache.poi.hssf.record.Record r) { - _totalSize += r.getRecordSize(); - } - } - /** - * A wrapper for {@link RecordVisitor} which accumulates the sizes of all - * records visited. - */ - public static final class PositionTrackingVisitor implements RecordVisitor { - private final RecordVisitor _rv; - private int _position; + public RecordSizingVisitor() { + _totalSize = 0; + } + public int getTotalSize() { + return _totalSize; + } + @Override + public void visitRecord(org.apache.poi.hssf.record.Record r) { + _totalSize += r.getRecordSize(); + } + } + /** + * A wrapper for {@link RecordVisitor} which accumulates the sizes of all + * records visited. + */ + public static final class PositionTrackingVisitor implements RecordVisitor { + private final RecordVisitor _rv; + private int _position; - public PositionTrackingVisitor(RecordVisitor rv, int initialPosition) { - _rv = rv; - _position = initialPosition; - } - @Override - public void visitRecord(org.apache.poi.hssf.record.Record r) { - _position += r.getRecordSize(); - _rv.visitRecord(r); - } - public void setPosition(int position) { - _position = position; - } - public int getPosition() { - return _position; - } - } + public PositionTrackingVisitor(RecordVisitor rv, int initialPosition) { + _rv = rv; + _position = initialPosition; + } + @Override + public void visitRecord(org.apache.poi.hssf.record.Record r) { + _position += r.getRecordSize(); + _rv.visitRecord(r); + } + public void setPosition(int position) { + _position = position; + } + public int getPosition() { + return _position; + } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/SharedValueManager.java b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/SharedValueManager.java index 9a635b566a..20d73d80a3 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/SharedValueManager.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/SharedValueManager.java @@ -43,121 +43,121 @@ import org.apache.poi.ss.util.CellReference; */ public final class SharedValueManager { - private static final class SharedFormulaGroup { - private final SharedFormulaRecord _sfr; - private final FormulaRecordAggregate[] _frAggs; - private int _numberOfFormulas; - /** - * Coordinates of the first cell having a formula that uses this shared formula. - * This is often but not always the top left cell in the range covered by - * {@link #_sfr} - */ - private final CellReference _firstCell; + private static final class SharedFormulaGroup { + private final SharedFormulaRecord _sfr; + private final FormulaRecordAggregate[] _frAggs; + private int _numberOfFormulas; + /** + * Coordinates of the first cell having a formula that uses this shared formula. + * This is often but not always the top left cell in the range covered by + * {@link #_sfr} + */ + private final CellReference _firstCell; - public SharedFormulaGroup(SharedFormulaRecord sfr, CellReference firstCell) { - if (!sfr.isInRange(firstCell.getRow(), firstCell.getCol())) { - throw new IllegalArgumentException("First formula cell " + firstCell.formatAsString() - + " is not shared formula range " + sfr.getRange() + "."); - } - _sfr = sfr; - _firstCell = firstCell; - int width = sfr.getLastColumn() - sfr.getFirstColumn() + 1; - int height = sfr.getLastRow() - sfr.getFirstRow() + 1; - _frAggs = new FormulaRecordAggregate[width * height]; - _numberOfFormulas = 0; - } + public SharedFormulaGroup(SharedFormulaRecord sfr, CellReference firstCell) { + if (!sfr.isInRange(firstCell.getRow(), firstCell.getCol())) { + throw new IllegalArgumentException("First formula cell " + firstCell.formatAsString() + + " is not shared formula range " + sfr.getRange() + "."); + } + _sfr = sfr; + _firstCell = firstCell; + int width = sfr.getLastColumn() - sfr.getFirstColumn() + 1; + int height = sfr.getLastRow() - sfr.getFirstRow() + 1; + _frAggs = new FormulaRecordAggregate[width * height]; + _numberOfFormulas = 0; + } - public void add(FormulaRecordAggregate agg) { - if (_numberOfFormulas == 0) { - if (_firstCell.getRow() != agg.getRow() || _firstCell.getCol() != agg.getColumn()) { - throw new IllegalStateException("shared formula coding error: "+_firstCell.getCol()+'/'+_firstCell.getRow()+" != "+agg.getColumn()+'/'+agg.getRow()); - } - } - if (_numberOfFormulas >= _frAggs.length) { - throw new RuntimeException("Too many formula records for shared formula group"); - } - _frAggs[_numberOfFormulas++] = agg; - } + public void add(FormulaRecordAggregate agg) { + if (_numberOfFormulas == 0) { + if (_firstCell.getRow() != agg.getRow() || _firstCell.getCol() != agg.getColumn()) { + throw new IllegalStateException("shared formula coding error: "+_firstCell.getCol()+'/'+_firstCell.getRow()+" != "+agg.getColumn()+'/'+agg.getRow()); + } + } + if (_numberOfFormulas >= _frAggs.length) { + throw new RuntimeException("Too many formula records for shared formula group"); + } + _frAggs[_numberOfFormulas++] = agg; + } - public void unlinkSharedFormulas() { - for (int i = 0; i < _numberOfFormulas; i++) { - _frAggs[i].unlinkSharedFormula(); - } - } + public void unlinkSharedFormulas() { + for (int i = 0; i < _numberOfFormulas; i++) { + _frAggs[i].unlinkSharedFormula(); + } + } - public SharedFormulaRecord getSFR() { - return _sfr; - } + public SharedFormulaRecord getSFR() { + return _sfr; + } - public final String toString() { - return getClass().getName() + " [" + - _sfr.getRange() + - "]"; - } - } + public final String toString() { + return getClass().getName() + " [" + + _sfr.getRange() + + "]"; + } + } - /** - * @return a new empty SharedValueManager. - */ - public static SharedValueManager createEmpty() { - // Note - must create distinct instances because they are assumed to be mutable. - return new SharedValueManager( - new SharedFormulaRecord[0], new CellReference[0], new ArrayRecord[0], new TableRecord[0]); - } - private final List _arrayRecords; - private final TableRecord[] _tableRecords; - private final Map _groupsBySharedFormulaRecord; - /** cached for optimization purposes */ + /** + * @return a new empty SharedValueManager. + */ + public static SharedValueManager createEmpty() { + // Note - must create distinct instances because they are assumed to be mutable. + return new SharedValueManager( + new SharedFormulaRecord[0], new CellReference[0], new ArrayRecord[0], new TableRecord[0]); + } + private final List _arrayRecords; + private final TableRecord[] _tableRecords; + private final Map _groupsBySharedFormulaRecord; + /** cached for optimization purposes */ private Map _groupsCache; - private SharedValueManager(SharedFormulaRecord[] sharedFormulaRecords, - CellReference[] firstCells, ArrayRecord[] arrayRecords, TableRecord[] tableRecords) { - int nShF = sharedFormulaRecords.length; - if (nShF != firstCells.length) { - throw new IllegalArgumentException("array sizes don't match: " + nShF + "!=" + firstCells.length + "."); - } - _arrayRecords = toList(arrayRecords); - _tableRecords = tableRecords; - Map m = new HashMap<>(nShF * 3 / 2); - for (int i = 0; i < nShF; i++) { - SharedFormulaRecord sfr = sharedFormulaRecords[i]; - m.put(sfr, new SharedFormulaGroup(sfr, firstCells[i])); - } - _groupsBySharedFormulaRecord = m; - } + private SharedValueManager(SharedFormulaRecord[] sharedFormulaRecords, + CellReference[] firstCells, ArrayRecord[] arrayRecords, TableRecord[] tableRecords) { + int nShF = sharedFormulaRecords.length; + if (nShF != firstCells.length) { + throw new IllegalArgumentException("array sizes don't match: " + nShF + "!=" + firstCells.length + "."); + } + _arrayRecords = toList(arrayRecords); + _tableRecords = tableRecords; + Map m = new HashMap<>(nShF * 3 / 2); + for (int i = 0; i < nShF; i++) { + SharedFormulaRecord sfr = sharedFormulaRecords[i]; + m.put(sfr, new SharedFormulaGroup(sfr, firstCells[i])); + } + _groupsBySharedFormulaRecord = m; + } - /** - * @return a modifiable list, independent of the supplied array - */ - private static List toList(Z[] zz) { - List result = new ArrayList<>(zz.length); - Collections.addAll(result, zz); - return result; - } + /** + * @return a modifiable list, independent of the supplied array + */ + private static List toList(Z[] zz) { + List result = new ArrayList<>(zz.length); + Collections.addAll(result, zz); + return result; + } - /** - */ - public static SharedValueManager create(SharedFormulaRecord[] sharedFormulaRecords, - CellReference[] firstCells, ArrayRecord[] arrayRecords, TableRecord[] tableRecords) { - if (sharedFormulaRecords.length + firstCells.length + arrayRecords.length + tableRecords.length < 1) { - return createEmpty(); - } - return new SharedValueManager(sharedFormulaRecords, firstCells, arrayRecords, tableRecords); - } + /** + */ + public static SharedValueManager create(SharedFormulaRecord[] sharedFormulaRecords, + CellReference[] firstCells, ArrayRecord[] arrayRecords, TableRecord[] tableRecords) { + if (sharedFormulaRecords.length + firstCells.length + arrayRecords.length + tableRecords.length < 1) { + return createEmpty(); + } + return new SharedValueManager(sharedFormulaRecords, firstCells, arrayRecords, tableRecords); + } - /** - * @param firstCell as extracted from the {@link ExpPtg} from the cell's formula. - * @return never {@code null} - */ - public SharedFormulaRecord linkSharedFormulaRecord(CellReference firstCell, FormulaRecordAggregate agg) { - SharedFormulaGroup result = findFormulaGroupForCell(firstCell); + /** + * @param firstCell as extracted from the {@link ExpPtg} from the cell's formula. + * @return never {@code null} + */ + public SharedFormulaRecord linkSharedFormulaRecord(CellReference firstCell, FormulaRecordAggregate agg) { + SharedFormulaGroup result = findFormulaGroupForCell(firstCell); if(null == result) { throw new RuntimeException("Failed to find a matching shared formula record"); } - result.add(agg); - return result.getSFR(); - } + result.add(agg); + return result.getSFR(); + } private SharedFormulaGroup findFormulaGroupForCell(final CellReference cellRef) { if(null == _groupsCache) { @@ -174,34 +174,34 @@ public final class SharedValueManager { return ((cellRef.getCol()+1)<<16 | cellRef.getRow()); } - /** - * Gets the {@link SharedValueRecordBase} record if it should be encoded immediately after the - * formula record contained in the specified {@link FormulaRecordAggregate} agg. Note - the - * shared value record always appears after the first formula record in the group. For arrays - * and tables the first formula is always the in the top left cell. However, since shared - * formula groups can be sparse and/or overlap, the first formula may not actually be in the - * top left cell. - * - * @return the SHRFMLA, TABLE or ARRAY record for the formula cell, if it is the first cell of - * a table or array region. {@code null} if the formula cell is not shared/array/table, - * or if the specified formula is not the the first in the group. - */ - public SharedValueRecordBase getRecordForFirstCell(FormulaRecordAggregate agg) { - CellReference firstCell = agg.getFormulaRecord().getFormula().getExpReference(); - // perhaps this could be optimised by consulting the (somewhat unreliable) isShared flag - // and/or distinguishing between tExp and tTbl. - if (firstCell == null) { - // not a shared/array/table formula - return null; - } + /** + * Gets the {@link SharedValueRecordBase} record if it should be encoded immediately after the + * formula record contained in the specified {@link FormulaRecordAggregate} agg. Note - the + * shared value record always appears after the first formula record in the group. For arrays + * and tables the first formula is always the in the top left cell. However, since shared + * formula groups can be sparse and/or overlap, the first formula may not actually be in the + * top left cell. + * + * @return the SHRFMLA, TABLE or ARRAY record for the formula cell, if it is the first cell of + * a table or array region. {@code null} if the formula cell is not shared/array/table, + * or if the specified formula is not the the first in the group. + */ + public SharedValueRecordBase getRecordForFirstCell(FormulaRecordAggregate agg) { + CellReference firstCell = agg.getFormulaRecord().getFormula().getExpReference(); + // perhaps this could be optimised by consulting the (somewhat unreliable) isShared flag + // and/or distinguishing between tExp and tTbl. + if (firstCell == null) { + // not a shared/array/table formula + return null; + } - int row = firstCell.getRow(); - int column = firstCell.getCol(); - if (agg.getRow() != row || agg.getColumn() != column) { - // not the first formula cell in the group - return null; - } + int row = firstCell.getRow(); + int column = firstCell.getCol(); + if (agg.getRow() != row || agg.getColumn() != column) { + // not the first formula cell in the group + return null; + } if(!_groupsBySharedFormulaRecord.isEmpty()) { SharedFormulaGroup sfg = findFormulaGroupForCell(firstCell); @@ -210,70 +210,70 @@ public final class SharedValueManager { } } - // Since arrays and tables cannot be sparse (all cells in range participate) - // The first cell will be the top left in the range. So we can match the - // ARRAY/TABLE record directly. + // Since arrays and tables cannot be sparse (all cells in range participate) + // The first cell will be the top left in the range. So we can match the + // ARRAY/TABLE record directly. - for (TableRecord tr : _tableRecords) { - if (tr.isFirstCell(row, column)) { - return tr; - } - } - for (ArrayRecord ar : _arrayRecords) { - if (ar.isFirstCell(row, column)) { - return ar; - } - } - return null; - } + for (TableRecord tr : _tableRecords) { + if (tr.isFirstCell(row, column)) { + return tr; + } + } + for (ArrayRecord ar : _arrayRecords) { + if (ar.isFirstCell(row, column)) { + return ar; + } + } + return null; + } - /** - * Converts all {@link FormulaRecord}s handled by {@code sharedFormulaRecord} - * to plain unshared formulas - */ - public void unlink(SharedFormulaRecord sharedFormulaRecord) { - SharedFormulaGroup svg = _groupsBySharedFormulaRecord.remove(sharedFormulaRecord); - if (svg == null) { - throw new IllegalStateException("Failed to find formulas for shared formula"); - } - _groupsCache = null; // be sure to reset cached value - svg.unlinkSharedFormulas(); - } + /** + * Converts all {@link FormulaRecord}s handled by {@code sharedFormulaRecord} + * to plain unshared formulas + */ + public void unlink(SharedFormulaRecord sharedFormulaRecord) { + SharedFormulaGroup svg = _groupsBySharedFormulaRecord.remove(sharedFormulaRecord); + if (svg == null) { + throw new IllegalStateException("Failed to find formulas for shared formula"); + } + _groupsCache = null; // be sure to reset cached value + svg.unlinkSharedFormulas(); + } - /** - * Add specified Array Record. - */ - public void addArrayRecord(ArrayRecord ar) { - // could do a check here to make sure none of the ranges overlap - _arrayRecords.add(ar); - } + /** + * Add specified Array Record. + */ + public void addArrayRecord(ArrayRecord ar) { + // could do a check here to make sure none of the ranges overlap + _arrayRecords.add(ar); + } - /** - * Removes the {@link ArrayRecord} for the cell group containing the specified cell. - * The caller should clear (set blank) all cells in the returned range. - * @return the range of the array formula which was just removed. Never {@code null}. - */ - public CellRangeAddress8Bit removeArrayFormula(int rowIndex, int columnIndex) { - for (ArrayRecord ar : _arrayRecords) { - if (ar.isInRange(rowIndex, columnIndex)) { - _arrayRecords.remove(ar); - return ar.getRange(); - } - } - String ref = new CellReference(rowIndex, columnIndex, false, false).formatAsString(); - throw new IllegalArgumentException("Specified cell " + ref - + " is not part of an array formula."); - } + /** + * Removes the {@link ArrayRecord} for the cell group containing the specified cell. + * The caller should clear (set blank) all cells in the returned range. + * @return the range of the array formula which was just removed. Never {@code null}. + */ + public CellRangeAddress8Bit removeArrayFormula(int rowIndex, int columnIndex) { + for (ArrayRecord ar : _arrayRecords) { + if (ar.isInRange(rowIndex, columnIndex)) { + _arrayRecords.remove(ar); + return ar.getRange(); + } + } + String ref = new CellReference(rowIndex, columnIndex, false, false).formatAsString(); + throw new IllegalArgumentException("Specified cell " + ref + + " is not part of an array formula."); + } - /** - * @return the shared ArrayRecord identified by (firstRow, firstColumn). never {@code null}. - */ - public ArrayRecord getArrayRecord(int firstRow, int firstColumn) { - for(ArrayRecord ar : _arrayRecords) { - if(ar.isFirstCell(firstRow, firstColumn)) { - return ar; - } - } - return null; - } + /** + * @return the shared ArrayRecord identified by (firstRow, firstColumn). never {@code null}. + */ + public ArrayRecord getArrayRecord(int firstRow, int firstColumn) { + for(ArrayRecord ar : _arrayRecords) { + if(ar.isFirstCell(firstRow, firstColumn)) { + return ar; + } + } + return null; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ValueRecordsAggregate.java b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ValueRecordsAggregate.java index 573dd2e54f..7e6ac22aaf 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ValueRecordsAggregate.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/ValueRecordsAggregate.java @@ -39,256 +39,256 @@ import org.apache.poi.util.Removal; * Aggregate value records together. Things are easier to handle that way. */ public final class ValueRecordsAggregate implements Iterable { - private static final int MAX_ROW_INDEX = 0XFFFF; - private static final int INDEX_NOT_SET = -1; - private int firstcell = INDEX_NOT_SET; - private int lastcell = INDEX_NOT_SET; - private CellValueRecordInterface[][] records; + private static final int MAX_ROW_INDEX = 0XFFFF; + private static final int INDEX_NOT_SET = -1; + private int firstcell = INDEX_NOT_SET; + private int lastcell = INDEX_NOT_SET; + private CellValueRecordInterface[][] records; - /** Creates a new instance of ValueRecordsAggregate */ + /** Creates a new instance of ValueRecordsAggregate */ - public ValueRecordsAggregate() { - this(INDEX_NOT_SET, INDEX_NOT_SET, new CellValueRecordInterface[30][]); // We start with 30 Rows. - } - private ValueRecordsAggregate(int firstCellIx, int lastCellIx, CellValueRecordInterface[][] pRecords) { - firstcell = firstCellIx; - lastcell = lastCellIx; - records = pRecords; - } + public ValueRecordsAggregate() { + this(INDEX_NOT_SET, INDEX_NOT_SET, new CellValueRecordInterface[30][]); // We start with 30 Rows. + } + private ValueRecordsAggregate(int firstCellIx, int lastCellIx, CellValueRecordInterface[][] pRecords) { + firstcell = firstCellIx; + lastcell = lastCellIx; + records = pRecords; + } - public void insertCell(CellValueRecordInterface cell) { - short column = cell.getColumn(); - int row = cell.getRow(); - if (row >= records.length) { - CellValueRecordInterface[][] oldRecords = records; - int newSize = oldRecords.length * 2; - if (newSize < row + 1) - newSize = row + 1; - records = new CellValueRecordInterface[newSize][]; - System.arraycopy(oldRecords, 0, records, 0, oldRecords.length); - } - CellValueRecordInterface[] rowCells = records[row]; - if (rowCells == null) { - int newSize = column + 1; - if (newSize < 10) - newSize = 10; - rowCells = new CellValueRecordInterface[newSize]; - records[row] = rowCells; - } - if (column >= rowCells.length) { - CellValueRecordInterface[] oldRowCells = rowCells; - int newSize = oldRowCells.length * 2; - if (newSize < column + 1) - newSize = column + 1; - // if(newSize>257) newSize=257; // activate? - rowCells = new CellValueRecordInterface[newSize]; - System.arraycopy(oldRowCells, 0, rowCells, 0, oldRowCells.length); - records[row] = rowCells; - } - rowCells[column] = cell; + public void insertCell(CellValueRecordInterface cell) { + short column = cell.getColumn(); + int row = cell.getRow(); + if (row >= records.length) { + CellValueRecordInterface[][] oldRecords = records; + int newSize = oldRecords.length * 2; + if (newSize < row + 1) + newSize = row + 1; + records = new CellValueRecordInterface[newSize][]; + System.arraycopy(oldRecords, 0, records, 0, oldRecords.length); + } + CellValueRecordInterface[] rowCells = records[row]; + if (rowCells == null) { + int newSize = column + 1; + if (newSize < 10) + newSize = 10; + rowCells = new CellValueRecordInterface[newSize]; + records[row] = rowCells; + } + if (column >= rowCells.length) { + CellValueRecordInterface[] oldRowCells = rowCells; + int newSize = oldRowCells.length * 2; + if (newSize < column + 1) + newSize = column + 1; + // if(newSize>257) newSize=257; // activate? + rowCells = new CellValueRecordInterface[newSize]; + System.arraycopy(oldRowCells, 0, rowCells, 0, oldRowCells.length); + records[row] = rowCells; + } + rowCells[column] = cell; - if (column < firstcell || firstcell == INDEX_NOT_SET) { - firstcell = column; - } - if (column > lastcell || lastcell == INDEX_NOT_SET) { - lastcell = column; - } - } + if (column < firstcell || firstcell == INDEX_NOT_SET) { + firstcell = column; + } + if (column > lastcell || lastcell == INDEX_NOT_SET) { + lastcell = column; + } + } - public void removeCell(CellValueRecordInterface cell) { - if (cell == null) { - throw new IllegalArgumentException("cell must not be null"); - } - int row = cell.getRow(); - if (row >= records.length) { - throw new RuntimeException("cell row is out of range"); - } - CellValueRecordInterface[] rowCells = records[row]; - if (rowCells == null) { - throw new RuntimeException("cell row is already empty"); - } - short column = cell.getColumn(); - if (column >= rowCells.length) { - throw new RuntimeException("cell column is out of range"); - } - rowCells[column] = null; - } + public void removeCell(CellValueRecordInterface cell) { + if (cell == null) { + throw new IllegalArgumentException("cell must not be null"); + } + int row = cell.getRow(); + if (row >= records.length) { + throw new RuntimeException("cell row is out of range"); + } + CellValueRecordInterface[] rowCells = records[row]; + if (rowCells == null) { + throw new RuntimeException("cell row is already empty"); + } + short column = cell.getColumn(); + if (column >= rowCells.length) { + throw new RuntimeException("cell column is out of range"); + } + rowCells[column] = null; + } - public void removeAllCellsValuesForRow(int rowIndex) { - if (rowIndex < 0 || rowIndex > MAX_ROW_INDEX) { - throw new IllegalArgumentException("Specified rowIndex " + rowIndex - + " is outside the allowable range (0.." +MAX_ROW_INDEX + ")"); - } - if (rowIndex >= records.length) { - // this can happen when the client code has created a row, - // and then removes/replaces it before adding any cells. (see bug 46312) - return; - } + public void removeAllCellsValuesForRow(int rowIndex) { + if (rowIndex < 0 || rowIndex > MAX_ROW_INDEX) { + throw new IllegalArgumentException("Specified rowIndex " + rowIndex + + " is outside the allowable range (0.." +MAX_ROW_INDEX + ")"); + } + if (rowIndex >= records.length) { + // this can happen when the client code has created a row, + // and then removes/replaces it before adding any cells. (see bug 46312) + return; + } - records[rowIndex] = null; - } + records[rowIndex] = null; + } - public int getPhysicalNumberOfCells() { - int count = 0; - for (int r = 0; r < records.length; r++) { - CellValueRecordInterface[] rowCells = records[r]; - if (rowCells != null) { - for (int c = 0; c < rowCells.length; c++) { - if (rowCells[c] != null) - count++; - } - } - } - return count; - } + public int getPhysicalNumberOfCells() { + int count = 0; + for (int r = 0; r < records.length; r++) { + CellValueRecordInterface[] rowCells = records[r]; + if (rowCells != null) { + for (int c = 0; c < rowCells.length; c++) { + if (rowCells[c] != null) + count++; + } + } + } + return count; + } - public int getFirstCellNum() { - return firstcell; - } + public int getFirstCellNum() { + return firstcell; + } - public int getLastCellNum() { - return lastcell; - } + public int getLastCellNum() { + return lastcell; + } - public void addMultipleBlanks(MulBlankRecord mbr) { - for (int j = 0; j < mbr.getNumColumns(); j++) { - BlankRecord br = new BlankRecord(); + public void addMultipleBlanks(MulBlankRecord mbr) { + for (int j = 0; j < mbr.getNumColumns(); j++) { + BlankRecord br = new BlankRecord(); - br.setColumn(( short ) (j + mbr.getFirstColumn())); - br.setRow(mbr.getRow()); - br.setXFIndex(mbr.getXFAt(j)); - insertCell(br); - } - } + br.setColumn(( short ) (j + mbr.getFirstColumn())); + br.setRow(mbr.getRow()); + br.setXFIndex(mbr.getXFAt(j)); + insertCell(br); + } + } - /** - * Processes a single cell value record - * @param sfh used to resolve any shared-formulas/arrays/tables for the current sheet - */ - public void construct(CellValueRecordInterface rec, RecordStream rs, SharedValueManager sfh) { - if (rec instanceof FormulaRecord) { - FormulaRecord formulaRec = (FormulaRecord)rec; - // read optional cached text value - StringRecord cachedText; - Class nextClass = rs.peekNextClass(); - if (nextClass == StringRecord.class) { - cachedText = (StringRecord) rs.getNext(); - } else { - cachedText = null; - } - insertCell(new FormulaRecordAggregate(formulaRec, cachedText, sfh)); - } else { - insertCell(rec); - } - } + /** + * Processes a single cell value record + * @param sfh used to resolve any shared-formulas/arrays/tables for the current sheet + */ + public void construct(CellValueRecordInterface rec, RecordStream rs, SharedValueManager sfh) { + if (rec instanceof FormulaRecord) { + FormulaRecord formulaRec = (FormulaRecord)rec; + // read optional cached text value + StringRecord cachedText; + Class nextClass = rs.peekNextClass(); + if (nextClass == StringRecord.class) { + cachedText = (StringRecord) rs.getNext(); + } else { + cachedText = null; + } + insertCell(new FormulaRecordAggregate(formulaRec, cachedText, sfh)); + } else { + insertCell(rec); + } + } - /** Tallies a count of the size of the cell records - * that are attached to the rows in the range specified. - */ - public int getRowCellBlockSize(int startRow, int endRow) { - int result = 0; - for(int rowIx=startRow; rowIx<=endRow && rowIx= records.length) { - return false; - } - CellValueRecordInterface[] rowCells=records[row]; - if(rowCells==null) return false; - for(int col=0;col= records.length) { + return false; + } + CellValueRecordInterface[] rowCells=records[row]; + if(rowCells==null) return false; + for(int col=0;col 1) { - result += (10 + 2*nBlank); - i+=nBlank-1; - } else { - result += cvr.getRecordSize(); - } - } - return result; - } + private static int getRowSerializedSize(CellValueRecordInterface[] rowCells) { + if(rowCells == null) { + return 0; + } + int result = 0; + for (int i = 0; i < rowCells.length; i++) { + RecordBase cvr = (RecordBase) rowCells[i]; + if(cvr == null) { + continue; + } + int nBlank = countBlanks(rowCells, i); + if (nBlank > 1) { + result += (10 + 2*nBlank); + i+=nBlank-1; + } else { + result += cvr.getRecordSize(); + } + } + return result; + } - public void visitCellsForRow(int rowIndex, RecordVisitor rv) { + public void visitCellsForRow(int rowIndex, RecordVisitor rv) { - CellValueRecordInterface[] rowCells = records[rowIndex]; - if(rowCells == null) { - throw new IllegalArgumentException("Row [" + rowIndex + "] is empty"); - } + CellValueRecordInterface[] rowCells = records[rowIndex]; + if(rowCells == null) { + throw new IllegalArgumentException("Row [" + rowIndex + "] is empty"); + } - for (int i = 0; i < rowCells.length; i++) { - RecordBase cvr = (RecordBase) rowCells[i]; - if(cvr == null) { - continue; - } - int nBlank = countBlanks(rowCells, i); - if (nBlank > 1) { - rv.visitRecord(createMBR(rowCells, i, nBlank)); - i+=nBlank-1; - } else if (cvr instanceof RecordAggregate) { - RecordAggregate agg = (RecordAggregate) cvr; - agg.visitContainedRecords(rv); - } else { - rv.visitRecord((org.apache.poi.hssf.record.Record) cvr); - } - } - } + for (int i = 0; i < rowCells.length; i++) { + RecordBase cvr = (RecordBase) rowCells[i]; + if(cvr == null) { + continue; + } + int nBlank = countBlanks(rowCells, i); + if (nBlank > 1) { + rv.visitRecord(createMBR(rowCells, i, nBlank)); + i+=nBlank-1; + } else if (cvr instanceof RecordAggregate) { + RecordAggregate agg = (RecordAggregate) cvr; + agg.visitContainedRecords(rv); + } else { + rv.visitRecord((org.apache.poi.hssf.record.Record) cvr); + } + } + } - /** - * @return the number of consecutive {@link BlankRecord}s in the specified row - * starting from startIx. - */ - private static int countBlanks(CellValueRecordInterface[] rowCellValues, int startIx) { - int i = startIx; - while(i < rowCellValues.length) { - CellValueRecordInterface cvr = rowCellValues[i]; - if (!(cvr instanceof BlankRecord)) { - break; - } - i++; - } - return i - startIx; - } + /** + * @return the number of consecutive {@link BlankRecord}s in the specified row + * starting from startIx. + */ + private static int countBlanks(CellValueRecordInterface[] rowCellValues, int startIx) { + int i = startIx; + while(i < rowCellValues.length) { + CellValueRecordInterface cvr = rowCellValues[i]; + if (!(cvr instanceof BlankRecord)) { + break; + } + i++; + } + return i - startIx; + } - private MulBlankRecord createMBR(CellValueRecordInterface[] cellValues, int startIx, int nBlank) { + private MulBlankRecord createMBR(CellValueRecordInterface[] cellValues, int startIx, int nBlank) { - short[] xfs = new short[nBlank]; - for (int i = 0; i < xfs.length; i++) { - xfs[i] = cellValues[startIx + i].getXFIndex(); - } - int rowIx = cellValues[startIx].getRow(); - return new MulBlankRecord(rowIx, startIx, xfs); - } + short[] xfs = new short[nBlank]; + for (int i = 0; i < xfs.length; i++) { + xfs[i] = cellValues[startIx + i].getXFIndex(); + } + int rowIx = cellValues[startIx].getRow(); + return new MulBlankRecord(rowIx, startIx, xfs); + } - public void updateFormulasAfterRowShift(FormulaShifter shifter, int currentExternSheetIndex) { - for (int i = 0; i < records.length; i++) { - CellValueRecordInterface[] rowCells = records[i]; - if (rowCells == null) { - continue; - } - for (int j = 0; j < rowCells.length; j++) { - CellValueRecordInterface cell = rowCells[j]; - if (cell instanceof FormulaRecordAggregate) { + public void updateFormulasAfterRowShift(FormulaShifter shifter, int currentExternSheetIndex) { + for (int i = 0; i < records.length; i++) { + CellValueRecordInterface[] rowCells = records[i]; + if (rowCells == null) { + continue; + } + for (int j = 0; j < rowCells.length; j++) { + CellValueRecordInterface cell = rowCells[j]; + if (cell instanceof FormulaRecordAggregate) { FormulaRecordAggregate fra = (FormulaRecordAggregate)cell; Ptg[] ptgs = fra.getFormulaTokens(); // needs clone() inside this getter? Ptg[] ptgs2 = ((FormulaRecordAggregate)cell).getFormulaRecord().getParsedExpression(); // needs clone() inside this getter? @@ -297,74 +297,74 @@ public final class ValueRecordsAggregate implements Iterable { + /** + * iterator for CellValueRecordInterface + */ + class ValueIterator implements Iterator { - int curRowIndex, curColIndex = -1; - int nextRowIndex, nextColIndex = -1; + int curRowIndex, curColIndex = -1; + int nextRowIndex, nextColIndex = -1; - public ValueIterator() { - getNextPos(); - } + public ValueIterator() { + getNextPos(); + } - void getNextPos() { - if (nextRowIndex >= records.length) - return; // no next already + void getNextPos() { + if (nextRowIndex >= records.length) + return; // no next already - while (nextRowIndex < records.length) { - ++nextColIndex; - if (records[nextRowIndex] == null || nextColIndex >= records[nextRowIndex].length) { - ++nextRowIndex; - nextColIndex = -1; - continue; - } + while (nextRowIndex < records.length) { + ++nextColIndex; + if (records[nextRowIndex] == null || nextColIndex >= records[nextRowIndex].length) { + ++nextRowIndex; + nextColIndex = -1; + continue; + } - if (records[nextRowIndex][nextColIndex] != null) - return; // next cell found - } - // no next found - } + if (records[nextRowIndex][nextColIndex] != null) + return; // next cell found + } + // no next found + } - public boolean hasNext() { - return nextRowIndex < records.length; - } + public boolean hasNext() { + return nextRowIndex < records.length; + } - public CellValueRecordInterface next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } + public CellValueRecordInterface next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } - curRowIndex = nextRowIndex; - curColIndex = nextColIndex; - final CellValueRecordInterface ret = records[curRowIndex][curColIndex]; - getNextPos(); - return ret; - } + curRowIndex = nextRowIndex; + curColIndex = nextColIndex; + final CellValueRecordInterface ret = records[curRowIndex][curColIndex]; + getNextPos(); + return ret; + } - public void remove() { - records[curRowIndex][curColIndex] = null; - } - } + public void remove() { + records[curRowIndex][curColIndex] = null; + } + } - /** value iterator */ - public Iterator iterator() { - return new ValueIterator(); - } + /** value iterator */ + public Iterator iterator() { + return new ValueIterator(); + } - /** - * @deprecated use {@link org.apache.poi.hssf.usermodel.HSSFSheet#cloneSheet(HSSFWorkbook)} instead - */ - @Override - @SuppressWarnings("squid:S2975") - @Deprecated - @Removal(version = "5.0.0") - public Object clone() { - throw new RuntimeException("clone() should not be called. ValueRecordsAggregate should be copied via Sheet.cloneSheet()"); - } + /** + * @deprecated use {@link org.apache.poi.hssf.usermodel.HSSFSheet#cloneSheet(HSSFWorkbook)} instead + */ + @Override + @SuppressWarnings("squid:S2975") + @Deprecated + @Removal(version = "5.0.0") + public Object clone() { + throw new RuntimeException("clone() should not be called. ValueRecordsAggregate should be copied via Sheet.cloneSheet()"); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/WorksheetProtectionBlock.java b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/WorksheetProtectionBlock.java index 995b6466ba..da74baaf57 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/aggregates/WorksheetProtectionBlock.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/aggregates/WorksheetProtectionBlock.java @@ -33,212 +33,212 @@ import org.apache.poi.util.RecordFormatException; * (BIFF5-BIFF8)' */ public final class WorksheetProtectionBlock extends RecordAggregate { - // Every one of these component records is optional - // (The whole WorksheetProtectionBlock may not be present) - private ProtectRecord _protectRecord; - private ObjectProtectRecord _objectProtectRecord; - private ScenarioProtectRecord _scenarioProtectRecord; - private PasswordRecord _passwordRecord; + // Every one of these component records is optional + // (The whole WorksheetProtectionBlock may not be present) + private ProtectRecord _protectRecord; + private ObjectProtectRecord _objectProtectRecord; + private ScenarioProtectRecord _scenarioProtectRecord; + private PasswordRecord _passwordRecord; - /** - * Creates an empty WorksheetProtectionBlock - */ - public WorksheetProtectionBlock() { - // all fields empty - } + /** + * Creates an empty WorksheetProtectionBlock + */ + public WorksheetProtectionBlock() { + // all fields empty + } - /** - * @return {@code true} if the specified Record sid is one belonging to - * the 'Page Settings Block'. - */ - public static boolean isComponentRecord(int sid) { - switch (sid) { - case ProtectRecord.sid: - case ObjectProtectRecord.sid: - case ScenarioProtectRecord.sid: - case PasswordRecord.sid: - return true; - } - return false; - } + /** + * @return {@code true} if the specified Record sid is one belonging to + * the 'Page Settings Block'. + */ + public static boolean isComponentRecord(int sid) { + switch (sid) { + case ProtectRecord.sid: + case ObjectProtectRecord.sid: + case ScenarioProtectRecord.sid: + case PasswordRecord.sid: + return true; + } + return false; + } - private boolean readARecord(RecordStream rs) { - switch (rs.peekNextSid()) { - case ProtectRecord.sid: - checkNotPresent(_protectRecord); - _protectRecord = (ProtectRecord) rs.getNext(); - break; - case ObjectProtectRecord.sid: - checkNotPresent(_objectProtectRecord); - _objectProtectRecord = (ObjectProtectRecord) rs.getNext(); - break; - case ScenarioProtectRecord.sid: - checkNotPresent(_scenarioProtectRecord); - _scenarioProtectRecord = (ScenarioProtectRecord) rs.getNext(); - break; - case PasswordRecord.sid: - checkNotPresent(_passwordRecord); - _passwordRecord = (PasswordRecord) rs.getNext(); - break; - default: - // all other record types are not part of the PageSettingsBlock - return false; - } - return true; - } + private boolean readARecord(RecordStream rs) { + switch (rs.peekNextSid()) { + case ProtectRecord.sid: + checkNotPresent(_protectRecord); + _protectRecord = (ProtectRecord) rs.getNext(); + break; + case ObjectProtectRecord.sid: + checkNotPresent(_objectProtectRecord); + _objectProtectRecord = (ObjectProtectRecord) rs.getNext(); + break; + case ScenarioProtectRecord.sid: + checkNotPresent(_scenarioProtectRecord); + _scenarioProtectRecord = (ScenarioProtectRecord) rs.getNext(); + break; + case PasswordRecord.sid: + checkNotPresent(_passwordRecord); + _passwordRecord = (PasswordRecord) rs.getNext(); + break; + default: + // all other record types are not part of the PageSettingsBlock + return false; + } + return true; + } - private void checkNotPresent(org.apache.poi.hssf.record.Record rec) { - if (rec != null) { - throw new RecordFormatException("Duplicate PageSettingsBlock record (sid=0x" - + Integer.toHexString(rec.getSid()) + ")"); - } - } + private void checkNotPresent(org.apache.poi.hssf.record.Record rec) { + if (rec != null) { + throw new RecordFormatException("Duplicate PageSettingsBlock record (sid=0x" + + Integer.toHexString(rec.getSid()) + ")"); + } + } - @Override + @Override public void visitContainedRecords(RecordVisitor rv) { - // Replicates record order from Excel 2007, though this is not critical + // Replicates record order from Excel 2007, though this is not critical - visitIfPresent(_protectRecord, rv); - visitIfPresent(_objectProtectRecord, rv); - visitIfPresent(_scenarioProtectRecord, rv); - visitIfPresent(_passwordRecord, rv); - } + visitIfPresent(_protectRecord, rv); + visitIfPresent(_objectProtectRecord, rv); + visitIfPresent(_scenarioProtectRecord, rv); + visitIfPresent(_passwordRecord, rv); + } - private static void visitIfPresent(org.apache.poi.hssf.record.Record r, RecordVisitor rv) { - if (r != null) { - rv.visitRecord(r); - } - } + private static void visitIfPresent(org.apache.poi.hssf.record.Record r, RecordVisitor rv) { + if (r != null) { + rv.visitRecord(r); + } + } - public PasswordRecord getPasswordRecord() { - return _passwordRecord; - } + public PasswordRecord getPasswordRecord() { + return _passwordRecord; + } - public ScenarioProtectRecord getHCenter() { - return _scenarioProtectRecord; - } + public ScenarioProtectRecord getHCenter() { + return _scenarioProtectRecord; + } - /** - * This method reads WorksheetProtectionBlock records from the supplied RecordStream - * until the first non-WorksheetProtectionBlock record is encountered. As each record is read, - * it is incorporated into this WorksheetProtectionBlock. - *

- * As per the OOO documentation, the protection block records can be expected to be written - * together (with no intervening records), but earlier versions of POI (prior to Jun 2009) - * didn't do this. Workbooks with sheet protection created by those earlier POI versions - * seemed to be valid (Excel opens them OK). So PO allows continues to support reading of files - * with non continuous worksheet protection blocks. - * - *

- * Note - when POI writes out this WorksheetProtectionBlock, the records will always be - * written in one consolidated block (in the standard ordering) regardless of how scattered the - * records were when they were originally read. - */ - public void addRecords(RecordStream rs) { - while (true) { - if (!readARecord(rs)) { - break; - } - } - } + /** + * This method reads WorksheetProtectionBlock records from the supplied RecordStream + * until the first non-WorksheetProtectionBlock record is encountered. As each record is read, + * it is incorporated into this WorksheetProtectionBlock. + *

+ * As per the OOO documentation, the protection block records can be expected to be written + * together (with no intervening records), but earlier versions of POI (prior to Jun 2009) + * didn't do this. Workbooks with sheet protection created by those earlier POI versions + * seemed to be valid (Excel opens them OK). So PO allows continues to support reading of files + * with non continuous worksheet protection blocks. + * + *

+ * Note - when POI writes out this WorksheetProtectionBlock, the records will always be + * written in one consolidated block (in the standard ordering) regardless of how scattered the + * records were when they were originally read. + */ + public void addRecords(RecordStream rs) { + while (true) { + if (!readARecord(rs)) { + break; + } + } + } - /** - * @return the ProtectRecord. If one is not contained in the sheet, then one - * is created. - */ - private ProtectRecord getProtect() { - if (_protectRecord == null) { - _protectRecord = new ProtectRecord(false); - } - return _protectRecord; - } + /** + * @return the ProtectRecord. If one is not contained in the sheet, then one + * is created. + */ + private ProtectRecord getProtect() { + if (_protectRecord == null) { + _protectRecord = new ProtectRecord(false); + } + return _protectRecord; + } - /** - * @return the PasswordRecord. If one is not contained in the sheet, then - * one is created. - */ - private PasswordRecord getPassword() { - if (_passwordRecord == null) { - _passwordRecord = createPassword(); - } - return _passwordRecord; - } + /** + * @return the PasswordRecord. If one is not contained in the sheet, then + * one is created. + */ + private PasswordRecord getPassword() { + if (_passwordRecord == null) { + _passwordRecord = createPassword(); + } + return _passwordRecord; + } - /** - * protect a spreadsheet with a password (not encrypted, just sets protect - * flags and the password. - * - * @param password to set. Pass {@code null} to remove all protection - * @param shouldProtectObjects are protected - * @param shouldProtectScenarios are protected - */ - public void protectSheet(String password, boolean shouldProtectObjects, - boolean shouldProtectScenarios) { - if (password == null) { - _passwordRecord = null; - _protectRecord = null; - _objectProtectRecord = null; - _scenarioProtectRecord = null; - return; - } + /** + * protect a spreadsheet with a password (not encrypted, just sets protect + * flags and the password. + * + * @param password to set. Pass {@code null} to remove all protection + * @param shouldProtectObjects are protected + * @param shouldProtectScenarios are protected + */ + public void protectSheet(String password, boolean shouldProtectObjects, + boolean shouldProtectScenarios) { + if (password == null) { + _passwordRecord = null; + _protectRecord = null; + _objectProtectRecord = null; + _scenarioProtectRecord = null; + return; + } - ProtectRecord prec = getProtect(); - PasswordRecord pass = getPassword(); - prec.setProtect(true); - pass.setPassword((short)CryptoFunctions.createXorVerifier1(password)); - if (_objectProtectRecord == null && shouldProtectObjects) { - ObjectProtectRecord rec = createObjectProtect(); - rec.setProtect(true); - _objectProtectRecord = rec; - } - if (_scenarioProtectRecord == null && shouldProtectScenarios) { - ScenarioProtectRecord srec = createScenarioProtect(); - srec.setProtect(true); - _scenarioProtectRecord = srec; - } - } + ProtectRecord prec = getProtect(); + PasswordRecord pass = getPassword(); + prec.setProtect(true); + pass.setPassword((short)CryptoFunctions.createXorVerifier1(password)); + if (_objectProtectRecord == null && shouldProtectObjects) { + ObjectProtectRecord rec = createObjectProtect(); + rec.setProtect(true); + _objectProtectRecord = rec; + } + if (_scenarioProtectRecord == null && shouldProtectScenarios) { + ScenarioProtectRecord srec = createScenarioProtect(); + srec.setProtect(true); + _scenarioProtectRecord = srec; + } + } - public boolean isSheetProtected() { - return _protectRecord != null && _protectRecord.getProtect(); - } + public boolean isSheetProtected() { + return _protectRecord != null && _protectRecord.getProtect(); + } - public boolean isObjectProtected() { - return _objectProtectRecord != null && _objectProtectRecord.getProtect(); - } + public boolean isObjectProtected() { + return _objectProtectRecord != null && _objectProtectRecord.getProtect(); + } - public boolean isScenarioProtected() { - return _scenarioProtectRecord != null && _scenarioProtectRecord.getProtect(); - } + public boolean isScenarioProtected() { + return _scenarioProtectRecord != null && _scenarioProtectRecord.getProtect(); + } - /** - * creates an ObjectProtect record with protect set to false. - */ - private static ObjectProtectRecord createObjectProtect() { - ObjectProtectRecord retval = new ObjectProtectRecord(); - retval.setProtect(false); - return retval; - } + /** + * creates an ObjectProtect record with protect set to false. + */ + private static ObjectProtectRecord createObjectProtect() { + ObjectProtectRecord retval = new ObjectProtectRecord(); + retval.setProtect(false); + return retval; + } - /** - * creates a ScenarioProtect record with protect set to false. - */ - private static ScenarioProtectRecord createScenarioProtect() { - ScenarioProtectRecord retval = new ScenarioProtectRecord(); - retval.setProtect(false); - return retval; - } + /** + * creates a ScenarioProtect record with protect set to false. + */ + private static ScenarioProtectRecord createScenarioProtect() { + ScenarioProtectRecord retval = new ScenarioProtectRecord(); + retval.setProtect(false); + return retval; + } - /** - * creates a Password record with password set to 0x0000. - */ - private static PasswordRecord createPassword() { - return new PasswordRecord(0x0000); - } + /** + * creates a Password record with password set to 0x0000. + */ + private static PasswordRecord createPassword() { + return new PasswordRecord(0x0000); + } - public int getPasswordHash() { - if (_passwordRecord == null) { - return 0; - } - return _passwordRecord.getPassword(); - } + public int getPasswordHash() { + if (_passwordRecord == null) { + return 0; + } + return _passwordRecord.getPassword(); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/cf/FontFormatting.java b/poi/src/main/java/org/apache/poi/hssf/record/cf/FontFormatting.java index fe40aec82f..b8adbcb86f 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/cf/FontFormatting.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/cf/FontFormatting.java @@ -71,7 +71,7 @@ public final class FontFormatting implements Duplicatable, GenericRecord { /** * Bold boldness (bold) */ - private static final short FONT_WEIGHT_BOLD = 0x2bc; + private static final short FONT_WEIGHT_BOLD = 0x2bc; private final byte[] _rawData = new byte[RAW_DATA_SIZE]; diff --git a/poi/src/main/java/org/apache/poi/hssf/record/chart/CatLabRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/chart/CatLabRecord.java index 9cb603d253..98f35847db 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/chart/CatLabRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/chart/CatLabRecord.java @@ -30,80 +30,80 @@ import org.apache.poi.util.LittleEndianOutput; * CATLAB - Category Labels (0x0856) */ public final class CatLabRecord extends StandardRecord { - public static final short sid = 0x0856; + public static final short sid = 0x0856; - private short rt; - private short grbitFrt; - private short wOffset; - private short at; - private short grbit; - private Short unused; + private short rt; + private short grbitFrt; + private short wOffset; + private short at; + private short grbit; + private Short unused; - public CatLabRecord(CatLabRecord other) { - super(other); - rt = other.rt; - grbitFrt = other.grbitFrt; - wOffset = other.wOffset; - at = other.at; - grbit = other.grbit; - unused = other.unused; - } + public CatLabRecord(CatLabRecord other) { + super(other); + rt = other.rt; + grbitFrt = other.grbitFrt; + wOffset = other.wOffset; + at = other.at; + grbit = other.grbit; + unused = other.unused; + } - public CatLabRecord(RecordInputStream in) { - rt = in.readShort(); - grbitFrt = in.readShort(); - wOffset = in.readShort(); - at = in.readShort(); - grbit = in.readShort(); + public CatLabRecord(RecordInputStream in) { + rt = in.readShort(); + grbitFrt = in.readShort(); + wOffset = in.readShort(); + at = in.readShort(); + grbit = in.readShort(); - // Often, but not always has an unused short at the end - if(in.available() == 0) { - unused = null; - } else { - unused = in.readShort(); - } - } + // Often, but not always has an unused short at the end + if(in.available() == 0) { + unused = null; + } else { + unused = in.readShort(); + } + } - @Override - protected int getDataSize() { - return 2 + 2 + 2 + 2 + 2 + (unused==null? 0:2); - } + @Override + protected int getDataSize() { + return 2 + 2 + 2 + 2 + 2 + (unused==null? 0:2); + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public void serialize(LittleEndianOutput out) { - out.writeShort(rt); - out.writeShort(grbitFrt); - out.writeShort(wOffset); - out.writeShort(at); - out.writeShort(grbit); - if(unused != null) - out.writeShort(unused); - } + @Override + public void serialize(LittleEndianOutput out) { + out.writeShort(rt); + out.writeShort(grbitFrt); + out.writeShort(wOffset); + out.writeShort(at); + out.writeShort(grbit); + if(unused != null) + out.writeShort(unused); + } - @Override - public CatLabRecord copy() { - return new CatLabRecord(this); - } + @Override + public CatLabRecord copy() { + return new CatLabRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.CAT_LAB; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.CAT_LAB; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "rt", () -> rt, - "grbitFrt", () -> grbitFrt, - "wOffset", () -> wOffset, - "at", () -> at, - "grbit", () -> grbit, - "unused", () -> unused - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "rt", () -> rt, + "grbitFrt", () -> grbitFrt, + "wOffset", () -> wOffset, + "at", () -> at, + "grbit", () -> grbit, + "unused", () -> unused + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartEndBlockRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartEndBlockRecord.java index c222c8a47e..63da3f7bf1 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartEndBlockRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartEndBlockRecord.java @@ -30,73 +30,73 @@ import org.apache.poi.util.LittleEndianOutput; * ENDBLOCK - Chart Future Record Type End Block (0x0853) */ public final class ChartEndBlockRecord extends StandardRecord { - public static final short sid = 0x0853; + public static final short sid = 0x0853; - private short rt; - private short grbitFrt; - private short iObjectKind; - private byte[] unused; + private short rt; + private short grbitFrt; + private short iObjectKind; + private byte[] unused; - public ChartEndBlockRecord() {} + public ChartEndBlockRecord() {} - public ChartEndBlockRecord(ChartEndBlockRecord other) { - super(other); - rt = other.rt; - grbitFrt = other.grbitFrt; - iObjectKind = other.iObjectKind; - unused = (other.unused == null) ? null : other.unused.clone(); - } + public ChartEndBlockRecord(ChartEndBlockRecord other) { + super(other); + rt = other.rt; + grbitFrt = other.grbitFrt; + iObjectKind = other.iObjectKind; + unused = (other.unused == null) ? null : other.unused.clone(); + } - public ChartEndBlockRecord(RecordInputStream in) { - rt = in.readShort(); - grbitFrt = in.readShort(); - iObjectKind = in.readShort(); + public ChartEndBlockRecord(RecordInputStream in) { + rt = in.readShort(); + grbitFrt = in.readShort(); + iObjectKind = in.readShort(); - // Often, but not always has 6 unused bytes at the end - if(in.available() == 0) { - unused = new byte[0]; - } else { - unused = new byte[6]; - in.readFully(unused); - } - } + // Often, but not always has 6 unused bytes at the end + if(in.available() == 0) { + unused = new byte[0]; + } else { + unused = new byte[6]; + in.readFully(unused); + } + } - @Override - protected int getDataSize() { - return 2 + 2 + 2 + unused.length; - } + @Override + protected int getDataSize() { + return 2 + 2 + 2 + unused.length; + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public void serialize(LittleEndianOutput out) { - out.writeShort(rt); - out.writeShort(grbitFrt); - out.writeShort(iObjectKind); - // 6 bytes unused - out.write(unused); - } + @Override + public void serialize(LittleEndianOutput out) { + out.writeShort(rt); + out.writeShort(grbitFrt); + out.writeShort(iObjectKind); + // 6 bytes unused + out.write(unused); + } - @Override - public ChartEndBlockRecord copy() { - return new ChartEndBlockRecord(this); - } + @Override + public ChartEndBlockRecord copy() { + return new ChartEndBlockRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.CHART_END_BLOCK; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.CHART_END_BLOCK; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "rt", () -> rt, - "grbitFrt", () -> grbitFrt, - "iObjectKind", () -> iObjectKind, - "unused", () -> unused - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "rt", () -> rt, + "grbitFrt", () -> grbitFrt, + "iObjectKind", () -> iObjectKind, + "unused", () -> unused + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartEndObjectRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartEndObjectRecord.java index 86c8ea10db..168312c0d6 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartEndObjectRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartEndObjectRecord.java @@ -30,74 +30,74 @@ import org.apache.poi.util.LittleEndianOutput; * ENDOBJECT - Chart Future Record Type End Object (0x0855) */ public final class ChartEndObjectRecord extends StandardRecord { - public static final short sid = 0x0855; + public static final short sid = 0x0855; - private short rt; - private short grbitFrt; - private short iObjectKind; - private byte[] reserved; + private short rt; + private short grbitFrt; + private short iObjectKind; + private byte[] reserved; - public ChartEndObjectRecord(ChartEndObjectRecord other) { - super(other); - rt = other.rt; - grbitFrt = other.grbitFrt; - iObjectKind = other.iObjectKind; - reserved = (other.reserved == null) ? null : other.reserved.clone(); - } + public ChartEndObjectRecord(ChartEndObjectRecord other) { + super(other); + rt = other.rt; + grbitFrt = other.grbitFrt; + iObjectKind = other.iObjectKind; + reserved = (other.reserved == null) ? null : other.reserved.clone(); + } - public ChartEndObjectRecord(RecordInputStream in) { - rt = in.readShort(); - grbitFrt = in.readShort(); - iObjectKind = in.readShort(); + public ChartEndObjectRecord(RecordInputStream in) { + rt = in.readShort(); + grbitFrt = in.readShort(); + iObjectKind = in.readShort(); - // The spec says that there should be 6 bytes at the - // end, which must be there and must be zero - // However, sometimes Excel forgets them... - reserved = new byte[6]; - if(in.available() == 0) { - // They've gone missing... - } else { - // Read the reserved bytes - in.readFully(reserved); - } - } + // The spec says that there should be 6 bytes at the + // end, which must be there and must be zero + // However, sometimes Excel forgets them... + reserved = new byte[6]; + if(in.available() == 0) { + // They've gone missing... + } else { + // Read the reserved bytes + in.readFully(reserved); + } + } - @Override - protected int getDataSize() { - return 2 + 2 + 2 + 6; - } + @Override + protected int getDataSize() { + return 2 + 2 + 2 + 6; + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public void serialize(LittleEndianOutput out) { - out.writeShort(rt); - out.writeShort(grbitFrt); - out.writeShort(iObjectKind); - // 6 bytes unused - out.write(reserved); - } + @Override + public void serialize(LittleEndianOutput out) { + out.writeShort(rt); + out.writeShort(grbitFrt); + out.writeShort(iObjectKind); + // 6 bytes unused + out.write(reserved); + } - @Override - public ChartEndObjectRecord copy() { - return new ChartEndObjectRecord(this); - } + @Override + public ChartEndObjectRecord copy() { + return new ChartEndObjectRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.CHART_END_OBJECT; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.CHART_END_OBJECT; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "rt", () -> rt, - "grbitFrt", () -> grbitFrt, - "iObjectKind", () -> iObjectKind, - "reserved", () -> reserved - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "rt", () -> rt, + "grbitFrt", () -> grbitFrt, + "iObjectKind", () -> iObjectKind, + "reserved", () -> reserved + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartFRTInfoRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartFRTInfoRecord.java index 66e10fbab0..3685f06762 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartFRTInfoRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartFRTInfoRecord.java @@ -32,101 +32,101 @@ import org.apache.poi.util.LittleEndianOutput; * CHARTFRTINFO - Chart Future Record Type Info (0x0850) */ public final class ChartFRTInfoRecord extends StandardRecord { - public static final short sid = 0x850; + public static final short sid = 0x850; - private short rt; - private short grbitFrt; - private byte verOriginator; - private byte verWriter; - private CFRTID[] rgCFRTID; + private short rt; + private short grbitFrt; + private byte verOriginator; + private byte verWriter; + private CFRTID[] rgCFRTID; - private static final class CFRTID { - public static final int ENCODED_SIZE = 4; - private int rtFirst; - private int rtLast; + private static final class CFRTID { + public static final int ENCODED_SIZE = 4; + private int rtFirst; + private int rtLast; - public CFRTID(CFRTID other) { - rtFirst = other.rtFirst; - rtLast = other.rtLast; - } + public CFRTID(CFRTID other) { + rtFirst = other.rtFirst; + rtLast = other.rtLast; + } - public CFRTID(LittleEndianInput in) { - rtFirst = in.readShort(); - rtLast = in.readShort(); - } + public CFRTID(LittleEndianInput in) { + rtFirst = in.readShort(); + rtLast = in.readShort(); + } - public void serialize(LittleEndianOutput out) { - out.writeShort(rtFirst); - out.writeShort(rtLast); - } - } + public void serialize(LittleEndianOutput out) { + out.writeShort(rtFirst); + out.writeShort(rtLast); + } + } - public ChartFRTInfoRecord(ChartFRTInfoRecord other) { - super(other); - rt = other.rt; - grbitFrt = other.grbitFrt; - verOriginator = other.verOriginator; - verWriter = other.verWriter; - if (other.rgCFRTID != null) { - rgCFRTID = Stream.of(other.rgCFRTID).map(CFRTID::new).toArray(CFRTID[]::new); - } - } + public ChartFRTInfoRecord(ChartFRTInfoRecord other) { + super(other); + rt = other.rt; + grbitFrt = other.grbitFrt; + verOriginator = other.verOriginator; + verWriter = other.verWriter; + if (other.rgCFRTID != null) { + rgCFRTID = Stream.of(other.rgCFRTID).map(CFRTID::new).toArray(CFRTID[]::new); + } + } - public ChartFRTInfoRecord(RecordInputStream in) { - rt = in.readShort(); - grbitFrt = in.readShort(); - verOriginator = in.readByte(); - verWriter = in.readByte(); - int cCFRTID = in.readShort(); + public ChartFRTInfoRecord(RecordInputStream in) { + rt = in.readShort(); + grbitFrt = in.readShort(); + verOriginator = in.readByte(); + verWriter = in.readByte(); + int cCFRTID = in.readShort(); - rgCFRTID = new CFRTID[cCFRTID]; - for (int i = 0; i < cCFRTID; i++) { - rgCFRTID[i] = new CFRTID(in); - } - } + rgCFRTID = new CFRTID[cCFRTID]; + for (int i = 0; i < cCFRTID; i++) { + rgCFRTID[i] = new CFRTID(in); + } + } - @Override - protected int getDataSize() { - return 2 + 2 + 1 + 1 + 2 + rgCFRTID.length * CFRTID.ENCODED_SIZE; - } + @Override + protected int getDataSize() { + return 2 + 2 + 1 + 1 + 2 + rgCFRTID.length * CFRTID.ENCODED_SIZE; + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public void serialize(LittleEndianOutput out) { + @Override + public void serialize(LittleEndianOutput out) { - out.writeShort(rt); - out.writeShort(grbitFrt); - out.writeByte(verOriginator); - out.writeByte(verWriter); - out.writeShort(rgCFRTID.length); + out.writeShort(rt); + out.writeShort(grbitFrt); + out.writeByte(verOriginator); + out.writeByte(verWriter); + out.writeShort(rgCFRTID.length); - for (CFRTID cfrtid : rgCFRTID) { - cfrtid.serialize(out); - } - } + for (CFRTID cfrtid : rgCFRTID) { + cfrtid.serialize(out); + } + } - @Override - public ChartFRTInfoRecord copy() { - return new ChartFRTInfoRecord(this); - } + @Override + public ChartFRTInfoRecord copy() { + return new ChartFRTInfoRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.CHART_FRT_INFO; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.CHART_FRT_INFO; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "rt", () -> rt, - "grbitFrt", () -> grbitFrt, - "verOriginator", () -> verOriginator, - "verWriter", () -> verWriter, - "rgCFRTIDs", () -> rgCFRTID - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "rt", () -> rt, + "grbitFrt", () -> grbitFrt, + "verOriginator", () -> verOriginator, + "verWriter", () -> verWriter, + "rgCFRTIDs", () -> rgCFRTID + ); + } } \ No newline at end of file diff --git a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartStartBlockRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartStartBlockRecord.java index 6e9601e09a..69dab892b5 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartStartBlockRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartStartBlockRecord.java @@ -30,75 +30,75 @@ import org.apache.poi.util.LittleEndianOutput; * STARTBLOCK - Chart Future Record Type Start Block (0x0852) */ public final class ChartStartBlockRecord extends StandardRecord { - public static final short sid = 0x0852; + public static final short sid = 0x0852; - private short rt; - private short grbitFrt; - private short iObjectKind; - private short iObjectContext; - private short iObjectInstance1; - private short iObjectInstance2; + private short rt; + private short grbitFrt; + private short iObjectKind; + private short iObjectContext; + private short iObjectInstance1; + private short iObjectInstance2; - public ChartStartBlockRecord() {} + public ChartStartBlockRecord() {} - public ChartStartBlockRecord(ChartStartBlockRecord other) { - super(other); - rt = other.rt; - grbitFrt = other.grbitFrt; - iObjectKind = other.iObjectKind; - iObjectContext = other.iObjectContext; - iObjectInstance1 = other.iObjectInstance1; - iObjectInstance2 = other.iObjectInstance2; - } + public ChartStartBlockRecord(ChartStartBlockRecord other) { + super(other); + rt = other.rt; + grbitFrt = other.grbitFrt; + iObjectKind = other.iObjectKind; + iObjectContext = other.iObjectContext; + iObjectInstance1 = other.iObjectInstance1; + iObjectInstance2 = other.iObjectInstance2; + } - public ChartStartBlockRecord(RecordInputStream in) { - rt = in.readShort(); - grbitFrt = in.readShort(); - iObjectKind = in.readShort(); - iObjectContext = in.readShort(); - iObjectInstance1 = in.readShort(); - iObjectInstance2 = in.readShort(); - } + public ChartStartBlockRecord(RecordInputStream in) { + rt = in.readShort(); + grbitFrt = in.readShort(); + iObjectKind = in.readShort(); + iObjectContext = in.readShort(); + iObjectInstance1 = in.readShort(); + iObjectInstance2 = in.readShort(); + } - @Override - protected int getDataSize() { - return 2 + 2 + 2 + 2 + 2 + 2; - } + @Override + protected int getDataSize() { + return 2 + 2 + 2 + 2 + 2 + 2; + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public void serialize(LittleEndianOutput out) { - out.writeShort(rt); - out.writeShort(grbitFrt); - out.writeShort(iObjectKind); - out.writeShort(iObjectContext); - out.writeShort(iObjectInstance1); - out.writeShort(iObjectInstance2); - } + @Override + public void serialize(LittleEndianOutput out) { + out.writeShort(rt); + out.writeShort(grbitFrt); + out.writeShort(iObjectKind); + out.writeShort(iObjectContext); + out.writeShort(iObjectInstance1); + out.writeShort(iObjectInstance2); + } - @Override - public ChartStartBlockRecord copy() { - return new ChartStartBlockRecord(this); - } + @Override + public ChartStartBlockRecord copy() { + return new ChartStartBlockRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.CHART_START_BLOCK; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.CHART_START_BLOCK; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "rt", () -> rt, - "grbitFrt", () -> grbitFrt, - "iObjectKind", () -> iObjectKind, - "iObjectContext", () -> iObjectContext, - "iObjectInstance1", () -> iObjectInstance1, - "iObjectInstance2", () -> iObjectInstance2 - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "rt", () -> rt, + "grbitFrt", () -> grbitFrt, + "iObjectKind", () -> iObjectKind, + "iObjectContext", () -> iObjectContext, + "iObjectInstance1", () -> iObjectInstance1, + "iObjectInstance2", () -> iObjectInstance2 + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartStartObjectRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartStartObjectRecord.java index 27a600cfad..c1ad2197a0 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartStartObjectRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartStartObjectRecord.java @@ -30,73 +30,73 @@ import org.apache.poi.util.LittleEndianOutput; * STARTOBJECT - Chart Future Record Type Start Object (0x0854) */ public final class ChartStartObjectRecord extends StandardRecord { - public static final short sid = 0x0854; + public static final short sid = 0x0854; - private short rt; - private short grbitFrt; - private short iObjectKind; - private short iObjectContext; - private short iObjectInstance1; - private short iObjectInstance2; + private short rt; + private short grbitFrt; + private short iObjectKind; + private short iObjectContext; + private short iObjectInstance1; + private short iObjectInstance2; - public ChartStartObjectRecord(ChartStartObjectRecord other) { - super(other); - rt = other.rt; - grbitFrt = other.grbitFrt; - iObjectKind = other.iObjectKind; - iObjectContext = other.iObjectContext; - iObjectInstance1 = other.iObjectInstance1; - iObjectInstance2 = other.iObjectInstance2; - } + public ChartStartObjectRecord(ChartStartObjectRecord other) { + super(other); + rt = other.rt; + grbitFrt = other.grbitFrt; + iObjectKind = other.iObjectKind; + iObjectContext = other.iObjectContext; + iObjectInstance1 = other.iObjectInstance1; + iObjectInstance2 = other.iObjectInstance2; + } - public ChartStartObjectRecord(RecordInputStream in) { - rt = in.readShort(); - grbitFrt = in.readShort(); - iObjectKind = in.readShort(); - iObjectContext = in.readShort(); - iObjectInstance1 = in.readShort(); - iObjectInstance2 = in.readShort(); - } + public ChartStartObjectRecord(RecordInputStream in) { + rt = in.readShort(); + grbitFrt = in.readShort(); + iObjectKind = in.readShort(); + iObjectContext = in.readShort(); + iObjectInstance1 = in.readShort(); + iObjectInstance2 = in.readShort(); + } - @Override - protected int getDataSize() { - return 2 + 2 + 2 + 2 + 2 + 2; - } + @Override + protected int getDataSize() { + return 2 + 2 + 2 + 2 + 2 + 2; + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public void serialize(LittleEndianOutput out) { - out.writeShort(rt); - out.writeShort(grbitFrt); - out.writeShort(iObjectKind); - out.writeShort(iObjectContext); - out.writeShort(iObjectInstance1); - out.writeShort(iObjectInstance2); - } + @Override + public void serialize(LittleEndianOutput out) { + out.writeShort(rt); + out.writeShort(grbitFrt); + out.writeShort(iObjectKind); + out.writeShort(iObjectContext); + out.writeShort(iObjectInstance1); + out.writeShort(iObjectInstance2); + } - @Override - public ChartStartObjectRecord copy() { - return new ChartStartObjectRecord(this); - } + @Override + public ChartStartObjectRecord copy() { + return new ChartStartObjectRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.CHART_START_OBJECT; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.CHART_START_OBJECT; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "rt", () -> rt, - "grbitFrt", () -> grbitFrt, - "iObjectKind", () -> iObjectKind, - "iObjectContext", () -> iObjectContext, - "iObjectInstance1", () -> iObjectInstance1, - "iObjectInstance2", () -> iObjectInstance2 - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "rt", () -> rt, + "grbitFrt", () -> grbitFrt, + "iObjectKind", () -> iObjectKind, + "iObjectContext", () -> iObjectContext, + "iObjectInstance1", () -> iObjectInstance1, + "iObjectInstance2", () -> iObjectInstance2 + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartTitleFormatRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartTitleFormatRecord.java index 281cfb5138..ea062fbda7 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartTitleFormatRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/chart/ChartTitleFormatRecord.java @@ -36,107 +36,107 @@ import org.apache.poi.util.LittleEndianOutput; * Describes the formatting runs associated with a chart title. */ public class ChartTitleFormatRecord extends StandardRecord { - public static final short sid = 0x1050; + public static final short sid = 0x1050; - private final CTFormat[] _formats; + private final CTFormat[] _formats; - private static final class CTFormat implements GenericRecord { - public static final int ENCODED_SIZE=4; - private int _offset; - private int _fontIndex; + private static final class CTFormat implements GenericRecord { + public static final int ENCODED_SIZE=4; + private int _offset; + private int _fontIndex; - public CTFormat(CTFormat other) { - _offset = other._offset; - _fontIndex = other._fontIndex; - } + public CTFormat(CTFormat other) { + _offset = other._offset; + _fontIndex = other._fontIndex; + } - public CTFormat(RecordInputStream in) { - _offset = in.readShort(); - _fontIndex = in.readShort(); - } + public CTFormat(RecordInputStream in) { + _offset = in.readShort(); + _fontIndex = in.readShort(); + } - public int getOffset(){ - return _offset; - } - public void setOffset(int newOff){ - _offset = newOff; - } - public int getFontIndex() { - return _fontIndex; - } + public int getOffset(){ + return _offset; + } + public void setOffset(int newOff){ + _offset = newOff; + } + public int getFontIndex() { + return _fontIndex; + } - public void serialize(LittleEndianOutput out) { - out.writeShort(_offset); - out.writeShort(_fontIndex); - } + public void serialize(LittleEndianOutput out) { + out.writeShort(_offset); + out.writeShort(_fontIndex); + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "offset", this::getOffset, - "fontIndex", this::getFontIndex - ); - } - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "offset", this::getOffset, + "fontIndex", this::getFontIndex + ); + } + } - public ChartTitleFormatRecord(ChartTitleFormatRecord other) { - super(other); - _formats = Stream.of(other._formats).map(CTFormat::new).toArray(CTFormat[]::new); - } + public ChartTitleFormatRecord(ChartTitleFormatRecord other) { + super(other); + _formats = Stream.of(other._formats).map(CTFormat::new).toArray(CTFormat[]::new); + } - public ChartTitleFormatRecord(RecordInputStream in) { - int nRecs = in.readUShort(); - _formats = new CTFormat[nRecs]; + public ChartTitleFormatRecord(RecordInputStream in) { + int nRecs = in.readUShort(); + _formats = new CTFormat[nRecs]; - for(int i=0;i> getGenericProperties() { - return GenericRecordUtil.getGenericProperties("formats", () -> _formats); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties("formats", () -> _formats); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/chart/DataLabelExtensionRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/chart/DataLabelExtensionRecord.java index 6374d8fb8c..ad3b0c27fd 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/chart/DataLabelExtensionRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/chart/DataLabelExtensionRecord.java @@ -30,58 +30,58 @@ import org.apache.poi.util.LittleEndianOutput; * DATALABEXT - Chart Data Label Extension (0x086A) */ public final class DataLabelExtensionRecord extends StandardRecord { - public static final short sid = 0x086A; + public static final short sid = 0x086A; - private int rt; - private int grbitFrt; - private final byte[] unused = new byte[8]; + private int rt; + private int grbitFrt; + private final byte[] unused = new byte[8]; - public DataLabelExtensionRecord(DataLabelExtensionRecord other) { - super(other); - rt = other.rt; - grbitFrt = other.grbitFrt; - System.arraycopy(other.unused, 0, unused, 0, unused.length); - } + public DataLabelExtensionRecord(DataLabelExtensionRecord other) { + super(other); + rt = other.rt; + grbitFrt = other.grbitFrt; + System.arraycopy(other.unused, 0, unused, 0, unused.length); + } - public DataLabelExtensionRecord(RecordInputStream in) { - rt = in.readShort(); - grbitFrt = in.readShort(); - in.readFully(unused); - } + public DataLabelExtensionRecord(RecordInputStream in) { + rt = in.readShort(); + grbitFrt = in.readShort(); + in.readFully(unused); + } - @Override - protected int getDataSize() { - return 2 + 2 + 8; - } + @Override + protected int getDataSize() { + return 2 + 2 + 8; + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - protected void serialize(LittleEndianOutput out) { - out.writeShort(rt); - out.writeShort(grbitFrt); - out.write(unused); - } + @Override + protected void serialize(LittleEndianOutput out) { + out.writeShort(rt); + out.writeShort(grbitFrt); + out.write(unused); + } - @Override - public DataLabelExtensionRecord copy() { - return new DataLabelExtensionRecord(this); - } + @Override + public DataLabelExtensionRecord copy() { + return new DataLabelExtensionRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.DATA_LABEL_EXTENSION; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.DATA_LABEL_EXTENSION; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "rt", () -> rt, - "grbitFrt", () -> grbitFrt, - "unused", () -> unused - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "rt", () -> rt, + "grbitFrt", () -> grbitFrt, + "unused", () -> unused + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/chart/SeriesListRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/chart/SeriesListRecord.java index ac1fb5aba2..3bd6f704e7 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/chart/SeriesListRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/chart/SeriesListRecord.java @@ -44,16 +44,16 @@ public final class SeriesListRecord extends StandardRecord { } public SeriesListRecord(short[] seriesNumbers) { - field_1_seriesNumbers = (seriesNumbers == null) ? null : seriesNumbers.clone(); + field_1_seriesNumbers = (seriesNumbers == null) ? null : seriesNumbers.clone(); } public SeriesListRecord(RecordInputStream in) { - int nItems = in.readUShort(); - short[] ss = new short[nItems]; - for (int i = 0; i < nItems; i++) { - ss[i] = in.readShort(); + int nItems = in.readUShort(); + short[] ss = new short[nItems]; + for (int i = 0; i < nItems; i++) { + ss[i] = in.readShort(); - } + } field_1_seriesNumbers = ss; } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/chart/SeriesTextRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/chart/SeriesTextRecord.java index 4eecfc484a..d808e5dacf 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/chart/SeriesTextRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/chart/SeriesTextRecord.java @@ -32,112 +32,112 @@ import org.apache.poi.util.StringUtil; * Defines a series name */ public final class SeriesTextRecord extends StandardRecord { - public static final short sid = 0x100D; + public static final short sid = 0x100D; - /** - * the actual text cannot be longer than 255 characters - */ - private static final int MAX_LEN = 0xFF; + /** + * the actual text cannot be longer than 255 characters + */ + private static final int MAX_LEN = 0xFF; - private int field_1_id; - private boolean is16bit; - private String field_4_text; + private int field_1_id; + private boolean is16bit; + private String field_4_text; - public SeriesTextRecord() { - field_4_text = ""; - is16bit = false; - } + public SeriesTextRecord() { + field_4_text = ""; + is16bit = false; + } - public SeriesTextRecord(SeriesTextRecord other) { - super(other); - field_1_id = other.field_1_id; - is16bit = other.is16bit; - field_4_text = other.field_4_text; - } + public SeriesTextRecord(SeriesTextRecord other) { + super(other); + field_1_id = other.field_1_id; + is16bit = other.is16bit; + field_4_text = other.field_4_text; + } - public SeriesTextRecord(RecordInputStream in) { - field_1_id = in.readUShort(); - int field_2_textLength = in.readUByte(); - is16bit = (in.readUByte() & 0x01) != 0; - if (is16bit) { - field_4_text = in.readUnicodeLEString(field_2_textLength); - } else { - field_4_text = in.readCompressedUnicode(field_2_textLength); - } - } + public SeriesTextRecord(RecordInputStream in) { + field_1_id = in.readUShort(); + int field_2_textLength = in.readUByte(); + is16bit = (in.readUByte() & 0x01) != 0; + if (is16bit) { + field_4_text = in.readUnicodeLEString(field_2_textLength); + } else { + field_4_text = in.readCompressedUnicode(field_2_textLength); + } + } - public void serialize(LittleEndianOutput out) { + public void serialize(LittleEndianOutput out) { - out.writeShort(field_1_id); - out.writeByte(field_4_text.length()); - if (is16bit) { - // Excel (2007) seems to choose 16bit regardless of whether it is needed - out.writeByte(0x01); - StringUtil.putUnicodeLE(field_4_text, out); - } else { - // Excel can read this OK - out.writeByte(0x00); - StringUtil.putCompressedUnicode(field_4_text, out); - } - } + out.writeShort(field_1_id); + out.writeByte(field_4_text.length()); + if (is16bit) { + // Excel (2007) seems to choose 16bit regardless of whether it is needed + out.writeByte(0x01); + StringUtil.putUnicodeLE(field_4_text, out); + } else { + // Excel can read this OK + out.writeByte(0x00); + StringUtil.putCompressedUnicode(field_4_text, out); + } + } - protected int getDataSize() { - return 2 + 1 + 1 + field_4_text.length() * (is16bit ? 2 : 1); - } + protected int getDataSize() { + return 2 + 1 + 1 + field_4_text.length() * (is16bit ? 2 : 1); + } - public short getSid() { - return sid; - } + public short getSid() { + return sid; + } - @Override - public SeriesTextRecord copy() { - return new SeriesTextRecord(this); - } + @Override + public SeriesTextRecord copy() { + return new SeriesTextRecord(this); + } - /** - * Get the id field for the SeriesText record. - */ - public int getId() { - return field_1_id; - } + /** + * Get the id field for the SeriesText record. + */ + public int getId() { + return field_1_id; + } - /** - * Set the id field for the SeriesText record. - */ - public void setId(int id) { - field_1_id = id; - } + /** + * Set the id field for the SeriesText record. + */ + public void setId(int id) { + field_1_id = id; + } - /** - * Get the text field for the SeriesText record. - */ - public String getText() { - return field_4_text; - } + /** + * Get the text field for the SeriesText record. + */ + public String getText() { + return field_4_text; + } - /** - * Set the text field for the SeriesText record. - */ - public void setText(String text) { - if (text.length() > MAX_LEN) { - throw new IllegalArgumentException("Text is too long (" - + text.length() + ">" + MAX_LEN + ")"); - } - field_4_text = text; - is16bit = StringUtil.hasMultibyte(text); - } + /** + * Set the text field for the SeriesText record. + */ + public void setText(String text) { + if (text.length() > MAX_LEN) { + throw new IllegalArgumentException("Text is too long (" + + text.length() + ">" + MAX_LEN + ")"); + } + field_4_text = text; + is16bit = StringUtil.hasMultibyte(text); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.SERIES_TEXT; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.SERIES_TEXT; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "id", this::getId, - "bit16", () -> is16bit, - "text", this::getText - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "id", this::getId, + "bit16", () -> is16bit, + "text", this::getText + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/common/FeatFormulaErr2.java b/poi/src/main/java/org/apache/poi/hssf/record/common/FeatFormulaErr2.java index bdf9f06bc2..e78075ae9d 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/common/FeatFormulaErr2.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/common/FeatFormulaErr2.java @@ -41,114 +41,114 @@ import org.apache.poi.util.LittleEndianOutput; * https://msdn.microsoft.com/en-us/library/dd924991%28v=office.12%29.aspx */ public final class FeatFormulaErr2 implements SharedFeature { - private static final BitField CHECK_CALCULATION_ERRORS = BitFieldFactory.getInstance(0x01); - private static final BitField CHECK_EMPTY_CELL_REF = BitFieldFactory.getInstance(0x02); - private static final BitField CHECK_NUMBERS_AS_TEXT = BitFieldFactory.getInstance(0x04); - private static final BitField CHECK_INCONSISTENT_RANGES = BitFieldFactory.getInstance(0x08); - private static final BitField CHECK_INCONSISTENT_FORMULAS = BitFieldFactory.getInstance(0x10); - private static final BitField CHECK_DATETIME_FORMATS = BitFieldFactory.getInstance(0x20); - private static final BitField CHECK_UNPROTECTED_FORMULAS = BitFieldFactory.getInstance(0x40); - private static final BitField PERFORM_DATA_VALIDATION = BitFieldFactory.getInstance(0x80); + private static final BitField CHECK_CALCULATION_ERRORS = BitFieldFactory.getInstance(0x01); + private static final BitField CHECK_EMPTY_CELL_REF = BitFieldFactory.getInstance(0x02); + private static final BitField CHECK_NUMBERS_AS_TEXT = BitFieldFactory.getInstance(0x04); + private static final BitField CHECK_INCONSISTENT_RANGES = BitFieldFactory.getInstance(0x08); + private static final BitField CHECK_INCONSISTENT_FORMULAS = BitFieldFactory.getInstance(0x10); + private static final BitField CHECK_DATETIME_FORMATS = BitFieldFactory.getInstance(0x20); + private static final BitField CHECK_UNPROTECTED_FORMULAS = BitFieldFactory.getInstance(0x40); + private static final BitField PERFORM_DATA_VALIDATION = BitFieldFactory.getInstance(0x80); - /** - * What errors we should ignore - */ - private int errorCheck; + /** + * What errors we should ignore + */ + private int errorCheck; - public FeatFormulaErr2() {} + public FeatFormulaErr2() {} - public FeatFormulaErr2(FeatFormulaErr2 other) { - errorCheck = other.errorCheck; - } + public FeatFormulaErr2(FeatFormulaErr2 other) { + errorCheck = other.errorCheck; + } - public FeatFormulaErr2(RecordInputStream in) { - errorCheck = in.readInt(); - } + public FeatFormulaErr2(RecordInputStream in) { + errorCheck = in.readInt(); + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "errorCheck", getBitsAsString(this::_getRawErrorCheckValue, - new BitField[]{CHECK_CALCULATION_ERRORS, CHECK_EMPTY_CELL_REF, CHECK_NUMBERS_AS_TEXT, CHECK_INCONSISTENT_RANGES, CHECK_INCONSISTENT_FORMULAS, CHECK_DATETIME_FORMATS, CHECK_UNPROTECTED_FORMULAS, PERFORM_DATA_VALIDATION}, - new String[]{"CHECK_CALCULATION_ERRORS", "CHECK_EMPTY_CELL_REF", "CHECK_NUMBERS_AS_TEXT", "CHECK_INCONSISTENT_RANGES", "CHECK_INCONSISTENT_FORMULAS", "CHECK_DATETIME_FORMATS", "CHECK_UNPROTECTED_FORMULAS", "PERFORM_DATA_VALIDATION"}) - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "errorCheck", getBitsAsString(this::_getRawErrorCheckValue, + new BitField[]{CHECK_CALCULATION_ERRORS, CHECK_EMPTY_CELL_REF, CHECK_NUMBERS_AS_TEXT, CHECK_INCONSISTENT_RANGES, CHECK_INCONSISTENT_FORMULAS, CHECK_DATETIME_FORMATS, CHECK_UNPROTECTED_FORMULAS, PERFORM_DATA_VALIDATION}, + new String[]{"CHECK_CALCULATION_ERRORS", "CHECK_EMPTY_CELL_REF", "CHECK_NUMBERS_AS_TEXT", "CHECK_INCONSISTENT_RANGES", "CHECK_INCONSISTENT_FORMULAS", "CHECK_DATETIME_FORMATS", "CHECK_UNPROTECTED_FORMULAS", "PERFORM_DATA_VALIDATION"}) + ); + } - public String toString() { - return GenericRecordJsonWriter.marshal(this); - } + public String toString() { + return GenericRecordJsonWriter.marshal(this); + } - public void serialize(LittleEndianOutput out) { - out.writeInt(errorCheck); - } + public void serialize(LittleEndianOutput out) { + out.writeInt(errorCheck); + } - public int getDataSize() { - return 4; - } + public int getDataSize() { + return 4; + } - public int _getRawErrorCheckValue() { - return errorCheck; - } + public int _getRawErrorCheckValue() { + return errorCheck; + } - public boolean getCheckCalculationErrors() { - return CHECK_CALCULATION_ERRORS.isSet(errorCheck); - } - public void setCheckCalculationErrors(boolean checkCalculationErrors) { - errorCheck = CHECK_CALCULATION_ERRORS.setBoolean(errorCheck, checkCalculationErrors); - } + public boolean getCheckCalculationErrors() { + return CHECK_CALCULATION_ERRORS.isSet(errorCheck); + } + public void setCheckCalculationErrors(boolean checkCalculationErrors) { + errorCheck = CHECK_CALCULATION_ERRORS.setBoolean(errorCheck, checkCalculationErrors); + } - public boolean getCheckEmptyCellRef() { - return CHECK_EMPTY_CELL_REF.isSet(errorCheck); - } - public void setCheckEmptyCellRef(boolean checkEmptyCellRef) { - errorCheck = CHECK_EMPTY_CELL_REF.setBoolean(errorCheck, checkEmptyCellRef); - } + public boolean getCheckEmptyCellRef() { + return CHECK_EMPTY_CELL_REF.isSet(errorCheck); + } + public void setCheckEmptyCellRef(boolean checkEmptyCellRef) { + errorCheck = CHECK_EMPTY_CELL_REF.setBoolean(errorCheck, checkEmptyCellRef); + } - public boolean getCheckNumbersAsText() { - return CHECK_NUMBERS_AS_TEXT.isSet(errorCheck); - } - public void setCheckNumbersAsText(boolean checkNumbersAsText) { - errorCheck = CHECK_NUMBERS_AS_TEXT.setBoolean(errorCheck, checkNumbersAsText); - } + public boolean getCheckNumbersAsText() { + return CHECK_NUMBERS_AS_TEXT.isSet(errorCheck); + } + public void setCheckNumbersAsText(boolean checkNumbersAsText) { + errorCheck = CHECK_NUMBERS_AS_TEXT.setBoolean(errorCheck, checkNumbersAsText); + } - public boolean getCheckInconsistentRanges() { - return CHECK_INCONSISTENT_RANGES.isSet(errorCheck); - } - public void setCheckInconsistentRanges(boolean checkInconsistentRanges) { - errorCheck = CHECK_INCONSISTENT_RANGES.setBoolean(errorCheck, checkInconsistentRanges); - } + public boolean getCheckInconsistentRanges() { + return CHECK_INCONSISTENT_RANGES.isSet(errorCheck); + } + public void setCheckInconsistentRanges(boolean checkInconsistentRanges) { + errorCheck = CHECK_INCONSISTENT_RANGES.setBoolean(errorCheck, checkInconsistentRanges); + } - public boolean getCheckInconsistentFormulas() { - return CHECK_INCONSISTENT_FORMULAS.isSet(errorCheck); - } - public void setCheckInconsistentFormulas(boolean checkInconsistentFormulas) { - errorCheck = CHECK_INCONSISTENT_FORMULAS.setBoolean(errorCheck, checkInconsistentFormulas); - } + public boolean getCheckInconsistentFormulas() { + return CHECK_INCONSISTENT_FORMULAS.isSet(errorCheck); + } + public void setCheckInconsistentFormulas(boolean checkInconsistentFormulas) { + errorCheck = CHECK_INCONSISTENT_FORMULAS.setBoolean(errorCheck, checkInconsistentFormulas); + } - public boolean getCheckDateTimeFormats() { - return CHECK_DATETIME_FORMATS.isSet(errorCheck); - } - public void setCheckDateTimeFormats(boolean checkDateTimeFormats) { - errorCheck = CHECK_DATETIME_FORMATS.setBoolean(errorCheck, checkDateTimeFormats); - } + public boolean getCheckDateTimeFormats() { + return CHECK_DATETIME_FORMATS.isSet(errorCheck); + } + public void setCheckDateTimeFormats(boolean checkDateTimeFormats) { + errorCheck = CHECK_DATETIME_FORMATS.setBoolean(errorCheck, checkDateTimeFormats); + } - public boolean getCheckUnprotectedFormulas() { - return CHECK_UNPROTECTED_FORMULAS.isSet(errorCheck); - } - public void setCheckUnprotectedFormulas(boolean checkUnprotectedFormulas) { - errorCheck = CHECK_UNPROTECTED_FORMULAS.setBoolean(errorCheck, checkUnprotectedFormulas); - } + public boolean getCheckUnprotectedFormulas() { + return CHECK_UNPROTECTED_FORMULAS.isSet(errorCheck); + } + public void setCheckUnprotectedFormulas(boolean checkUnprotectedFormulas) { + errorCheck = CHECK_UNPROTECTED_FORMULAS.setBoolean(errorCheck, checkUnprotectedFormulas); + } - public boolean getPerformDataValidation() { - return PERFORM_DATA_VALIDATION.isSet(errorCheck); - } - public void setPerformDataValidation(boolean performDataValidation) { - errorCheck = PERFORM_DATA_VALIDATION.setBoolean(errorCheck, performDataValidation); - } + public boolean getPerformDataValidation() { + return PERFORM_DATA_VALIDATION.isSet(errorCheck); + } + public void setPerformDataValidation(boolean performDataValidation) { + errorCheck = PERFORM_DATA_VALIDATION.setBoolean(errorCheck, performDataValidation); + } - @Override - public FeatFormulaErr2 copy() { - return new FeatFormulaErr2(this); - } + @Override + public FeatFormulaErr2 copy() { + return new FeatFormulaErr2(this); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/common/FeatProtection.java b/poi/src/main/java/org/apache/poi/hssf/record/common/FeatProtection.java index b8d4aa80c9..b85803ecaa 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/common/FeatProtection.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/common/FeatProtection.java @@ -36,87 +36,87 @@ import org.apache.poi.util.StringUtil; * as {@link FeatRecord} */ public final class FeatProtection implements SharedFeature { - @SuppressWarnings("RedundantFieldInitialization") - public static final long NO_SELF_RELATIVE_SECURITY_FEATURE = 0; - public static final long HAS_SELF_RELATIVE_SECURITY_FEATURE = 1; + @SuppressWarnings("RedundantFieldInitialization") + public static final long NO_SELF_RELATIVE_SECURITY_FEATURE = 0; + public static final long HAS_SELF_RELATIVE_SECURITY_FEATURE = 1; - private int fSD; + private int fSD; - /** - * 0 means no password. Otherwise indicates the - * password verifier algorithm (same kind as - * {@link PasswordRecord} and - * {@link PasswordRev4Record}) - */ - private int passwordVerifier; + /** + * 0 means no password. Otherwise indicates the + * password verifier algorithm (same kind as + * {@link PasswordRecord} and + * {@link PasswordRev4Record}) + */ + private int passwordVerifier; - private String title; - private byte[] securityDescriptor; + private String title; + private byte[] securityDescriptor; - public FeatProtection() { - securityDescriptor = new byte[0]; - } + public FeatProtection() { + securityDescriptor = new byte[0]; + } - public FeatProtection(FeatProtection other) { - fSD = other.fSD; - passwordVerifier = other.passwordVerifier; - title = other.title; - securityDescriptor = (other.securityDescriptor == null) ? null : other.securityDescriptor.clone(); - } + public FeatProtection(FeatProtection other) { + fSD = other.fSD; + passwordVerifier = other.passwordVerifier; + title = other.title; + securityDescriptor = (other.securityDescriptor == null) ? null : other.securityDescriptor.clone(); + } - public FeatProtection(RecordInputStream in) { - fSD = in.readInt(); - passwordVerifier = in.readInt(); + public FeatProtection(RecordInputStream in) { + fSD = in.readInt(); + passwordVerifier = in.readInt(); - title = StringUtil.readUnicodeString(in); + title = StringUtil.readUnicodeString(in); - securityDescriptor = in.readRemainder(); - } + securityDescriptor = in.readRemainder(); + } - public void serialize(LittleEndianOutput out) { - out.writeInt(fSD); - out.writeInt(passwordVerifier); - StringUtil.writeUnicodeString(out, title); - out.write(securityDescriptor); - } + public void serialize(LittleEndianOutput out) { + out.writeInt(fSD); + out.writeInt(passwordVerifier); + StringUtil.writeUnicodeString(out, title); + out.write(securityDescriptor); + } - public int getDataSize() { - return 4 + 4 + StringUtil.getEncodedSize(title) + securityDescriptor.length; - } + public int getDataSize() { + return 4 + 4 + StringUtil.getEncodedSize(title) + securityDescriptor.length; + } - public int getPasswordVerifier() { - return passwordVerifier; - } - public void setPasswordVerifier(int passwordVerifier) { - this.passwordVerifier = passwordVerifier; - } + public int getPasswordVerifier() { + return passwordVerifier; + } + public void setPasswordVerifier(int passwordVerifier) { + this.passwordVerifier = passwordVerifier; + } - public String getTitle() { - return title; - } - public void setTitle(String title) { - this.title = title; - } + public String getTitle() { + return title; + } + public void setTitle(String title) { + this.title = title; + } - /** - * @return Self Relative - */ - public int getFSD() { - return fSD; - } + /** + * @return Self Relative + */ + public int getFSD() { + return fSD; + } - @Override - public FeatProtection copy() { - return new FeatProtection(this); - } + @Override + public FeatProtection copy() { + return new FeatProtection(this); + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "FSD", this::getFSD, - "passwordVerifier", this::getPasswordVerifier, - "title", this::getTitle, - "securityDescriptor", () -> securityDescriptor - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "FSD", this::getFSD, + "passwordVerifier", this::getPasswordVerifier, + "title", this::getTitle, + "securityDescriptor", () -> securityDescriptor + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/common/FeatSmartTag.java b/poi/src/main/java/org/apache/poi/hssf/record/common/FeatSmartTag.java index 976f9a6d1c..5c3bb316e7 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/common/FeatSmartTag.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/common/FeatSmartTag.java @@ -40,40 +40,40 @@ import org.apache.poi.util.LittleEndianOutput; * format documentation. */ public final class FeatSmartTag implements SharedFeature { - // TODO - process - private byte[] data; + // TODO - process + private byte[] data; - public FeatSmartTag() { - data = new byte[0]; - } + public FeatSmartTag() { + data = new byte[0]; + } - public FeatSmartTag(FeatSmartTag other) { - data = (other.data == null) ? null : other.data.clone(); - } + public FeatSmartTag(FeatSmartTag other) { + data = (other.data == null) ? null : other.data.clone(); + } - public FeatSmartTag(RecordInputStream in) { - data = in.readRemainder(); - } + public FeatSmartTag(RecordInputStream in) { + data = in.readRemainder(); + } - public String toString() { - return GenericRecordJsonWriter.marshal(this); - } + public String toString() { + return GenericRecordJsonWriter.marshal(this); + } - public int getDataSize() { - return data.length; - } + public int getDataSize() { + return data.length; + } - public void serialize(LittleEndianOutput out) { - out.write(data); - } + public void serialize(LittleEndianOutput out) { + out.write(data); + } - @Override - public FeatSmartTag copy() { - return new FeatSmartTag(this); - } + @Override + public FeatSmartTag copy() { + return new FeatSmartTag(this); + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties("data", () -> data); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties("data", () -> data); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/common/SharedFeature.java b/poi/src/main/java/org/apache/poi/hssf/record/common/SharedFeature.java index 5880bbc8ef..6e60d207e1 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/common/SharedFeature.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/common/SharedFeature.java @@ -24,8 +24,8 @@ import org.apache.poi.util.LittleEndianOutput; * Common Interface for all Shared Features */ public interface SharedFeature extends GenericRecord { - String toString(); - void serialize(LittleEndianOutput out); - int getDataSize(); - SharedFeature copy(); + String toString(); + void serialize(LittleEndianOutput out); + int getDataSize(); + SharedFeature copy(); } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/common/UnicodeString.java b/poi/src/main/java/org/apache/poi/hssf/record/common/UnicodeString.java index f087facd8e..caeeec0e9d 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/common/UnicodeString.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/common/UnicodeString.java @@ -177,9 +177,9 @@ public class UnicodeString implements Comparable, Duplicatable, G * @return number of characters */ public int getCharCount() { - if(field_1_charCount < 0) { - return field_1_charCount + 65536; - } + if(field_1_charCount < 0) { + return field_1_charCount + 65536; + } return field_1_charCount; } @@ -272,11 +272,11 @@ public class UnicodeString implements Comparable, Duplicatable, G public FormatRun getFormatRun(int index) { if (field_4_format_runs == null) { - return null; - } + return null; + } if (index < 0 || index >= field_4_format_runs.size()) { - return null; - } + return null; + } return field_4_format_runs.get(index); } @@ -300,8 +300,8 @@ public class UnicodeString implements Comparable, Duplicatable, G */ public void addFormatRun(FormatRun r) { if (field_4_format_runs == null) { - field_4_format_runs = new ArrayList<>(); - } + field_4_format_runs = new ArrayList<>(); + } int index = findFormatRunAt(r._character); if (index != -1) { diff --git a/poi/src/main/java/org/apache/poi/hssf/record/cont/ContinuableRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/cont/ContinuableRecord.java index dceb7b86b1..ab90d043be 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/cont/ContinuableRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/cont/ContinuableRecord.java @@ -29,52 +29,52 @@ import org.apache.poi.util.LittleEndianOutput; */ public abstract class ContinuableRecord extends Record { - protected ContinuableRecord() {} + protected ContinuableRecord() {} - protected ContinuableRecord(ContinuableRecord other) { - super(other); - } + protected ContinuableRecord(ContinuableRecord other) { + super(other); + } - /** - * Serializes this record's content to the supplied data output.

- * The standard BIFF header (ushort sid, ushort size) has been handled by the superclass, so - * only BIFF data should be written by this method. Simple data types can be written with the - * standard {@link LittleEndianOutput} methods. Methods from {@link ContinuableRecordOutput} - * can be used to serialize strings (with {@link ContinueRecord}s being written as required). - * If necessary, implementors can explicitly start {@link ContinueRecord}s (regardless of the - * amount of remaining space). - * - * @param out a data output stream - */ - protected abstract void serialize(ContinuableRecordOutput out); + /** + * Serializes this record's content to the supplied data output.

+ * The standard BIFF header (ushort sid, ushort size) has been handled by the superclass, so + * only BIFF data should be written by this method. Simple data types can be written with the + * standard {@link LittleEndianOutput} methods. Methods from {@link ContinuableRecordOutput} + * can be used to serialize strings (with {@link ContinueRecord}s being written as required). + * If necessary, implementors can explicitly start {@link ContinueRecord}s (regardless of the + * amount of remaining space). + * + * @param out a data output stream + */ + protected abstract void serialize(ContinuableRecordOutput out); - /** - * @return the total length of the encoded record(s) - * (Note - if any {@link ContinueRecord} is required, this result includes the - * size of those too) - */ - @Override - public final int getRecordSize() { - ContinuableRecordOutput out = ContinuableRecordOutput.createForCountingOnly(); - serialize(out); - out.terminate(); - return out.getTotalSize(); - } + /** + * @return the total length of the encoded record(s) + * (Note - if any {@link ContinueRecord} is required, this result includes the + * size of those too) + */ + @Override + public final int getRecordSize() { + ContinuableRecordOutput out = ContinuableRecordOutput.createForCountingOnly(); + serialize(out); + out.terminate(); + return out.getTotalSize(); + } - @Override - public final int serialize(int offset, byte[] data) { - int totalSize = 0; - try (LittleEndianByteArrayOutputStream leo = - new LittleEndianByteArrayOutputStream(data, offset)) { - ContinuableRecordOutput out = new ContinuableRecordOutput(leo, getSid()); - serialize(out); - out.terminate(); - totalSize = out.getTotalSize(); - } catch (IOException ioe) { - // should never happen in practice - throw new IllegalStateException(ioe); - } - return totalSize; - } + @Override + public final int serialize(int offset, byte[] data) { + int totalSize = 0; + try (LittleEndianByteArrayOutputStream leo = + new LittleEndianByteArrayOutputStream(data, offset)) { + ContinuableRecordOutput out = new ContinuableRecordOutput(leo, getSid()); + serialize(out); + out.terminate(); + totalSize = out.getTotalSize(); + } catch (IOException ioe) { + // should never happen in practice + throw new IllegalStateException(ioe); + } + return totalSize; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/cont/ContinuableRecordOutput.java b/poi/src/main/java/org/apache/poi/hssf/record/cont/ContinuableRecordOutput.java index 38857289c7..1f404cde52 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/cont/ContinuableRecordOutput.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/cont/ContinuableRecordOutput.java @@ -29,184 +29,184 @@ import org.apache.poi.util.StringUtil; */ public final class ContinuableRecordOutput implements LittleEndianOutput { - private final LittleEndianOutput _out; - private UnknownLengthRecordOutput _ulrOutput; - private int _totalPreviousRecordsSize; + private final LittleEndianOutput _out; + private UnknownLengthRecordOutput _ulrOutput; + private int _totalPreviousRecordsSize; - public ContinuableRecordOutput(LittleEndianOutput out, int sid) { - _ulrOutput = new UnknownLengthRecordOutput(out, sid); - _out = out; - _totalPreviousRecordsSize = 0; - } + public ContinuableRecordOutput(LittleEndianOutput out, int sid) { + _ulrOutput = new UnknownLengthRecordOutput(out, sid); + _out = out; + _totalPreviousRecordsSize = 0; + } - public static ContinuableRecordOutput createForCountingOnly() { - return new ContinuableRecordOutput(NOPOutput, -777); // fake sid - } + public static ContinuableRecordOutput createForCountingOnly() { + return new ContinuableRecordOutput(NOPOutput, -777); // fake sid + } - /** - * @return total number of bytes written so far (including all BIFF headers) - */ - public int getTotalSize() { - return _totalPreviousRecordsSize + _ulrOutput.getTotalSize(); - } - /** - * Terminates the last record (also updates its 'ushort size' field) - */ - void terminate() { - _ulrOutput.terminate(); - } - /** - * @return number of remaining bytes of space in current record - */ - public int getAvailableSpace() { - return _ulrOutput.getAvailableSpace(); - } + /** + * @return total number of bytes written so far (including all BIFF headers) + */ + public int getTotalSize() { + return _totalPreviousRecordsSize + _ulrOutput.getTotalSize(); + } + /** + * Terminates the last record (also updates its 'ushort size' field) + */ + void terminate() { + _ulrOutput.terminate(); + } + /** + * @return number of remaining bytes of space in current record + */ + public int getAvailableSpace() { + return _ulrOutput.getAvailableSpace(); + } - /** - * Terminates the current record and starts a new {@link ContinueRecord} (regardless - * of how much space is still available in the current record). - */ - public void writeContinue() { - _ulrOutput.terminate(); - _totalPreviousRecordsSize += _ulrOutput.getTotalSize(); - _ulrOutput = new UnknownLengthRecordOutput(_out, ContinueRecord.sid); - } - /** - * Will terminate the current record and start a new {@link ContinueRecord} - * if there isn't space for the requested number of bytes - * @param requiredContinuousSize The number of bytes that need to be written - */ - public void writeContinueIfRequired(int requiredContinuousSize) { - if (_ulrOutput.getAvailableSpace() < requiredContinuousSize) { - writeContinue(); - } - } + /** + * Terminates the current record and starts a new {@link ContinueRecord} (regardless + * of how much space is still available in the current record). + */ + public void writeContinue() { + _ulrOutput.terminate(); + _totalPreviousRecordsSize += _ulrOutput.getTotalSize(); + _ulrOutput = new UnknownLengthRecordOutput(_out, ContinueRecord.sid); + } + /** + * Will terminate the current record and start a new {@link ContinueRecord} + * if there isn't space for the requested number of bytes + * @param requiredContinuousSize The number of bytes that need to be written + */ + public void writeContinueIfRequired(int requiredContinuousSize) { + if (_ulrOutput.getAvailableSpace() < requiredContinuousSize) { + writeContinue(); + } + } - /** - * Writes the 'optionFlags' byte and encoded character data of a unicode string. This includes: - *

    - *
  • byte optionFlags
  • - *
  • encoded character data (in "ISO-8859-1" or "UTF-16LE" encoding)
  • - *
- * - * Notes: - *
    - *
  • The value of the 'is16bitEncoded' flag is determined by the actual character data - * of {@code text}
  • - *
  • The string options flag is never separated (by a {@link ContinueRecord}) from the - * first chunk of character data it refers to.
  • - *
  • The 'ushort length' field is assumed to have been explicitly written earlier. Hence, - * there may be an intervening {@link ContinueRecord}
  • - *
- */ - public void writeStringData(String text) { - boolean is16bitEncoded = StringUtil.hasMultibyte(text); - // calculate total size of the header and first encoded char - int keepTogetherSize = 1 + 1; // ushort len, at least one character byte - int optionFlags = 0x00; - if (is16bitEncoded) { - optionFlags |= 0x01; - keepTogetherSize += 1; // one extra byte for first char - } - writeContinueIfRequired(keepTogetherSize); - writeByte(optionFlags); - writeCharacterData(text, is16bitEncoded); - } - /** - * Writes a unicode string complete with header and character data. This includes: - *
    - *
  • ushort length
  • - *
  • byte optionFlags
  • - *
  • ushort numberOfRichTextRuns (optional)
  • - *
  • ushort extendedDataSize (optional)
  • - *
  • encoded character data (in "ISO-8859-1" or "UTF-16LE" encoding)
  • - *
- * - * The following bits of the 'optionFlags' byte will be set as appropriate: - * - * - * - * - * - * - *
bits of the 'optionFlags'
MaskDescription
0x01is16bitEncoded
0x04hasExtendedData
0x08isRichText
- * Notes: - *
    - *
  • The value of the 'is16bitEncoded' flag is determined by the actual character data - * of {@code text}
  • - *
  • The string header fields are never separated (by a {@link ContinueRecord}) from the - * first chunk of character data (i.e. the first character is always encoded in the same - * record as the string header).
  • - *
- */ - public void writeString(String text, int numberOfRichTextRuns, int extendedDataSize) { - boolean is16bitEncoded = StringUtil.hasMultibyte(text); - // calculate total size of the header and first encoded char - int keepTogetherSize = 2 + 1 + 1; // ushort len, byte optionFlags, at least one character byte - int optionFlags = 0x00; - if (is16bitEncoded) { - optionFlags |= 0x01; - keepTogetherSize += 1; // one extra byte for first char - } - if (numberOfRichTextRuns > 0) { - optionFlags |= 0x08; - keepTogetherSize += 2; - } - if (extendedDataSize > 0) { - optionFlags |= 0x04; - keepTogetherSize += 4; - } - writeContinueIfRequired(keepTogetherSize); - writeShort(text.length()); - writeByte(optionFlags); - if (numberOfRichTextRuns > 0) { - writeShort(numberOfRichTextRuns); - } - if (extendedDataSize > 0) { - writeInt(extendedDataSize); - } - writeCharacterData(text, is16bitEncoded); - } + /** + * Writes the 'optionFlags' byte and encoded character data of a unicode string. This includes: + *
    + *
  • byte optionFlags
  • + *
  • encoded character data (in "ISO-8859-1" or "UTF-16LE" encoding)
  • + *
+ * + * Notes: + *
    + *
  • The value of the 'is16bitEncoded' flag is determined by the actual character data + * of {@code text}
  • + *
  • The string options flag is never separated (by a {@link ContinueRecord}) from the + * first chunk of character data it refers to.
  • + *
  • The 'ushort length' field is assumed to have been explicitly written earlier. Hence, + * there may be an intervening {@link ContinueRecord}
  • + *
+ */ + public void writeStringData(String text) { + boolean is16bitEncoded = StringUtil.hasMultibyte(text); + // calculate total size of the header and first encoded char + int keepTogetherSize = 1 + 1; // ushort len, at least one character byte + int optionFlags = 0x00; + if (is16bitEncoded) { + optionFlags |= 0x01; + keepTogetherSize += 1; // one extra byte for first char + } + writeContinueIfRequired(keepTogetherSize); + writeByte(optionFlags); + writeCharacterData(text, is16bitEncoded); + } + /** + * Writes a unicode string complete with header and character data. This includes: + *
    + *
  • ushort length
  • + *
  • byte optionFlags
  • + *
  • ushort numberOfRichTextRuns (optional)
  • + *
  • ushort extendedDataSize (optional)
  • + *
  • encoded character data (in "ISO-8859-1" or "UTF-16LE" encoding)
  • + *
+ * + * The following bits of the 'optionFlags' byte will be set as appropriate: + * + * + * + * + * + * + *
bits of the 'optionFlags'
MaskDescription
0x01is16bitEncoded
0x04hasExtendedData
0x08isRichText
+ * Notes: + *
    + *
  • The value of the 'is16bitEncoded' flag is determined by the actual character data + * of {@code text}
  • + *
  • The string header fields are never separated (by a {@link ContinueRecord}) from the + * first chunk of character data (i.e. the first character is always encoded in the same + * record as the string header).
  • + *
+ */ + public void writeString(String text, int numberOfRichTextRuns, int extendedDataSize) { + boolean is16bitEncoded = StringUtil.hasMultibyte(text); + // calculate total size of the header and first encoded char + int keepTogetherSize = 2 + 1 + 1; // ushort len, byte optionFlags, at least one character byte + int optionFlags = 0x00; + if (is16bitEncoded) { + optionFlags |= 0x01; + keepTogetherSize += 1; // one extra byte for first char + } + if (numberOfRichTextRuns > 0) { + optionFlags |= 0x08; + keepTogetherSize += 2; + } + if (extendedDataSize > 0) { + optionFlags |= 0x04; + keepTogetherSize += 4; + } + writeContinueIfRequired(keepTogetherSize); + writeShort(text.length()); + writeByte(optionFlags); + if (numberOfRichTextRuns > 0) { + writeShort(numberOfRichTextRuns); + } + if (extendedDataSize > 0) { + writeInt(extendedDataSize); + } + writeCharacterData(text, is16bitEncoded); + } - private void writeCharacterData(String text, boolean is16bitEncoded) { - int nChars = text.length(); - int i=0; - if (is16bitEncoded) { - while(true) { - int nWritableChars = Math.min(nChars-i, _ulrOutput.getAvailableSpace() / 2); - for ( ; nWritableChars > 0; nWritableChars--) { - _ulrOutput.writeShort(text.charAt(i++)); - } - if (i >= nChars) { - break; - } - writeContinue(); - writeByte(0x01); - } - } else { - while(true) { - int nWritableChars = Math.min(nChars-i, _ulrOutput.getAvailableSpace()); - for ( ; nWritableChars > 0; nWritableChars--) { - _ulrOutput.writeByte(text.charAt(i++)); - } - if (i >= nChars) { - break; - } - writeContinue(); - writeByte(0x00); - } - } - } + private void writeCharacterData(String text, boolean is16bitEncoded) { + int nChars = text.length(); + int i=0; + if (is16bitEncoded) { + while(true) { + int nWritableChars = Math.min(nChars-i, _ulrOutput.getAvailableSpace() / 2); + for ( ; nWritableChars > 0; nWritableChars--) { + _ulrOutput.writeShort(text.charAt(i++)); + } + if (i >= nChars) { + break; + } + writeContinue(); + writeByte(0x01); + } + } else { + while(true) { + int nWritableChars = Math.min(nChars-i, _ulrOutput.getAvailableSpace()); + for ( ; nWritableChars > 0; nWritableChars--) { + _ulrOutput.writeByte(text.charAt(i++)); + } + if (i >= nChars) { + break; + } + writeContinue(); + writeByte(0x00); + } + } + } - @Override - public void write(byte[] b) { - writeContinueIfRequired(b.length); - _ulrOutput.write(b); - } + @Override + public void write(byte[] b) { + writeContinueIfRequired(b.length); + _ulrOutput.write(b); + } - @Override - public void write(byte[] b, int offset, int len) { + @Override + public void write(byte[] b, int offset, int len) { int i=0; while(true) { @@ -219,70 +219,70 @@ public final class ContinuableRecordOutput implements LittleEndianOutput { } writeContinue(); } - } + } - @Override - public void writeByte(int v) { - writeContinueIfRequired(1); - _ulrOutput.writeByte(v); - } - @Override - public void writeDouble(double v) { - writeContinueIfRequired(8); - _ulrOutput.writeDouble(v); - } - @Override - public void writeInt(int v) { - writeContinueIfRequired(4); - _ulrOutput.writeInt(v); - } - @Override - public void writeLong(long v) { - writeContinueIfRequired(8); - _ulrOutput.writeLong(v); - } - @Override - public void writeShort(int v) { - writeContinueIfRequired(2); - _ulrOutput.writeShort(v); - } + @Override + public void writeByte(int v) { + writeContinueIfRequired(1); + _ulrOutput.writeByte(v); + } + @Override + public void writeDouble(double v) { + writeContinueIfRequired(8); + _ulrOutput.writeDouble(v); + } + @Override + public void writeInt(int v) { + writeContinueIfRequired(4); + _ulrOutput.writeInt(v); + } + @Override + public void writeLong(long v) { + writeContinueIfRequired(8); + _ulrOutput.writeLong(v); + } + @Override + public void writeShort(int v) { + writeContinueIfRequired(2); + _ulrOutput.writeShort(v); + } - /** - * Allows optimised usage of {@link ContinuableRecordOutput} for sizing purposes only. - */ - private static final LittleEndianOutput NOPOutput = new DelayableLittleEndianOutput() { + /** + * Allows optimised usage of {@link ContinuableRecordOutput} for sizing purposes only. + */ + private static final LittleEndianOutput NOPOutput = new DelayableLittleEndianOutput() { - @Override - public LittleEndianOutput createDelayedOutput(int size) { - return this; - } - @Override - public void write(byte[] b) { - // does nothing - } - @Override - public void write(byte[] b, int offset, int len) { - // does nothing - } - @Override - public void writeByte(int v) { - // does nothing - } - @Override - public void writeDouble(double v) { - // does nothing - } - @Override - public void writeInt(int v) { - // does nothing - } - @Override - public void writeLong(long v) { - // does nothing - } - @Override - public void writeShort(int v) { - // does nothing - } - }; + @Override + public LittleEndianOutput createDelayedOutput(int size) { + return this; + } + @Override + public void write(byte[] b) { + // does nothing + } + @Override + public void write(byte[] b, int offset, int len) { + // does nothing + } + @Override + public void writeByte(int v) { + // does nothing + } + @Override + public void writeDouble(double v) { + // does nothing + } + @Override + public void writeInt(int v) { + // does nothing + } + @Override + public void writeLong(long v) { + // does nothing + } + @Override + public void writeShort(int v) { + // does nothing + } + }; } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/cont/UnknownLengthRecordOutput.java b/poi/src/main/java/org/apache/poi/hssf/record/cont/UnknownLengthRecordOutput.java index 947cbcd595..7df897f5d5 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/cont/UnknownLengthRecordOutput.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/cont/UnknownLengthRecordOutput.java @@ -27,86 +27,86 @@ import org.apache.poi.util.LittleEndianOutput; * class updates the 'ushort size' with its final value. */ final class UnknownLengthRecordOutput implements LittleEndianOutput { - private static final int MAX_DATA_SIZE = RecordInputStream.MAX_RECORD_DATA_SIZE; + private static final int MAX_DATA_SIZE = RecordInputStream.MAX_RECORD_DATA_SIZE; - private final LittleEndianOutput _originalOut; - /** for writing the 'ushort size' field once its value is known */ - private final LittleEndianOutput _dataSizeOutput; - private final byte[] _byteBuffer; - private LittleEndianOutput _out; - private int _size; + private final LittleEndianOutput _originalOut; + /** for writing the 'ushort size' field once its value is known */ + private final LittleEndianOutput _dataSizeOutput; + private final byte[] _byteBuffer; + private LittleEndianOutput _out; + private int _size; - public UnknownLengthRecordOutput(LittleEndianOutput out, int sid) { - _originalOut = out; - out.writeShort(sid); - if (out instanceof DelayableLittleEndianOutput) { - // optimisation - DelayableLittleEndianOutput dleo = (DelayableLittleEndianOutput) out; - _dataSizeOutput = dleo.createDelayedOutput(2); - _byteBuffer = null; - _out = out; - } else { - // otherwise temporarily write all subsequent data to a buffer - _dataSizeOutput = out; - _byteBuffer = new byte[RecordInputStream.MAX_RECORD_DATA_SIZE]; - _out = new LittleEndianByteArrayOutputStream(_byteBuffer, 0); - } - } - /** - * includes 4 byte header - */ - public int getTotalSize() { - return 4 + _size; - } - public int getAvailableSpace() { - if (_out == null) { - throw new IllegalStateException("Record already terminated"); - } - return MAX_DATA_SIZE - _size; - } - /** - * Finishes writing the current record and updates 'ushort size' field.
- * After this method is called, only {@link #getTotalSize()} may be called. - */ - public void terminate() { - if (_out == null) { - throw new IllegalStateException("Record already terminated"); - } - _dataSizeOutput.writeShort(_size); - if (_byteBuffer != null) { - _originalOut.write(_byteBuffer, 0, _size); - _out = null; - return; - } - _out = null; - } + public UnknownLengthRecordOutput(LittleEndianOutput out, int sid) { + _originalOut = out; + out.writeShort(sid); + if (out instanceof DelayableLittleEndianOutput) { + // optimisation + DelayableLittleEndianOutput dleo = (DelayableLittleEndianOutput) out; + _dataSizeOutput = dleo.createDelayedOutput(2); + _byteBuffer = null; + _out = out; + } else { + // otherwise temporarily write all subsequent data to a buffer + _dataSizeOutput = out; + _byteBuffer = new byte[RecordInputStream.MAX_RECORD_DATA_SIZE]; + _out = new LittleEndianByteArrayOutputStream(_byteBuffer, 0); + } + } + /** + * includes 4 byte header + */ + public int getTotalSize() { + return 4 + _size; + } + public int getAvailableSpace() { + if (_out == null) { + throw new IllegalStateException("Record already terminated"); + } + return MAX_DATA_SIZE - _size; + } + /** + * Finishes writing the current record and updates 'ushort size' field.
+ * After this method is called, only {@link #getTotalSize()} may be called. + */ + public void terminate() { + if (_out == null) { + throw new IllegalStateException("Record already terminated"); + } + _dataSizeOutput.writeShort(_size); + if (_byteBuffer != null) { + _originalOut.write(_byteBuffer, 0, _size); + _out = null; + return; + } + _out = null; + } - public void write(byte[] b) { - _out.write(b); - _size += b.length; - } - public void write(byte[] b, int offset, int len) { - _out.write(b, offset, len); - _size += len; - } - public void writeByte(int v) { - _out.writeByte(v); - _size += 1; - } - public void writeDouble(double v) { - _out.writeDouble(v); - _size += 8; - } - public void writeInt(int v) { - _out.writeInt(v); - _size += 4; - } - public void writeLong(long v) { - _out.writeLong(v); - _size += 8; - } - public void writeShort(int v) { - _out.writeShort(v); - _size += 2; - } + public void write(byte[] b) { + _out.write(b); + _size += b.length; + } + public void write(byte[] b, int offset, int len) { + _out.write(b, offset, len); + _size += len; + } + public void writeByte(int v) { + _out.writeByte(v); + _size += 1; + } + public void writeDouble(double v) { + _out.writeDouble(v); + _size += 8; + } + public void writeInt(int v) { + _out.writeInt(v); + _size += 4; + } + public void writeLong(long v) { + _out.writeLong(v); + _size += 8; + } + public void writeShort(int v) { + _out.writeShort(v); + _size += 2; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/crypto/Biff8DecryptingStream.java b/poi/src/main/java/org/apache/poi/hssf/record/crypto/Biff8DecryptingStream.java index e04870b943..36776807f2 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/crypto/Biff8DecryptingStream.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/crypto/Biff8DecryptingStream.java @@ -44,16 +44,16 @@ public final class Biff8DecryptingStream implements BiffHeaderInput, LittleEndia private final byte[] buffer = new byte[LittleEndianConsts.LONG_SIZE]; private boolean shouldSkipEncryptionOnCurrentRecord; - public Biff8DecryptingStream(InputStream in, int initialOffset, EncryptionInfo info) throws RecordFormatException { + public Biff8DecryptingStream(InputStream in, int initialOffset, EncryptionInfo info) throws RecordFormatException { try { byte[] initialBuf = IOUtils.safelyAllocate(initialOffset, MAX_RECORD_LENGTH); - InputStream stream; - if (initialOffset == 0) { - stream = in; - } else { - stream = new PushbackInputStream(in, initialOffset); - ((PushbackInputStream)stream).unread(initialBuf); - } + InputStream stream; + if (initialOffset == 0) { + stream = in; + } else { + stream = new PushbackInputStream(in, initialOffset); + ((PushbackInputStream)stream).unread(initialBuf); + } Decryptor dec = info.getDecryptor(); dec.setChunkSize(RC4_REKEYING_INTERVAL); @@ -65,67 +65,67 @@ public final class Biff8DecryptingStream implements BiffHeaderInput, LittleEndia } catch (Exception e) { throw new RecordFormatException(e); } - } + } - @Override + @Override @SuppressForbidden("just delegating") public int available() { - return ccis.available(); - } + return ccis.available(); + } - /** - * Reads an unsigned short value without decrypting - */ - @Override + /** + * Reads an unsigned short value without decrypting + */ + @Override public int readRecordSID() { - readPlain(buffer, 0, LittleEndianConsts.SHORT_SIZE); - int sid = LittleEndian.getUShort(buffer, 0); - shouldSkipEncryptionOnCurrentRecord = isNeverEncryptedRecord(sid); - return sid; - } + readPlain(buffer, 0, LittleEndianConsts.SHORT_SIZE); + int sid = LittleEndian.getUShort(buffer, 0); + shouldSkipEncryptionOnCurrentRecord = isNeverEncryptedRecord(sid); + return sid; + } - /** - * Reads an unsigned short value without decrypting - */ - @Override + /** + * Reads an unsigned short value without decrypting + */ + @Override public int readDataSize() { readPlain(buffer, 0, LittleEndianConsts.SHORT_SIZE); int dataSize = LittleEndian.getUShort(buffer, 0); ccis.setNextRecordSize(dataSize); - return dataSize; - } + return dataSize; + } - @Override + @Override public double readDouble() { - long valueLongBits = readLong(); - double result = Double.longBitsToDouble(valueLongBits); - if (Double.isNaN(result)) { - // (Because Excel typically doesn't write NaN - throw new RuntimeException("Did not expect to read NaN"); - } - return result; - } + long valueLongBits = readLong(); + double result = Double.longBitsToDouble(valueLongBits); + if (Double.isNaN(result)) { + // (Because Excel typically doesn't write NaN + throw new RuntimeException("Did not expect to read NaN"); + } + return result; + } - @Override + @Override public void readFully(byte[] buf) { - readFully(buf, 0, buf.length); - } + readFully(buf, 0, buf.length); + } - @Override + @Override public void readFully(byte[] buf, int off, int len) { if (shouldSkipEncryptionOnCurrentRecord) { readPlain(buf, off, buf.length); } else { ccis.readFully(buf, off, len); } - } + } - @Override + @Override public int readUByte() { - return readByte() & 0xFF; - } + return readByte() & 0xFF; + } - @Override + @Override public byte readByte() { if (shouldSkipEncryptionOnCurrentRecord) { readPlain(buffer, 0, LittleEndianConsts.BYTE_SIZE); @@ -133,14 +133,14 @@ public final class Biff8DecryptingStream implements BiffHeaderInput, LittleEndia } else { return ccis.readByte(); } - } + } - @Override + @Override public int readUShort() { - return readShort() & 0xFFFF; - } + return readShort() & 0xFFFF; + } - @Override + @Override public short readShort() { if (shouldSkipEncryptionOnCurrentRecord) { readPlain(buffer, 0, LittleEndianConsts.SHORT_SIZE); @@ -148,9 +148,9 @@ public final class Biff8DecryptingStream implements BiffHeaderInput, LittleEndia } else { return ccis.readShort(); } - } + } - @Override + @Override public int readInt() { if (shouldSkipEncryptionOnCurrentRecord) { readPlain(buffer, 0, LittleEndianConsts.INT_SIZE); @@ -158,9 +158,9 @@ public final class Biff8DecryptingStream implements BiffHeaderInput, LittleEndia } else { return ccis.readInt(); } - } + } - @Override + @Override public long readLong() { if (shouldSkipEncryptionOnCurrentRecord) { readPlain(buffer, 0, LittleEndianConsts.LONG_SIZE); @@ -168,14 +168,14 @@ public final class Biff8DecryptingStream implements BiffHeaderInput, LittleEndia } else { return ccis.readLong(); } - } + } - /** - * @return the absolute position in the stream - */ - public long getPosition() { - return ccis.getPos(); - } + /** + * @return the absolute position in the stream + */ + public long getPosition() { + return ccis.getPos(); + } /** * TODO: Additionally, the lbPlyPos (position_of_BOF) field of the BoundSheet8 record MUST NOT be encrypted. diff --git a/poi/src/main/java/org/apache/poi/hssf/record/crypto/Biff8EncryptionKey.java b/poi/src/main/java/org/apache/poi/hssf/record/crypto/Biff8EncryptionKey.java index 23cd17a823..a96b80e37b 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/crypto/Biff8EncryptionKey.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/crypto/Biff8EncryptionKey.java @@ -19,31 +19,31 @@ package org.apache.poi.hssf.record.crypto; import org.apache.poi.hssf.usermodel.HSSFWorkbook; public final class Biff8EncryptionKey { - /** - * Stores the BIFF8 encryption/decryption password for the current thread. This has been done - * using a {@link ThreadLocal} in order to avoid further overloading the various public APIs - * (e.g. {@link HSSFWorkbook}) that need this functionality. - */ - private static final ThreadLocal _userPasswordTLS = new ThreadLocal<>(); + /** + * Stores the BIFF8 encryption/decryption password for the current thread. This has been done + * using a {@link ThreadLocal} in order to avoid further overloading the various public APIs + * (e.g. {@link HSSFWorkbook}) that need this functionality. + */ + private static final ThreadLocal _userPasswordTLS = new ThreadLocal<>(); - /** - * Sets the BIFF8 encryption/decryption password for the current thread. - * - * @param password pass null to clear user password (and use default) - */ - public static void setCurrentUserPassword(String password) { - if (password == null) { - _userPasswordTLS.remove(); - } else { - _userPasswordTLS.set(password); - } - } + /** + * Sets the BIFF8 encryption/decryption password for the current thread. + * + * @param password pass null to clear user password (and use default) + */ + public static void setCurrentUserPassword(String password) { + if (password == null) { + _userPasswordTLS.remove(); + } else { + _userPasswordTLS.set(password); + } + } - /** - * @return the BIFF8 encryption/decryption password for the current thread. - * null if it is currently unset. - */ - public static String getCurrentUserPassword() { - return _userPasswordTLS.get(); - } + /** + * @return the BIFF8 encryption/decryption password for the current thread. + * null if it is currently unset. + */ + public static String getCurrentUserPassword() { + return _userPasswordTLS.get(); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/DataItemRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/DataItemRecord.java index 9d77e4b361..cd6d4a1dd5 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/DataItemRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/DataItemRecord.java @@ -31,80 +31,80 @@ import org.apache.poi.util.StringUtil; * SXDI - Data Item (0x00C5) */ public final class DataItemRecord extends StandardRecord { - public static final short sid = 0x00C5; + public static final short sid = 0x00C5; - private int isxvdData; - private int iiftab; - private int df; - private int isxvd; - private int isxvi; - private int ifmt; - private String name; + private int isxvdData; + private int iiftab; + private int df; + private int isxvd; + private int isxvi; + private int ifmt; + private String name; - public DataItemRecord(DataItemRecord other) { - super(other); - isxvdData = other.isxvdData; - iiftab = other.iiftab; - df = other.df; - isxvd = other.isxvd; - isxvi = other.isxvi; - ifmt = other.ifmt; - name = other.name; - } + public DataItemRecord(DataItemRecord other) { + super(other); + isxvdData = other.isxvdData; + iiftab = other.iiftab; + df = other.df; + isxvd = other.isxvd; + isxvi = other.isxvi; + ifmt = other.ifmt; + name = other.name; + } - public DataItemRecord(RecordInputStream in) { - isxvdData = in.readUShort(); - iiftab = in.readUShort(); - df = in.readUShort(); - isxvd = in.readUShort(); - isxvi = in.readUShort(); - ifmt = in.readUShort(); + public DataItemRecord(RecordInputStream in) { + isxvdData = in.readUShort(); + iiftab = in.readUShort(); + df = in.readUShort(); + isxvd = in.readUShort(); + isxvi = in.readUShort(); + ifmt = in.readUShort(); - name = in.readString(); - } + name = in.readString(); + } - @Override - protected void serialize(LittleEndianOutput out) { + @Override + protected void serialize(LittleEndianOutput out) { - out.writeShort(isxvdData); - out.writeShort(iiftab); - out.writeShort(df); - out.writeShort(isxvd); - out.writeShort(isxvi); - out.writeShort(ifmt); + out.writeShort(isxvdData); + out.writeShort(iiftab); + out.writeShort(df); + out.writeShort(isxvd); + out.writeShort(isxvi); + out.writeShort(ifmt); - StringUtil.writeUnicodeString(out, name); - } + StringUtil.writeUnicodeString(out, name); + } - @Override - protected int getDataSize() { - return 2 + 2 + 2 + 2 + 2 + 2 + StringUtil.getEncodedSize(name); - } + @Override + protected int getDataSize() { + return 2 + 2 + 2 + 2 + 2 + 2 + StringUtil.getEncodedSize(name); + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public DataItemRecord copy() { - return new DataItemRecord(this); - } + @Override + public DataItemRecord copy() { + return new DataItemRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.DATA_ITEM; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.DATA_ITEM; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "isxvdData", () -> isxvdData, - "iiftab", () -> iiftab, - "df", () -> df, - "isxvd", () -> isxvd, - "isxvi", () -> isxvi, - "ifmt", () -> ifmt - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "isxvdData", () -> isxvdData, + "iiftab", () -> iiftab, + "df", () -> df, + "isxvd", () -> isxvd, + "isxvi", () -> isxvi, + "ifmt", () -> ifmt + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ExtendedPivotTableViewFieldsRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ExtendedPivotTableViewFieldsRecord.java index ade9c24d88..8839ce6ddb 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ExtendedPivotTableViewFieldsRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ExtendedPivotTableViewFieldsRecord.java @@ -32,115 +32,115 @@ import org.apache.poi.util.StringUtil; * SXVDEX - Extended PivotTable View Fields (0x0100) */ public final class ExtendedPivotTableViewFieldsRecord extends StandardRecord { - public static final short sid = 0x0100; + public static final short sid = 0x0100; - /** the value of the subname length when the {@link #_subtotalName} is not present */ - private static final int STRING_NOT_PRESENT_LEN = 0xFFFF; + /** the value of the subname length when the {@link #_subtotalName} is not present */ + private static final int STRING_NOT_PRESENT_LEN = 0xFFFF; - private int _grbit1; - private int _grbit2; - private int _citmShow; - private int _isxdiSort; - private int _isxdiShow; - private int _reserved1; - private int _reserved2; - /** custom sub-total name */ - private String _subtotalName; + private int _grbit1; + private int _grbit2; + private int _citmShow; + private int _isxdiSort; + private int _isxdiShow; + private int _reserved1; + private int _reserved2; + /** custom sub-total name */ + private String _subtotalName; - public ExtendedPivotTableViewFieldsRecord(ExtendedPivotTableViewFieldsRecord other) { - super(other); - _grbit1 = other._grbit1; - _grbit2 = other._grbit2; - _citmShow = other._citmShow; - _isxdiSort = other._isxdiSort; - _isxdiShow = other._isxdiShow; - _reserved1 = other._reserved1; - _reserved2 = other._reserved2; - _subtotalName = other._subtotalName; - } + public ExtendedPivotTableViewFieldsRecord(ExtendedPivotTableViewFieldsRecord other) { + super(other); + _grbit1 = other._grbit1; + _grbit2 = other._grbit2; + _citmShow = other._citmShow; + _isxdiSort = other._isxdiSort; + _isxdiShow = other._isxdiShow; + _reserved1 = other._reserved1; + _reserved2 = other._reserved2; + _subtotalName = other._subtotalName; + } - public ExtendedPivotTableViewFieldsRecord(RecordInputStream in) { - _grbit1 = in.readInt(); - _grbit2 = in.readUByte(); - _citmShow = in.readUByte(); - _isxdiSort = in.readUShort(); - _isxdiShow = in.readUShort(); - // This record seems to have different valid encodings - switch (in.remaining()) { - case 0: - // as per "Microsoft Excel Developer's Kit" book - // older version of SXVDEX - doesn't seem to have a sub-total name - _reserved1 = 0; - _reserved2 = 0; - _subtotalName = null; - return; - case 10: - // as per "MICROSOFT OFFICE EXCEL 97-2007 BINARY FILE FORMAT SPECIFICATION" pdf - break; - default: - throw new RecordFormatException("Unexpected remaining size (" + in.remaining() + ")"); - } - int cchSubName = in.readUShort(); - _reserved1 = in.readInt(); - _reserved2 = in.readInt(); - if (cchSubName != STRING_NOT_PRESENT_LEN) { - _subtotalName = in.readUnicodeLEString(cchSubName); - } - } + public ExtendedPivotTableViewFieldsRecord(RecordInputStream in) { + _grbit1 = in.readInt(); + _grbit2 = in.readUByte(); + _citmShow = in.readUByte(); + _isxdiSort = in.readUShort(); + _isxdiShow = in.readUShort(); + // This record seems to have different valid encodings + switch (in.remaining()) { + case 0: + // as per "Microsoft Excel Developer's Kit" book + // older version of SXVDEX - doesn't seem to have a sub-total name + _reserved1 = 0; + _reserved2 = 0; + _subtotalName = null; + return; + case 10: + // as per "MICROSOFT OFFICE EXCEL 97-2007 BINARY FILE FORMAT SPECIFICATION" pdf + break; + default: + throw new RecordFormatException("Unexpected remaining size (" + in.remaining() + ")"); + } + int cchSubName = in.readUShort(); + _reserved1 = in.readInt(); + _reserved2 = in.readInt(); + if (cchSubName != STRING_NOT_PRESENT_LEN) { + _subtotalName = in.readUnicodeLEString(cchSubName); + } + } - @Override - protected void serialize(LittleEndianOutput out) { + @Override + protected void serialize(LittleEndianOutput out) { - out.writeInt(_grbit1); - out.writeByte(_grbit2); - out.writeByte(_citmShow); - out.writeShort(_isxdiSort); - out.writeShort(_isxdiShow); + out.writeInt(_grbit1); + out.writeByte(_grbit2); + out.writeByte(_citmShow); + out.writeShort(_isxdiSort); + out.writeShort(_isxdiShow); - if (_subtotalName == null) { - out.writeShort(STRING_NOT_PRESENT_LEN); - } else { - out.writeShort(_subtotalName.length()); - } + if (_subtotalName == null) { + out.writeShort(STRING_NOT_PRESENT_LEN); + } else { + out.writeShort(_subtotalName.length()); + } - out.writeInt(_reserved1); - out.writeInt(_reserved2); - if (_subtotalName != null) { - StringUtil.putUnicodeLE(_subtotalName, out); - } - } + out.writeInt(_reserved1); + out.writeInt(_reserved2); + if (_subtotalName != null) { + StringUtil.putUnicodeLE(_subtotalName, out); + } + } - @Override - protected int getDataSize() { + @Override + protected int getDataSize() { - return 4 + 1 + 1 + 2 + 2 + 2 + 4 + 4 + - (_subtotalName == null ? 0 : (2*_subtotalName.length())); // in unicode - } + return 4 + 1 + 1 + 2 + 2 + 2 + 4 + 4 + + (_subtotalName == null ? 0 : (2*_subtotalName.length())); // in unicode + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public ExtendedPivotTableViewFieldsRecord copy() { - return new ExtendedPivotTableViewFieldsRecord(this); - } + @Override + public ExtendedPivotTableViewFieldsRecord copy() { + return new ExtendedPivotTableViewFieldsRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.EXTENDED_PIVOT_TABLE_VIEW_FIELDS; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.EXTENDED_PIVOT_TABLE_VIEW_FIELDS; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "grbit1", () -> _grbit1, - "grbit2", () -> _grbit2, - "citmShow", () -> _citmShow, - "isxdiSort", () -> _isxdiSort, - "isxdiShow", () -> _isxdiShow, - "subtotalName", () -> _subtotalName - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "grbit1", () -> _grbit1, + "grbit2", () -> _grbit2, + "citmShow", () -> _citmShow, + "isxdiSort", () -> _isxdiSort, + "isxdiShow", () -> _isxdiShow, + "subtotalName", () -> _subtotalName + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/PageItemRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/PageItemRecord.java index c1b0f91be4..60572a4ee9 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/PageItemRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/PageItemRecord.java @@ -33,96 +33,96 @@ import org.apache.poi.util.RecordFormatException; * SXPI - Page Item (0x00B6) */ public final class PageItemRecord extends StandardRecord { - public static final short sid = 0x00B6; + public static final short sid = 0x00B6; - private static final class FieldInfo implements GenericRecord { - public static final int ENCODED_SIZE = 6; - /** Index to the View Item SXVI(0x00B2) record */ - private int _isxvi; - /** Index to the {@link ViewFieldsRecord} SXVD(0x00B1) record */ - private int _isxvd; - /** Object ID for the drop-down arrow */ - private int _idObj; + private static final class FieldInfo implements GenericRecord { + public static final int ENCODED_SIZE = 6; + /** Index to the View Item SXVI(0x00B2) record */ + private int _isxvi; + /** Index to the {@link ViewFieldsRecord} SXVD(0x00B1) record */ + private int _isxvd; + /** Object ID for the drop-down arrow */ + private int _idObj; - public FieldInfo(FieldInfo other) { - _isxvi = other._isxvi; - _isxvd = other._isxvd; - _idObj = other._idObj; - } + public FieldInfo(FieldInfo other) { + _isxvi = other._isxvi; + _isxvd = other._isxvd; + _idObj = other._idObj; + } - public FieldInfo(RecordInputStream in) { - _isxvi = in.readShort(); - _isxvd = in.readShort(); - _idObj = in.readShort(); - } + public FieldInfo(RecordInputStream in) { + _isxvi = in.readShort(); + _isxvd = in.readShort(); + _idObj = in.readShort(); + } - private void serialize(LittleEndianOutput out) { - out.writeShort(_isxvi); - out.writeShort(_isxvd); - out.writeShort(_idObj); - } + private void serialize(LittleEndianOutput out) { + out.writeShort(_isxvi); + out.writeShort(_isxvd); + out.writeShort(_idObj); + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "isxvi", () -> _isxvi, - "isxvd", () -> _isxvd, - "idObj", () -> _idObj - ); - } - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "isxvi", () -> _isxvi, + "isxvd", () -> _isxvd, + "idObj", () -> _idObj + ); + } + } - private final FieldInfo[] _fieldInfos; + private final FieldInfo[] _fieldInfos; - public PageItemRecord(PageItemRecord other) { - super(other); - _fieldInfos = Stream.of(other._fieldInfos).map(FieldInfo::new).toArray(FieldInfo[]::new); - } + public PageItemRecord(PageItemRecord other) { + super(other); + _fieldInfos = Stream.of(other._fieldInfos).map(FieldInfo::new).toArray(FieldInfo[]::new); + } - public PageItemRecord(RecordInputStream in) { - int dataSize = in.remaining(); - if (dataSize % FieldInfo.ENCODED_SIZE != 0) { - throw new RecordFormatException("Bad data size " + dataSize); - } + public PageItemRecord(RecordInputStream in) { + int dataSize = in.remaining(); + if (dataSize % FieldInfo.ENCODED_SIZE != 0) { + throw new RecordFormatException("Bad data size " + dataSize); + } - int nItems = dataSize / FieldInfo.ENCODED_SIZE; + int nItems = dataSize / FieldInfo.ENCODED_SIZE; - FieldInfo[] fis = new FieldInfo[nItems]; - for (int i = 0; i < fis.length; i++) { - fis[i] = new FieldInfo(in); - } - _fieldInfos = fis; - } + FieldInfo[] fis = new FieldInfo[nItems]; + for (int i = 0; i < fis.length; i++) { + fis[i] = new FieldInfo(in); + } + _fieldInfos = fis; + } - @Override - protected void serialize(LittleEndianOutput out) { - for (FieldInfo fieldInfo : _fieldInfos) { - fieldInfo.serialize(out); - } - } + @Override + protected void serialize(LittleEndianOutput out) { + for (FieldInfo fieldInfo : _fieldInfos) { + fieldInfo.serialize(out); + } + } - @Override - protected int getDataSize() { - return _fieldInfos.length * FieldInfo.ENCODED_SIZE; - } + @Override + protected int getDataSize() { + return _fieldInfos.length * FieldInfo.ENCODED_SIZE; + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public PageItemRecord copy() { - return new PageItemRecord(this); - } + @Override + public PageItemRecord copy() { + return new PageItemRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.PAGE_ITEM; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.PAGE_ITEM; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties("fieldInfos", () -> _fieldInfos); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties("fieldInfos", () -> _fieldInfos); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/StreamIDRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/StreamIDRecord.java index 11beef32b9..a7ab145dbc 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/StreamIDRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/StreamIDRecord.java @@ -30,46 +30,46 @@ import org.apache.poi.util.LittleEndianOutput; * SXIDSTM - Stream ID (0x00D5) */ public final class StreamIDRecord extends StandardRecord { - public static final short sid = 0x00D5; + public static final short sid = 0x00D5; - private int idstm; + private int idstm; - public StreamIDRecord(StreamIDRecord other) { - super(other); - idstm = other.idstm; - } + public StreamIDRecord(StreamIDRecord other) { + super(other); + idstm = other.idstm; + } - public StreamIDRecord(RecordInputStream in) { - idstm = in.readShort(); - } + public StreamIDRecord(RecordInputStream in) { + idstm = in.readShort(); + } - @Override - protected void serialize(LittleEndianOutput out) { - out.writeShort(idstm); - } + @Override + protected void serialize(LittleEndianOutput out) { + out.writeShort(idstm); + } - @Override - protected int getDataSize() { - return 2; - } + @Override + protected int getDataSize() { + return 2; + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public StreamIDRecord copy() { - return new StreamIDRecord(this); - } + @Override + public StreamIDRecord copy() { + return new StreamIDRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.STREAM_ID; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.STREAM_ID; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties("idstm", () -> idstm); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties("idstm", () -> idstm); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewDefinitionRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewDefinitionRecord.java index 190b5e4d39..38cfcf850a 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewDefinitionRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewDefinitionRecord.java @@ -32,168 +32,168 @@ import org.apache.poi.util.StringUtil; * SXVIEW - View Definition (0x00B0)
*/ public final class ViewDefinitionRecord extends StandardRecord { - public static final short sid = 0x00B0; + public static final short sid = 0x00B0; - private int rwFirst; - private int rwLast; - private int colFirst; - private int colLast; - private int rwFirstHead; - private int rwFirstData; - private int colFirstData; - private int iCache; - private int reserved; + private int rwFirst; + private int rwLast; + private int colFirst; + private int colLast; + private int rwFirstHead; + private int rwFirstData; + private int colFirstData; + private int iCache; + private int reserved; - private int sxaxis4Data; - private int ipos4Data; - private int cDim; + private int sxaxis4Data; + private int ipos4Data; + private int cDim; - private int cDimRw; + private int cDimRw; - private int cDimCol; - private int cDimPg; + private int cDimCol; + private int cDimPg; - private int cDimData; - private int cRw; - private int cCol; - private int grbit; - private int itblAutoFmt; + private int cDimData; + private int cRw; + private int cCol; + private int grbit; + private int itblAutoFmt; - private String dataField; - private String name; + private String dataField; + private String name; - public ViewDefinitionRecord(ViewDefinitionRecord other) { - super(other); - rwFirst = other.rwFirst; - rwLast = other.rwLast; - colFirst = other.colFirst; - colLast = other.colLast; - rwFirstHead = other.rwFirstHead; - rwFirstData = other.rwFirstData; - colFirstData = other.colFirstData; - iCache = other.iCache; - reserved = other.reserved; - sxaxis4Data = other.sxaxis4Data; - ipos4Data = other.ipos4Data; - cDim = other.cDim; - cDimRw = other.cDimRw; - cDimCol = other.cDimCol; - cDimPg = other.cDimPg; - cDimData = other.cDimData; - cRw = other.cRw; - cCol = other.cCol; - grbit = other.grbit; - itblAutoFmt = other.itblAutoFmt; - name = other.name; - dataField = other.dataField; - } + public ViewDefinitionRecord(ViewDefinitionRecord other) { + super(other); + rwFirst = other.rwFirst; + rwLast = other.rwLast; + colFirst = other.colFirst; + colLast = other.colLast; + rwFirstHead = other.rwFirstHead; + rwFirstData = other.rwFirstData; + colFirstData = other.colFirstData; + iCache = other.iCache; + reserved = other.reserved; + sxaxis4Data = other.sxaxis4Data; + ipos4Data = other.ipos4Data; + cDim = other.cDim; + cDimRw = other.cDimRw; + cDimCol = other.cDimCol; + cDimPg = other.cDimPg; + cDimData = other.cDimData; + cRw = other.cRw; + cCol = other.cCol; + grbit = other.grbit; + itblAutoFmt = other.itblAutoFmt; + name = other.name; + dataField = other.dataField; + } - public ViewDefinitionRecord(RecordInputStream in) { - rwFirst = in.readUShort(); - rwLast = in.readUShort(); - colFirst = in.readUShort(); - colLast = in.readUShort(); - rwFirstHead = in.readUShort(); - rwFirstData = in.readUShort(); - colFirstData = in.readUShort(); - iCache = in.readUShort(); - reserved = in.readUShort(); - sxaxis4Data = in.readUShort(); - ipos4Data = in.readUShort(); - cDim = in.readUShort(); - cDimRw = in.readUShort(); - cDimCol = in.readUShort(); - cDimPg = in.readUShort(); - cDimData = in.readUShort(); - cRw = in.readUShort(); - cCol = in.readUShort(); - grbit = in.readUShort(); - itblAutoFmt = in.readUShort(); - int cchName = in.readUShort(); - int cchData = in.readUShort(); + public ViewDefinitionRecord(RecordInputStream in) { + rwFirst = in.readUShort(); + rwLast = in.readUShort(); + colFirst = in.readUShort(); + colLast = in.readUShort(); + rwFirstHead = in.readUShort(); + rwFirstData = in.readUShort(); + colFirstData = in.readUShort(); + iCache = in.readUShort(); + reserved = in.readUShort(); + sxaxis4Data = in.readUShort(); + ipos4Data = in.readUShort(); + cDim = in.readUShort(); + cDimRw = in.readUShort(); + cDimCol = in.readUShort(); + cDimPg = in.readUShort(); + cDimData = in.readUShort(); + cRw = in.readUShort(); + cCol = in.readUShort(); + grbit = in.readUShort(); + itblAutoFmt = in.readUShort(); + int cchName = in.readUShort(); + int cchData = in.readUShort(); - name = StringUtil.readUnicodeString(in, cchName); - dataField = StringUtil.readUnicodeString(in, cchData); - } + name = StringUtil.readUnicodeString(in, cchName); + dataField = StringUtil.readUnicodeString(in, cchData); + } - @Override - protected void serialize(LittleEndianOutput out) { - out.writeShort(rwFirst); - out.writeShort(rwLast); - out.writeShort(colFirst); - out.writeShort(colLast); - out.writeShort(rwFirstHead); - out.writeShort(rwFirstData); - out.writeShort(colFirstData); - out.writeShort(iCache); - out.writeShort(reserved); - out.writeShort(sxaxis4Data); - out.writeShort(ipos4Data); - out.writeShort(cDim); - out.writeShort(cDimRw); - out.writeShort(cDimCol); - out.writeShort(cDimPg); - out.writeShort(cDimData); - out.writeShort(cRw); - out.writeShort(cCol); - out.writeShort(grbit); - out.writeShort(itblAutoFmt); - out.writeShort(name.length()); - out.writeShort(dataField.length()); + @Override + protected void serialize(LittleEndianOutput out) { + out.writeShort(rwFirst); + out.writeShort(rwLast); + out.writeShort(colFirst); + out.writeShort(colLast); + out.writeShort(rwFirstHead); + out.writeShort(rwFirstData); + out.writeShort(colFirstData); + out.writeShort(iCache); + out.writeShort(reserved); + out.writeShort(sxaxis4Data); + out.writeShort(ipos4Data); + out.writeShort(cDim); + out.writeShort(cDimRw); + out.writeShort(cDimCol); + out.writeShort(cDimPg); + out.writeShort(cDimData); + out.writeShort(cRw); + out.writeShort(cCol); + out.writeShort(grbit); + out.writeShort(itblAutoFmt); + out.writeShort(name.length()); + out.writeShort(dataField.length()); - StringUtil.writeUnicodeStringFlagAndData(out, name); - StringUtil.writeUnicodeStringFlagAndData(out, dataField); - } + StringUtil.writeUnicodeStringFlagAndData(out, name); + StringUtil.writeUnicodeStringFlagAndData(out, dataField); + } - @Override - protected int getDataSize() { - return 40 + // 20 short fields (rwFirst ... itblAutoFmt) - StringUtil.getEncodedSize(name) + StringUtil.getEncodedSize(dataField) ; - } + @Override + protected int getDataSize() { + return 40 + // 20 short fields (rwFirst ... itblAutoFmt) + StringUtil.getEncodedSize(name) + StringUtil.getEncodedSize(dataField) ; + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public ViewDefinitionRecord copy() { - return new ViewDefinitionRecord(this); - } + @Override + public ViewDefinitionRecord copy() { + return new ViewDefinitionRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.VIEW_DEFINITION; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.VIEW_DEFINITION; + } - @Override - public Map> getGenericProperties() { - final Map> m = new LinkedHashMap<>(); + @Override + public Map> getGenericProperties() { + final Map> m = new LinkedHashMap<>(); - m.put("rwFirst", () -> rwFirst); - m.put("rwLast", () -> rwLast); - m.put("colFirst", () -> colFirst); - m.put("colLast", () -> colLast); - m.put("rwFirstHead", () -> rwFirstHead); - m.put("rwFirstData", () -> rwFirstData); - m.put("colFirstData", () -> colFirstData); - m.put("iCache", () -> iCache); - m.put("reserved", () -> reserved); - m.put("sxaxis4Data", () -> sxaxis4Data); - m.put("ipos4Data", () -> ipos4Data); - m.put("cDim", () -> cDim); - m.put("cDimRw", () -> cDimRw); - m.put("cDimCol", () -> cDimCol); - m.put("cDimPg", () -> cDimPg); - m.put("cDimData", () -> cDimData); - m.put("cRw", () -> cRw); - m.put("cCol", () -> cCol); - m.put("grbit", () -> grbit); - m.put("itblAutoFmt", () -> itblAutoFmt); - m.put("name", () -> name); - m.put("dataField", () -> dataField); + m.put("rwFirst", () -> rwFirst); + m.put("rwLast", () -> rwLast); + m.put("colFirst", () -> colFirst); + m.put("colLast", () -> colLast); + m.put("rwFirstHead", () -> rwFirstHead); + m.put("rwFirstData", () -> rwFirstData); + m.put("colFirstData", () -> colFirstData); + m.put("iCache", () -> iCache); + m.put("reserved", () -> reserved); + m.put("sxaxis4Data", () -> sxaxis4Data); + m.put("ipos4Data", () -> ipos4Data); + m.put("cDim", () -> cDim); + m.put("cDimRw", () -> cDimRw); + m.put("cDimCol", () -> cDimCol); + m.put("cDimPg", () -> cDimPg); + m.put("cDimData", () -> cDimData); + m.put("cRw", () -> cRw); + m.put("cCol", () -> cCol); + m.put("grbit", () -> grbit); + m.put("itblAutoFmt", () -> itblAutoFmt); + m.put("name", () -> name); + m.put("dataField", () -> dataField); - return Collections.unmodifiableMap(m); - } + return Collections.unmodifiableMap(m); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewFieldsRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewFieldsRecord.java index 2f5a6da67a..0d0543e690 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewFieldsRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewFieldsRecord.java @@ -31,109 +31,109 @@ import org.apache.poi.util.StringUtil; * SXVD - View Fields (0x00B1) */ public final class ViewFieldsRecord extends StandardRecord { - public static final short sid = 0x00B1; + public static final short sid = 0x00B1; - /** the value of the {@code cchName} field when the {@link #_name} is not present */ - private static final int STRING_NOT_PRESENT_LEN = 0xFFFF; - /** 5 shorts */ - private static final int BASE_SIZE = 10; + /** the value of the {@code cchName} field when the {@link #_name} is not present */ + private static final int STRING_NOT_PRESENT_LEN = 0xFFFF; + /** 5 shorts */ + private static final int BASE_SIZE = 10; - private final int _sxaxis; - private final int _cSub; - private final int _grbitSub; - private final int _cItm; + private final int _sxaxis; + private final int _cSub; + private final int _grbitSub; + private final int _cItm; - private String _name; + private String _name; - /** - * values for the {@link ViewFieldsRecord#_sxaxis} field - */ - private enum Axis { - NO_AXIS(0), - ROW(1), - COLUMN(2), - PAGE(4), - DATA(8); - final int id; - Axis(int id) { - this.id = id; - } - } + /** + * values for the {@link ViewFieldsRecord#_sxaxis} field + */ + private enum Axis { + NO_AXIS(0), + ROW(1), + COLUMN(2), + PAGE(4), + DATA(8); + final int id; + Axis(int id) { + this.id = id; + } + } - public ViewFieldsRecord(ViewFieldsRecord other) { - super(other); - _sxaxis = other._sxaxis; - _cSub = other._cSub; - _grbitSub = other._grbitSub; - _cItm = other._cItm; - _name = other._name; - } + public ViewFieldsRecord(ViewFieldsRecord other) { + super(other); + _sxaxis = other._sxaxis; + _cSub = other._cSub; + _grbitSub = other._grbitSub; + _cItm = other._cItm; + _name = other._name; + } - public ViewFieldsRecord(RecordInputStream in) { - _sxaxis = in.readShort(); - _cSub = in.readShort(); - _grbitSub = in.readShort(); - _cItm = in.readShort(); + public ViewFieldsRecord(RecordInputStream in) { + _sxaxis = in.readShort(); + _cSub = in.readShort(); + _grbitSub = in.readShort(); + _cItm = in.readShort(); - int cchName = in.readUShort(); - if (cchName != STRING_NOT_PRESENT_LEN) { - int flag = in.readByte(); - if ((flag & 0x01) != 0) { - _name = in.readUnicodeLEString(cchName); - } else { - _name = in.readCompressedUnicode(cchName); - } - } - } + int cchName = in.readUShort(); + if (cchName != STRING_NOT_PRESENT_LEN) { + int flag = in.readByte(); + if ((flag & 0x01) != 0) { + _name = in.readUnicodeLEString(cchName); + } else { + _name = in.readCompressedUnicode(cchName); + } + } + } - @Override - protected void serialize(LittleEndianOutput out) { + @Override + protected void serialize(LittleEndianOutput out) { - out.writeShort(_sxaxis); - out.writeShort(_cSub); - out.writeShort(_grbitSub); - out.writeShort(_cItm); + out.writeShort(_sxaxis); + out.writeShort(_cSub); + out.writeShort(_grbitSub); + out.writeShort(_cItm); - if (_name != null) { - StringUtil.writeUnicodeString(out, _name); - } else { - out.writeShort(STRING_NOT_PRESENT_LEN); - } - } + if (_name != null) { + StringUtil.writeUnicodeString(out, _name); + } else { + out.writeShort(STRING_NOT_PRESENT_LEN); + } + } - @Override - protected int getDataSize() { - if (_name == null) { - return BASE_SIZE; - } - return BASE_SIZE - + 1 // unicode flag - + _name.length() * (StringUtil.hasMultibyte(_name) ? 2 : 1); - } + @Override + protected int getDataSize() { + if (_name == null) { + return BASE_SIZE; + } + return BASE_SIZE + + 1 // unicode flag + + _name.length() * (StringUtil.hasMultibyte(_name) ? 2 : 1); + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public ViewFieldsRecord copy() { - return new ViewFieldsRecord(this); - } + @Override + public ViewFieldsRecord copy() { + return new ViewFieldsRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.VIEW_FIELDS; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.VIEW_FIELDS; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "sxaxis", () -> _sxaxis, - "cSub", () -> _cSub, - "grbitSub", () -> _grbitSub, - "cItm", () -> _cItm, - "name", () -> _name - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "sxaxis", () -> _sxaxis, + "cSub", () -> _cSub, + "grbitSub", () -> _grbitSub, + "cItm", () -> _cItm, + "name", () -> _name + ); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewSourceRecord.java b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewSourceRecord.java index 20aa600aea..3623f257c0 100644 --- a/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewSourceRecord.java +++ b/poi/src/main/java/org/apache/poi/hssf/record/pivottable/ViewSourceRecord.java @@ -30,46 +30,46 @@ import org.apache.poi.util.LittleEndianOutput; * SXVS - View Source (0x00E3)
*/ public final class ViewSourceRecord extends StandardRecord { - public static final short sid = 0x00E3; + public static final short sid = 0x00E3; - private int vs; + private int vs; - public ViewSourceRecord(ViewSourceRecord other) { - super(other); - vs = other.vs; - } + public ViewSourceRecord(ViewSourceRecord other) { + super(other); + vs = other.vs; + } - public ViewSourceRecord(RecordInputStream in) { - vs = in.readShort(); - } + public ViewSourceRecord(RecordInputStream in) { + vs = in.readShort(); + } - @Override - protected void serialize(LittleEndianOutput out) { - out.writeShort(vs); - } + @Override + protected void serialize(LittleEndianOutput out) { + out.writeShort(vs); + } - @Override - protected int getDataSize() { - return 2; - } + @Override + protected int getDataSize() { + return 2; + } - @Override - public short getSid() { - return sid; - } + @Override + public short getSid() { + return sid; + } - @Override - public ViewSourceRecord copy() { - return new ViewSourceRecord(this); - } + @Override + public ViewSourceRecord copy() { + return new ViewSourceRecord(this); + } - @Override - public HSSFRecordTypes getGenericRecordType() { - return HSSFRecordTypes.VIEW_SOURCE; - } + @Override + public HSSFRecordTypes getGenericRecordType() { + return HSSFRecordTypes.VIEW_SOURCE; + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties("vs", () -> vs); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties("vs", () -> vs); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/DVConstraint.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/DVConstraint.java index a7fa156dbc..1c53ba2043 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/DVConstraint.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/DVConstraint.java @@ -38,414 +38,414 @@ import org.apache.poi.util.LocaleUtil; * Data Validation Constraint */ public class DVConstraint implements DataValidationConstraint { - /* package */ static final class FormulaPair { + /* package */ static final class FormulaPair { - private final Ptg[] _formula1; - private final Ptg[] _formula2; + private final Ptg[] _formula1; + private final Ptg[] _formula2; - FormulaPair(Ptg[] formula1, Ptg[] formula2) { - _formula1 = (formula1 == null) ? null : formula1.clone(); - _formula2 = (formula2 == null) ? null : formula2.clone(); - } - public Ptg[] getFormula1() { - return _formula1; - } - public Ptg[] getFormula2() { - return _formula2; - } + FormulaPair(Ptg[] formula1, Ptg[] formula2) { + _formula1 = (formula1 == null) ? null : formula1.clone(); + _formula2 = (formula2 == null) ? null : formula2.clone(); + } + public Ptg[] getFormula1() { + return _formula1; + } + public Ptg[] getFormula2() { + return _formula2; + } - } + } - private final int _validationType; - private int _operator; - private String[] _explicitListValues; + private final int _validationType; + private int _operator; + private String[] _explicitListValues; - private String _formula1; - private String _formula2; - private Double _value1; - private Double _value2; + private String _formula1; + private String _formula2; + private Double _value1; + private Double _value2; - private DVConstraint(int validationType, int comparisonOperator, String formulaA, - String formulaB, Double value1, Double value2, String[] explicitListValues) { - _validationType = validationType; - _operator = comparisonOperator; - _formula1 = formulaA; - _formula2 = formulaB; - _value1 = value1; - _value2 = value2; - _explicitListValues = (explicitListValues == null) ? null : explicitListValues.clone(); - } + private DVConstraint(int validationType, int comparisonOperator, String formulaA, + String formulaB, Double value1, Double value2, String[] explicitListValues) { + _validationType = validationType; + _operator = comparisonOperator; + _formula1 = formulaA; + _formula2 = formulaB; + _value1 = value1; + _value2 = value2; + _explicitListValues = (explicitListValues == null) ? null : explicitListValues.clone(); + } - /** - * Creates a list constraint - */ - private DVConstraint(String listFormula, String[] explicitListValues) { - this(ValidationType.LIST, OperatorType.IGNORED, - listFormula, null, null, null, explicitListValues); - } + /** + * Creates a list constraint + */ + private DVConstraint(String listFormula, String[] explicitListValues) { + this(ValidationType.LIST, OperatorType.IGNORED, + listFormula, null, null, null, explicitListValues); + } - /** - * Creates a number based data validation constraint. The text values entered for expr1 and expr2 - * can be either standard Excel formulas or formatted number values. If the expression starts - * with '=' it is parsed as a formula, otherwise it is parsed as a formatted number. - * - * @param validationType one of {@link org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType#ANY}, + /** + * Creates a number based data validation constraint. The text values entered for expr1 and expr2 + * can be either standard Excel formulas or formatted number values. If the expression starts + * with '=' it is parsed as a formula, otherwise it is parsed as a formatted number. + * + * @param validationType one of {@link org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType#ANY}, * {@link org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType#DECIMAL}, * {@link org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType#INTEGER}, * {@link org.apache.poi.ss.usermodel.DataValidationConstraint.ValidationType#TEXT_LENGTH} - * @param comparisonOperator any constant from {@link org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType} enum - * @param expr1 date formula (when first char is '=') or formatted number value - * @param expr2 date formula (when first char is '=') or formatted number value - */ - public static DVConstraint createNumericConstraint(int validationType, int comparisonOperator, - String expr1, String expr2) { - switch (validationType) { - case ValidationType.ANY: - if (expr1 != null || expr2 != null) { - throw new IllegalArgumentException("expr1 and expr2 must be null for validation type 'any'"); - } - break; - case ValidationType.DECIMAL: - case ValidationType.INTEGER: - case ValidationType.TEXT_LENGTH: - if (expr1 == null) { - throw new IllegalArgumentException("expr1 must be supplied"); - } - OperatorType.validateSecondArg(comparisonOperator, expr2); - break; - default: - throw new IllegalArgumentException("Validation Type (" - + validationType + ") not supported with this method"); - } - // formula1 and value1 are mutually exclusive - String formula1 = getFormulaFromTextExpression(expr1); - Double value1 = formula1 == null ? convertNumber(expr1) : null; - // formula2 and value2 are mutually exclusive - String formula2 = getFormulaFromTextExpression(expr2); - Double value2 = formula2 == null ? convertNumber(expr2) : null; - return new DVConstraint(validationType, comparisonOperator, formula1, formula2, value1, value2, null); - } + * @param comparisonOperator any constant from {@link org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType} enum + * @param expr1 date formula (when first char is '=') or formatted number value + * @param expr2 date formula (when first char is '=') or formatted number value + */ + public static DVConstraint createNumericConstraint(int validationType, int comparisonOperator, + String expr1, String expr2) { + switch (validationType) { + case ValidationType.ANY: + if (expr1 != null || expr2 != null) { + throw new IllegalArgumentException("expr1 and expr2 must be null for validation type 'any'"); + } + break; + case ValidationType.DECIMAL: + case ValidationType.INTEGER: + case ValidationType.TEXT_LENGTH: + if (expr1 == null) { + throw new IllegalArgumentException("expr1 must be supplied"); + } + OperatorType.validateSecondArg(comparisonOperator, expr2); + break; + default: + throw new IllegalArgumentException("Validation Type (" + + validationType + ") not supported with this method"); + } + // formula1 and value1 are mutually exclusive + String formula1 = getFormulaFromTextExpression(expr1); + Double value1 = formula1 == null ? convertNumber(expr1) : null; + // formula2 and value2 are mutually exclusive + String formula2 = getFormulaFromTextExpression(expr2); + Double value2 = formula2 == null ? convertNumber(expr2) : null; + return new DVConstraint(validationType, comparisonOperator, formula1, formula2, value1, value2, null); + } - public static DVConstraint createFormulaListConstraint(String listFormula) { - return new DVConstraint(listFormula, null); - } - public static DVConstraint createExplicitListConstraint(String[] explicitListValues) { - return new DVConstraint(null, explicitListValues); - } + public static DVConstraint createFormulaListConstraint(String listFormula) { + return new DVConstraint(listFormula, null); + } + public static DVConstraint createExplicitListConstraint(String[] explicitListValues) { + return new DVConstraint(null, explicitListValues); + } - /** - * Creates a time based data validation constraint. The text values entered for expr1 and expr2 - * can be either standard Excel formulas or formatted time values. If the expression starts - * with '=' it is parsed as a formula, otherwise it is parsed as a formatted time. To parse - * formatted times, two formats are supported: "HH:MM" or "HH:MM:SS". This is contrary to - * Excel which uses the default time format from the OS. - * - * @param comparisonOperator constant from {@link org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType} enum - * @param expr1 date formula (when first char is '=') or formatted time value - * @param expr2 date formula (when first char is '=') or formatted time value - */ - public static DVConstraint createTimeConstraint(int comparisonOperator, String expr1, String expr2) { - if (expr1 == null) { - throw new IllegalArgumentException("expr1 must be supplied"); - } - OperatorType.validateSecondArg(comparisonOperator, expr1); + /** + * Creates a time based data validation constraint. The text values entered for expr1 and expr2 + * can be either standard Excel formulas or formatted time values. If the expression starts + * with '=' it is parsed as a formula, otherwise it is parsed as a formatted time. To parse + * formatted times, two formats are supported: "HH:MM" or "HH:MM:SS". This is contrary to + * Excel which uses the default time format from the OS. + * + * @param comparisonOperator constant from {@link org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType} enum + * @param expr1 date formula (when first char is '=') or formatted time value + * @param expr2 date formula (when first char is '=') or formatted time value + */ + public static DVConstraint createTimeConstraint(int comparisonOperator, String expr1, String expr2) { + if (expr1 == null) { + throw new IllegalArgumentException("expr1 must be supplied"); + } + OperatorType.validateSecondArg(comparisonOperator, expr1); - // formula1 and value1 are mutually exclusive - String formula1 = getFormulaFromTextExpression(expr1); - Double value1 = formula1 == null ? convertTime(expr1) : null; - // formula2 and value2 are mutually exclusive - String formula2 = getFormulaFromTextExpression(expr2); - Double value2 = formula2 == null ? convertTime(expr2) : null; - return new DVConstraint(ValidationType.TIME, comparisonOperator, formula1, formula2, value1, value2, null); - } + // formula1 and value1 are mutually exclusive + String formula1 = getFormulaFromTextExpression(expr1); + Double value1 = formula1 == null ? convertTime(expr1) : null; + // formula2 and value2 are mutually exclusive + String formula2 = getFormulaFromTextExpression(expr2); + Double value2 = formula2 == null ? convertTime(expr2) : null; + return new DVConstraint(ValidationType.TIME, comparisonOperator, formula1, formula2, value1, value2, null); + } - /** - * Creates a date based data validation constraint. The text values entered for expr1 and expr2 - * can be either standard Excel formulas or formatted date values. If the expression starts - * with '=' it is parsed as a formula, otherwise it is parsed as a formatted date (Excel uses - * the same convention). To parse formatted dates, a date format needs to be specified. This - * is contrary to Excel which uses the default short date format from the OS. - * - * @param comparisonOperator constant from {@link org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType} enum - * @param expr1 date formula (when first char is '=') or formatted date value - * @param expr2 date formula (when first char is '=') or formatted date value - * @param dateFormat ignored if both expr1 and expr2 are formulas. Default value is "YYYY/MM/DD" - * otherwise any other valid argument for {@code SimpleDateFormat} can be used - * @see SimpleDateFormat - */ - public static DVConstraint createDateConstraint(int comparisonOperator, String expr1, String expr2, String dateFormat) { - if (expr1 == null) { - throw new IllegalArgumentException("expr1 must be supplied"); - } - OperatorType.validateSecondArg(comparisonOperator, expr2); - SimpleDateFormat df = null; - if (dateFormat != null) { - df = new SimpleDateFormat(dateFormat, LocaleUtil.getUserLocale()); - df.setTimeZone(LocaleUtil.getUserTimeZone()); - } + /** + * Creates a date based data validation constraint. The text values entered for expr1 and expr2 + * can be either standard Excel formulas or formatted date values. If the expression starts + * with '=' it is parsed as a formula, otherwise it is parsed as a formatted date (Excel uses + * the same convention). To parse formatted dates, a date format needs to be specified. This + * is contrary to Excel which uses the default short date format from the OS. + * + * @param comparisonOperator constant from {@link org.apache.poi.ss.usermodel.DataValidationConstraint.OperatorType} enum + * @param expr1 date formula (when first char is '=') or formatted date value + * @param expr2 date formula (when first char is '=') or formatted date value + * @param dateFormat ignored if both expr1 and expr2 are formulas. Default value is "YYYY/MM/DD" + * otherwise any other valid argument for {@code SimpleDateFormat} can be used + * @see SimpleDateFormat + */ + public static DVConstraint createDateConstraint(int comparisonOperator, String expr1, String expr2, String dateFormat) { + if (expr1 == null) { + throw new IllegalArgumentException("expr1 must be supplied"); + } + OperatorType.validateSecondArg(comparisonOperator, expr2); + SimpleDateFormat df = null; + if (dateFormat != null) { + df = new SimpleDateFormat(dateFormat, LocaleUtil.getUserLocale()); + df.setTimeZone(LocaleUtil.getUserTimeZone()); + } - // formula1 and value1 are mutually exclusive - String formula1 = getFormulaFromTextExpression(expr1); - Double value1 = formula1 == null ? convertDate(expr1, df) : null; - // formula2 and value2 are mutually exclusive - String formula2 = getFormulaFromTextExpression(expr2); - Double value2 = formula2 == null ? convertDate(expr2, df) : null; - return new DVConstraint(ValidationType.DATE, comparisonOperator, formula1, formula2, value1, value2, null); - } + // formula1 and value1 are mutually exclusive + String formula1 = getFormulaFromTextExpression(expr1); + Double value1 = formula1 == null ? convertDate(expr1, df) : null; + // formula2 and value2 are mutually exclusive + String formula2 = getFormulaFromTextExpression(expr2); + Double value2 = formula2 == null ? convertDate(expr2, df) : null; + return new DVConstraint(ValidationType.DATE, comparisonOperator, formula1, formula2, value1, value2, null); + } - /** - * Distinguishes formula expressions from simple value expressions. This logic is only - * required by a few factory methods in this class that create data validation constraints - * from more or less the same parameters that would have been entered in the Excel UI. The - * data validation dialog box uses the convention that formulas begin with '='. Other methods - * in this class follow the POI convention (formulas and values are distinct), so the '=' - * convention is not used there. - * - * @param textExpr a formula or value expression - * @return all text after '=' if textExpr begins with '='. Otherwise {@code null} if textExpr does not begin with '=' - */ - private static String getFormulaFromTextExpression(String textExpr) { - if (textExpr == null) { - return null; - } - if (textExpr.length() < 1) { - throw new IllegalArgumentException("Empty string is not a valid formula/value expression"); - } - if (textExpr.charAt(0) == '=') { - return textExpr.substring(1); - } - return null; - } + /** + * Distinguishes formula expressions from simple value expressions. This logic is only + * required by a few factory methods in this class that create data validation constraints + * from more or less the same parameters that would have been entered in the Excel UI. The + * data validation dialog box uses the convention that formulas begin with '='. Other methods + * in this class follow the POI convention (formulas and values are distinct), so the '=' + * convention is not used there. + * + * @param textExpr a formula or value expression + * @return all text after '=' if textExpr begins with '='. Otherwise {@code null} if textExpr does not begin with '=' + */ + private static String getFormulaFromTextExpression(String textExpr) { + if (textExpr == null) { + return null; + } + if (textExpr.length() < 1) { + throw new IllegalArgumentException("Empty string is not a valid formula/value expression"); + } + if (textExpr.charAt(0) == '=') { + return textExpr.substring(1); + } + return null; + } - /** - * @return {@code null} if numberStr is {@code null} - */ - private static Double convertNumber(String numberStr) { - if (numberStr == null) { - return null; - } - try { - return Double.valueOf(numberStr); - } catch (NumberFormatException e) { - throw new RuntimeException("The supplied text '" + numberStr - + "' could not be parsed as a number"); - } - } + /** + * @return {@code null} if numberStr is {@code null} + */ + private static Double convertNumber(String numberStr) { + if (numberStr == null) { + return null; + } + try { + return Double.valueOf(numberStr); + } catch (NumberFormatException e) { + throw new RuntimeException("The supplied text '" + numberStr + + "' could not be parsed as a number"); + } + } - /** - * @return {@code null} if timeStr is {@code null} - */ - private static Double convertTime(String timeStr) { - if (timeStr == null) { - return null; - } - return DateUtil.convertTime(timeStr); - } - /** - * @param dateFormat pass {@code null} for default YYYYMMDD - * @return {@code null} if timeStr is {@code null} - */ - private static Double convertDate(String dateStr, SimpleDateFormat dateFormat) { - if (dateStr == null) { - return null; - } - Date dateVal; - if (dateFormat == null) { - dateVal = DateUtil.parseYYYYMMDDDate(dateStr); - } else { - try { - dateVal = dateFormat.parse(dateStr); - } catch (ParseException e) { - throw new RuntimeException("Failed to parse date '" + dateStr - + "' using specified format '" + dateFormat + "'", e); - } - } - return DateUtil.getExcelDate(dateVal); - } + /** + * @return {@code null} if timeStr is {@code null} + */ + private static Double convertTime(String timeStr) { + if (timeStr == null) { + return null; + } + return DateUtil.convertTime(timeStr); + } + /** + * @param dateFormat pass {@code null} for default YYYYMMDD + * @return {@code null} if timeStr is {@code null} + */ + private static Double convertDate(String dateStr, SimpleDateFormat dateFormat) { + if (dateStr == null) { + return null; + } + Date dateVal; + if (dateFormat == null) { + dateVal = DateUtil.parseYYYYMMDDDate(dateStr); + } else { + try { + dateVal = dateFormat.parse(dateStr); + } catch (ParseException e) { + throw new RuntimeException("Failed to parse date '" + dateStr + + "' using specified format '" + dateFormat + "'", e); + } + } + return DateUtil.getExcelDate(dateVal); + } - public static DVConstraint createCustomFormulaConstraint(String formula) { - if (formula == null) { - throw new IllegalArgumentException("formula must be supplied"); - } - return new DVConstraint(ValidationType.FORMULA, OperatorType.IGNORED, formula, null, null, null, null); - } + public static DVConstraint createCustomFormulaConstraint(String formula) { + if (formula == null) { + throw new IllegalArgumentException("formula must be supplied"); + } + return new DVConstraint(ValidationType.FORMULA, OperatorType.IGNORED, formula, null, null, null, null); + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getValidationType() - */ - @Override - public int getValidationType() { - return _validationType; - } - /** - * Convenience method - * @return {@code true} if this constraint is a 'list' validation - */ - public boolean isListValidationType() { - return _validationType == ValidationType.LIST; - } - /** - * Convenience method - * @return {@code true} if this constraint is a 'list' validation with explicit values - */ - public boolean isExplicitList() { - return _validationType == ValidationType.LIST && _explicitListValues != null; - } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getOperator() - */ - @Override - public int getOperator() { - return _operator; - } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setOperator(int) - */ - @Override - public void setOperator(int operator) { - _operator = operator; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getValidationType() + */ + @Override + public int getValidationType() { + return _validationType; + } + /** + * Convenience method + * @return {@code true} if this constraint is a 'list' validation + */ + public boolean isListValidationType() { + return _validationType == ValidationType.LIST; + } + /** + * Convenience method + * @return {@code true} if this constraint is a 'list' validation with explicit values + */ + public boolean isExplicitList() { + return _validationType == ValidationType.LIST && _explicitListValues != null; + } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getOperator() + */ + @Override + public int getOperator() { + return _operator; + } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setOperator(int) + */ + @Override + public void setOperator(int operator) { + _operator = operator; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getExplicitListValues() - */ - @Override - public String[] getExplicitListValues() { - return _explicitListValues; - } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setExplicitListValues(java.lang.String[]) - */ - @Override - public void setExplicitListValues(String[] explicitListValues) { - if (_validationType != ValidationType.LIST) { - throw new RuntimeException("Cannot setExplicitListValues on non-list constraint"); - } - _formula1 = null; - _explicitListValues = explicitListValues; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getExplicitListValues() + */ + @Override + public String[] getExplicitListValues() { + return _explicitListValues; + } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setExplicitListValues(java.lang.String[]) + */ + @Override + public void setExplicitListValues(String[] explicitListValues) { + if (_validationType != ValidationType.LIST) { + throw new RuntimeException("Cannot setExplicitListValues on non-list constraint"); + } + _formula1 = null; + _explicitListValues = explicitListValues; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getFormula1() - */ - @Override - public String getFormula1() { - return _formula1; - } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setFormula1(java.lang.String) - */ - @Override - public void setFormula1(String formula1) { - _value1 = null; - _explicitListValues = null; - _formula1 = formula1; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getFormula1() + */ + @Override + public String getFormula1() { + return _formula1; + } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setFormula1(java.lang.String) + */ + @Override + public void setFormula1(String formula1) { + _value1 = null; + _explicitListValues = null; + _formula1 = formula1; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getFormula2() - */ - @Override - public String getFormula2() { - return _formula2; - } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setFormula2(java.lang.String) - */ - @Override - public void setFormula2(String formula2) { - _value2 = null; - _formula2 = formula2; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#getFormula2() + */ + @Override + public String getFormula2() { + return _formula2; + } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidationConstraint#setFormula2(java.lang.String) + */ + @Override + public void setFormula2(String formula2) { + _value2 = null; + _formula2 = formula2; + } - /** - * @return the numeric value for expression 1. May be {@code null} - */ - public Double getValue1() { - return _value1; - } - /** - * Sets a numeric value for expression 1. - */ - public void setValue1(double value1) { - _formula1 = null; - _value1 = value1; - } + /** + * @return the numeric value for expression 1. May be {@code null} + */ + public Double getValue1() { + return _value1; + } + /** + * Sets a numeric value for expression 1. + */ + public void setValue1(double value1) { + _formula1 = null; + _value1 = value1; + } - /** - * @return the numeric value for expression 2. May be {@code null} - */ - public Double getValue2() { - return _value2; - } - /** - * Sets a numeric value for expression 2. - */ - public void setValue2(double value2) { - _formula2 = null; - _value2 = value2; - } + /** + * @return the numeric value for expression 2. May be {@code null} + */ + public Double getValue2() { + return _value2; + } + /** + * Sets a numeric value for expression 2. + */ + public void setValue2(double value2) { + _formula2 = null; + _value2 = value2; + } - /** - * @return both parsed formulas (for expression 1 and 2). - */ - /* package */ FormulaPair createFormulas(HSSFSheet sheet) { - Ptg[] formula1; - Ptg[] formula2; - if (isListValidationType()) { - formula1 = createListFormula(sheet); - formula2 = Ptg.EMPTY_PTG_ARRAY; - } else { - formula1 = convertDoubleFormula(_formula1, _value1, sheet); - formula2 = convertDoubleFormula(_formula2, _value2, sheet); - } - return new FormulaPair(formula1, formula2); - } + /** + * @return both parsed formulas (for expression 1 and 2). + */ + /* package */ FormulaPair createFormulas(HSSFSheet sheet) { + Ptg[] formula1; + Ptg[] formula2; + if (isListValidationType()) { + formula1 = createListFormula(sheet); + formula2 = Ptg.EMPTY_PTG_ARRAY; + } else { + formula1 = convertDoubleFormula(_formula1, _value1, sheet); + formula2 = convertDoubleFormula(_formula2, _value2, sheet); + } + return new FormulaPair(formula1, formula2); + } @SuppressWarnings("resource") private Ptg[] createListFormula(HSSFSheet sheet) { - if (_explicitListValues == null) { + if (_explicitListValues == null) { HSSFWorkbook wb = sheet.getWorkbook(); // formula is parsed with slightly different RVA rules: (root node type must be 'reference') - return HSSFFormulaParser.parse(_formula1, wb, FormulaType.DATAVALIDATION_LIST, wb.getSheetIndex(sheet)); - // To do: Excel places restrictions on the available operations within a list formula. - // Some things like union and intersection are not allowed. - } - // explicit list was provided - StringBuilder sb = new StringBuilder(_explicitListValues.length * 16); - for (int i = 0; i < _explicitListValues.length; i++) { - if (i > 0) { - sb.append('\0'); // list delimiter is the nul char - } - sb.append(_explicitListValues[i]); + return HSSFFormulaParser.parse(_formula1, wb, FormulaType.DATAVALIDATION_LIST, wb.getSheetIndex(sheet)); + // To do: Excel places restrictions on the available operations within a list formula. + // Some things like union and intersection are not allowed. + } + // explicit list was provided + StringBuilder sb = new StringBuilder(_explicitListValues.length * 16); + for (int i = 0; i < _explicitListValues.length; i++) { + if (i > 0) { + sb.append('\0'); // list delimiter is the nul char + } + sb.append(_explicitListValues[i]); - } - return new Ptg[] { new StringPtg(sb.toString()), }; - } + } + return new Ptg[] { new StringPtg(sb.toString()), }; + } - /** - * @return The parsed token array representing the formula or value specified. - * Empty array if both formula and value are {@code null} - */ + /** + * @return The parsed token array representing the formula or value specified. + * Empty array if both formula and value are {@code null} + */ @SuppressWarnings("resource") - private static Ptg[] convertDoubleFormula(String formula, Double value, HSSFSheet sheet) { - if (formula == null) { - if (value == null) { - return Ptg.EMPTY_PTG_ARRAY; - } - return new Ptg[] { new NumberPtg(value), }; - } - if (value != null) { - throw new IllegalStateException("Both formula and value cannot be present"); - } + private static Ptg[] convertDoubleFormula(String formula, Double value, HSSFSheet sheet) { + if (formula == null) { + if (value == null) { + return Ptg.EMPTY_PTG_ARRAY; + } + return new Ptg[] { new NumberPtg(value), }; + } + if (value != null) { + throw new IllegalStateException("Both formula and value cannot be present"); + } HSSFWorkbook wb = sheet.getWorkbook(); - return HSSFFormulaParser.parse(formula, wb, FormulaType.CELL, wb.getSheetIndex(sheet)); - } + return HSSFFormulaParser.parse(formula, wb, FormulaType.CELL, wb.getSheetIndex(sheet)); + } static DVConstraint createDVConstraint(DVRecord dvRecord, FormulaRenderingWorkbook book) { switch (dvRecord.getDataType()) { diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/EscherGraphics.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/EscherGraphics.java index 0fc1ca3e3d..a7ee8cd45a 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/EscherGraphics.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/EscherGraphics.java @@ -159,7 +159,7 @@ public class EscherGraphics extends Graphics { @Override @NotImplemented public void drawArc(int x, int y, int width, int height, - int startAngle, int arcAngle) + int startAngle, int arcAngle) { LOG.atWarn().log("drawArc not supported"); } @@ -167,10 +167,10 @@ public class EscherGraphics extends Graphics { @Override @NotImplemented public boolean drawImage(Image img, - int dx1, int dy1, int dx2, int dy2, - int sx1, int sy1, int sx2, int sy2, - Color bgcolor, - ImageObserver observer) + int dx1, int dy1, int dx2, int dy2, + int sx1, int sy1, int sx2, int sy2, + Color bgcolor, + ImageObserver observer) { LOG.atWarn().log("drawImage not supported"); @@ -180,9 +180,9 @@ public class EscherGraphics extends Graphics { @Override @NotImplemented public boolean drawImage(Image img, - int dx1, int dy1, int dx2, int dy2, - int sx1, int sy1, int sx2, int sy2, - ImageObserver observer) + int dx1, int dy1, int dx2, int dy2, + int sx1, int sy1, int sx2, int sy2, + ImageObserver observer) { LOG.atWarn().log("drawImage not supported"); return true; @@ -278,7 +278,7 @@ public class EscherGraphics extends Graphics { @Override @NotImplemented public void drawRoundRect(int x, int y, int width, int height, - int arcWidth, int arcHeight) + int arcWidth, int arcHeight) { LOG.atWarn().log("drawRoundRect not supported"); } @@ -353,7 +353,7 @@ public class EscherGraphics extends Graphics { @Override public void fillArc(int x, int y, int width, int height, - int startAngle, int arcAngle) + int startAngle, int arcAngle) { LOG.atWarn().log("fillArc not supported"); } @@ -435,7 +435,7 @@ public class EscherGraphics extends Graphics { @Override public void fillRoundRect(int x, int y, int width, int height, - int arcWidth, int arcHeight) + int arcWidth, int arcHeight) { LOG.atWarn().log("fillRoundRect not supported"); } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/EscherGraphics2d.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/EscherGraphics2d.java index 6ef38c71ee..6ac0e3c9c5 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/EscherGraphics2d.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/EscherGraphics2d.java @@ -127,7 +127,7 @@ public final class EscherGraphics2d extends Graphics2D { @Override public void copyArea(int x, int y, int width, int height, - int dx, int dy) + int dx, int dy) { getG2D().copyArea(x,y,width,height,dx,dy); } @@ -168,7 +168,7 @@ public final class EscherGraphics2d extends Graphics2D { @Override public void drawArc(int x, int y, int width, int height, - int startAngle, int arcAngle) + int startAngle, int arcAngle) { draw(new Arc2D.Float(x, y, width, height, startAngle, arcAngle, 0)); } @@ -203,8 +203,8 @@ public final class EscherGraphics2d extends Graphics2D { @Override public boolean drawImage(Image img, int x, int y, - int width, int height, - ImageObserver observer) + int width, int height, + ImageObserver observer) { return drawImage(img, x,y,width,height, null, observer); } @@ -387,7 +387,7 @@ public final class EscherGraphics2d extends Graphics2D { @Override public void fillRoundRect(int x, int y, int width, int height, - int arcWidth, int arcHeight) + int arcWidth, int arcHeight) { fill(new RoundRectangle2D.Float(x, y, width, height, arcWidth, arcHeight)); } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCell.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCell.java index 84df071015..31b6d0d9d5 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCell.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFCell.java @@ -1037,7 +1037,7 @@ public class HSSFCell extends CellBase { sdf.setTimeZone(LocaleUtil.getUserTimeZone()); return sdf.format(getDateCellValue()); } - return String.valueOf(getNumericCellValue()); + return String.valueOf(getNumericCellValue()); case STRING: return getStringCellValue(); default: diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFChart.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFChart.java index d78ac00d4d..4634d93349 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFChart.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFChart.java @@ -142,9 +142,9 @@ public final class HSSFChart { records.add( createValuesLinkedDataRecord() ); records.add( createCategoriesLinkedDataRecord() ); records.add( createDataFormatRecord() ); - // records.add(createBeginRecord()); + // records.add(createBeginRecord()); // unknown - // records.add(createEndRecord()); + // records.add(createEndRecord()); records.add( createSeriesToChartGroupRecord() ); records.add( createEndRecord() ); records.add( createSheetPropsRecord() ); @@ -590,7 +590,7 @@ public final class HSSFChart { r.setLogarithmicScale( false ); r.setValuesInReverse( false ); r.setCrossCategoryAxisAtMaximum( false ); - r.setReserved( true ); // what's this do?? + r.setReserved( true ); // what's this do?? return r; } @@ -847,9 +847,9 @@ public final class HSSFChart { private AreaFormatRecord createAreaFormatRecord1() { AreaFormatRecord r = new AreaFormatRecord(); - r.setForegroundColor( 16777215 ); // RGB Color - r.setBackgroundColor( 0 ); // RGB Color - r.setPattern( (short) 1 ); // TODO: Add Pattern constants to record + r.setForegroundColor( 16777215 ); // RGB Color + r.setBackgroundColor( 0 ); // RGB Color + r.setPattern( (short) 1 ); // TODO: Add Pattern constants to record r.setAutomatic( true ); r.setInvert( false ); r.setForecolorIndex( (short) 78 ); diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataFormat.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataFormat.java index e9a68aa21b..bc1f1d46e3 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataFormat.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataFormat.java @@ -38,97 +38,97 @@ import org.apache.poi.ss.usermodel.DataFormat; * @see Review guidelines for customizing a number format */ public final class HSSFDataFormat implements DataFormat { - private static final String[] _builtinFormats = BuiltinFormats.getAll(); + private static final String[] _builtinFormats = BuiltinFormats.getAll(); - private final Vector _formats = new Vector<>(); - private final InternalWorkbook _workbook; - private boolean _movedBuiltins; // Flag to see if need to - // check the built in list - // or if the regular list - // has all entries. + private final Vector _formats = new Vector<>(); + private final InternalWorkbook _workbook; + private boolean _movedBuiltins; // Flag to see if need to + // check the built in list + // or if the regular list + // has all entries. - /** - * Constructs a new data formatter. It takes a workbook to have - * access to the workbooks format records. - * @param workbook the workbook the formats are tied to. - */ - HSSFDataFormat(InternalWorkbook workbook) { - _workbook = workbook; + /** + * Constructs a new data formatter. It takes a workbook to have + * access to the workbooks format records. + * @param workbook the workbook the formats are tied to. + */ + HSSFDataFormat(InternalWorkbook workbook) { + _workbook = workbook; - Iterator i = workbook.getFormats().iterator(); - while (i.hasNext()) { - FormatRecord r = i.next(); - ensureFormatsSize(r.getIndexCode()); - _formats.set(r.getIndexCode(), r.getFormatString()); - } - } + Iterator i = workbook.getFormats().iterator(); + while (i.hasNext()) { + FormatRecord r = i.next(); + ensureFormatsSize(r.getIndexCode()); + _formats.set(r.getIndexCode(), r.getFormatString()); + } + } - public static List getBuiltinFormats() { - return Arrays.asList(_builtinFormats); - } + public static List getBuiltinFormats() { + return Arrays.asList(_builtinFormats); + } - /** - * get the format index that matches the given format string

- * Automatically converts "text" to excel's format string to represent text. - * @param format string matching a built in format - * @return index of format or -1 if undefined. - */ - public static short getBuiltinFormat(String format) { - return (short) BuiltinFormats.getBuiltinFormat(format); - } + /** + * get the format index that matches the given format string

+ * Automatically converts "text" to excel's format string to represent text. + * @param format string matching a built in format + * @return index of format or -1 if undefined. + */ + public static short getBuiltinFormat(String format) { + return (short) BuiltinFormats.getBuiltinFormat(format); + } - /** - * Get the format index that matches the given format - * string, creating a new format entry if required. - * Aliases text to the proper format as required. - * @param pFormat string matching a built in format - * @return index of format. - */ - public short getFormat(String pFormat) { - // Normalise the format string - String format; - if (pFormat.equalsIgnoreCase("TEXT")) { - format = "@"; - } else { - format = pFormat; - } + /** + * Get the format index that matches the given format + * string, creating a new format entry if required. + * Aliases text to the proper format as required. + * @param pFormat string matching a built in format + * @return index of format. + */ + public short getFormat(String pFormat) { + // Normalise the format string + String format; + if (pFormat.equalsIgnoreCase("TEXT")) { + format = "@"; + } else { + format = pFormat; + } - // Merge in the built in formats if we haven't already - if (!_movedBuiltins) { - for (int i=0; i<_builtinFormats.length; i++) { - ensureFormatsSize(i); - if (_formats.get(i) == null) { - _formats.set(i, _builtinFormats[i]); - } else { - // The workbook overrides this default format - } - } - _movedBuiltins = true; - } + // Merge in the built in formats if we haven't already + if (!_movedBuiltins) { + for (int i=0; i<_builtinFormats.length; i++) { + ensureFormatsSize(i); + if (_formats.get(i) == null) { + _formats.set(i, _builtinFormats[i]); + } else { + // The workbook overrides this default format + } + } + _movedBuiltins = true; + } - // See if we can find it - for(int i=0; i<_formats.size(); i++) { - if(format.equals(_formats.get(i))) { - return (short)i; - } - } + // See if we can find it + for(int i=0; i<_formats.size(); i++) { + if(format.equals(_formats.get(i))) { + return (short)i; + } + } - // We can't find it, so add it as a new one - short index = _workbook.getFormat(format, true); - ensureFormatsSize(index); - _formats.set(index, format); - return index; - } + // We can't find it, so add it as a new one + short index = _workbook.getFormat(format, true); + ensureFormatsSize(index); + _formats.set(index, format); + return index; + } - /** - * get the format string that matches the given format index - * @param index of a format - * @return string represented at index of format or null if there is not a format at that index - */ - public String getFormat(short index) { - if (_movedBuiltins) { - return _formats.get(index); - } + /** + * get the format string that matches the given format index + * @param index of a format + * @return string represented at index of format or null if there is not a format at that index + */ + public String getFormat(short index) { + if (_movedBuiltins) { + return _formats.get(index); + } if(index == -1) { // YK: formatIndex can be -1, for example, for cell in column Y in test-data/spreadsheet/45322.xls @@ -136,44 +136,44 @@ public final class HSSFDataFormat implements DataFormat { return null; } - String fmt = _formats.size() > index ? _formats.get(index) : null; - if (_builtinFormats.length > index && _builtinFormats[index] != null) { - // It's in the built in range - if (fmt != null) { - // It's been overriden, use that value - return fmt; - } else { - // Standard built in format - return _builtinFormats[index]; - } - } - return fmt; - } + String fmt = _formats.size() > index ? _formats.get(index) : null; + if (_builtinFormats.length > index && _builtinFormats[index] != null) { + // It's in the built in range + if (fmt != null) { + // It's been overriden, use that value + return fmt; + } else { + // Standard built in format + return _builtinFormats[index]; + } + } + return fmt; + } - /** - * get the format string that matches the given format index - * @param index of a built in format - * @return string represented at index of format or null if there is not a builtin format at that index - */ - public static String getBuiltinFormat(short index) { - return BuiltinFormats.getBuiltinFormat(index); - } + /** + * get the format string that matches the given format index + * @param index of a built in format + * @return string represented at index of format or null if there is not a builtin format at that index + */ + public static String getBuiltinFormat(short index) { + return BuiltinFormats.getBuiltinFormat(index); + } - /** - * get the number of built-in and reserved builtinFormats - * @return number of built-in and reserved builtinFormats - */ - public static int getNumberOfBuiltinBuiltinFormats() { - return _builtinFormats.length; - } + /** + * get the number of built-in and reserved builtinFormats + * @return number of built-in and reserved builtinFormats + */ + public static int getNumberOfBuiltinBuiltinFormats() { + return _builtinFormats.length; + } - /** - * Ensures that the formats list can hold entries - * up to and including the entry with this index - */ - private void ensureFormatsSize(int index) { - if(_formats.size() <= index) { - _formats.setSize(index+1); - } - } + /** + * Ensures that the formats list can hold entries + * up to and including the entry with this index + */ + private void ensureFormatsSize(int index) { + if(_formats.size() <= index) { + _formats.setSize(index+1); + } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataValidation.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataValidation.java index 40c0ada463..de90984bb6 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataValidation.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataValidation.java @@ -28,195 +28,195 @@ import org.apache.poi.ss.util.CellRangeAddressList; * Utility class for creating data validation cells */ public final class HSSFDataValidation implements DataValidation { - private String _prompt_title; - private String _prompt_text; - private String _error_title; - private String _error_text; + private String _prompt_title; + private String _prompt_text; + private String _error_title; + private String _error_text; - private int _errorStyle = ErrorStyle.STOP; - private boolean _emptyCellAllowed = true; - private boolean _suppress_dropdown_arrow; - private boolean _showPromptBox = true; - private boolean _showErrorBox = true; - private CellRangeAddressList _regions; - private DVConstraint _constraint; + private int _errorStyle = ErrorStyle.STOP; + private boolean _emptyCellAllowed = true; + private boolean _suppress_dropdown_arrow; + private boolean _showPromptBox = true; + private boolean _showErrorBox = true; + private CellRangeAddressList _regions; + private DVConstraint _constraint; - /** - * Constructor which initializes the cell range on which this object will be - * applied - * - * @param regions A list of regions where the constraint is validated. - * @param constraint The constraints to apply for this validation. - */ - public HSSFDataValidation(CellRangeAddressList regions, DataValidationConstraint constraint) { - _regions = regions; - - //FIXME: This cast can be avoided. - _constraint = (DVConstraint)constraint; - } + /** + * Constructor which initializes the cell range on which this object will be + * applied + * + * @param regions A list of regions where the constraint is validated. + * @param constraint The constraints to apply for this validation. + */ + public HSSFDataValidation(CellRangeAddressList regions, DataValidationConstraint constraint) { + _regions = regions; + + //FIXME: This cast can be avoided. + _constraint = (DVConstraint)constraint; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#getConstraint() - */ - public DataValidationConstraint getValidationConstraint() { - return _constraint; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#getConstraint() + */ + public DataValidationConstraint getValidationConstraint() { + return _constraint; + } - public DVConstraint getConstraint() { - return _constraint; - } - - public CellRangeAddressList getRegions() { - return _regions; - } + public DVConstraint getConstraint() { + return _constraint; + } + + public CellRangeAddressList getRegions() { + return _regions; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#setErrorStyle(int) - */ - public void setErrorStyle(int error_style) { - _errorStyle = error_style; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#setErrorStyle(int) + */ + public void setErrorStyle(int error_style) { + _errorStyle = error_style; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#getErrorStyle() - */ - public int getErrorStyle() { - return _errorStyle; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#getErrorStyle() + */ + public int getErrorStyle() { + return _errorStyle; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#setEmptyCellAllowed(boolean) - */ - public void setEmptyCellAllowed(boolean allowed) { - _emptyCellAllowed = allowed; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#setEmptyCellAllowed(boolean) + */ + public void setEmptyCellAllowed(boolean allowed) { + _emptyCellAllowed = allowed; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#getEmptyCellAllowed() - */ - public boolean getEmptyCellAllowed() { - return _emptyCellAllowed; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#getEmptyCellAllowed() + */ + public boolean getEmptyCellAllowed() { + return _emptyCellAllowed; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#setSuppressDropDownArrow(boolean) - */ - public void setSuppressDropDownArrow(boolean suppress) { - _suppress_dropdown_arrow = suppress; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#setSuppressDropDownArrow(boolean) + */ + public void setSuppressDropDownArrow(boolean suppress) { + _suppress_dropdown_arrow = suppress; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#getSuppressDropDownArrow() - */ - public boolean getSuppressDropDownArrow() { - //noinspection SimplifiableIfStatement - if (_constraint.getValidationType()==ValidationType.LIST) { - return _suppress_dropdown_arrow; - } - return false; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#getSuppressDropDownArrow() + */ + public boolean getSuppressDropDownArrow() { + //noinspection SimplifiableIfStatement + if (_constraint.getValidationType()==ValidationType.LIST) { + return _suppress_dropdown_arrow; + } + return false; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#setShowPromptBox(boolean) - */ - public void setShowPromptBox(boolean show) { - _showPromptBox = show; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#setShowPromptBox(boolean) + */ + public void setShowPromptBox(boolean show) { + _showPromptBox = show; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#getShowPromptBox() - */ - public boolean getShowPromptBox() { - return _showPromptBox; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#getShowPromptBox() + */ + public boolean getShowPromptBox() { + return _showPromptBox; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#setShowErrorBox(boolean) - */ - public void setShowErrorBox(boolean show) { - _showErrorBox = show; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#setShowErrorBox(boolean) + */ + public void setShowErrorBox(boolean show) { + _showErrorBox = show; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#getShowErrorBox() - */ - public boolean getShowErrorBox() { - return _showErrorBox; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#getShowErrorBox() + */ + public boolean getShowErrorBox() { + return _showErrorBox; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#createPromptBox(java.lang.String, java.lang.String) - */ - public void createPromptBox(String title, String text) { - // check length-limits - if(title != null && title.length() > 32) { - throw new IllegalStateException("Prompt-title cannot be longer than 32 characters, but had: " + title); - } - if(text != null && text.length() > 255) { - throw new IllegalStateException("Prompt-text cannot be longer than 255 characters, but had: " + text); - } - _prompt_title = title; - _prompt_text = text; - this.setShowPromptBox(true); - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#createPromptBox(java.lang.String, java.lang.String) + */ + public void createPromptBox(String title, String text) { + // check length-limits + if(title != null && title.length() > 32) { + throw new IllegalStateException("Prompt-title cannot be longer than 32 characters, but had: " + title); + } + if(text != null && text.length() > 255) { + throw new IllegalStateException("Prompt-text cannot be longer than 255 characters, but had: " + text); + } + _prompt_title = title; + _prompt_text = text; + this.setShowPromptBox(true); + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#getPromptBoxTitle() - */ - public String getPromptBoxTitle() { - return _prompt_title; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#getPromptBoxTitle() + */ + public String getPromptBoxTitle() { + return _prompt_title; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#getPromptBoxText() - */ - public String getPromptBoxText() { - return _prompt_text; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#getPromptBoxText() + */ + public String getPromptBoxText() { + return _prompt_text; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#createErrorBox(java.lang.String, java.lang.String) - */ - public void createErrorBox(String title, String text) { - if(title != null && title.length() > 32) { - throw new IllegalStateException("Error-title cannot be longer than 32 characters, but had: " + title); - } - if(text != null && text.length() > 255) { - throw new IllegalStateException("Error-text cannot be longer than 255 characters, but had: " + text); - } - _error_title = title; - _error_text = text; - this.setShowErrorBox(true); - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#createErrorBox(java.lang.String, java.lang.String) + */ + public void createErrorBox(String title, String text) { + if(title != null && title.length() > 32) { + throw new IllegalStateException("Error-title cannot be longer than 32 characters, but had: " + title); + } + if(text != null && text.length() > 255) { + throw new IllegalStateException("Error-text cannot be longer than 255 characters, but had: " + text); + } + _error_title = title; + _error_text = text; + this.setShowErrorBox(true); + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#getErrorBoxTitle() - */ - public String getErrorBoxTitle() { - return _error_title; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#getErrorBoxTitle() + */ + public String getErrorBoxTitle() { + return _error_title; + } - /* (non-Javadoc) - * @see org.apache.poi.hssf.usermodel.DataValidation#getErrorBoxText() - */ - public String getErrorBoxText() { - return _error_text; - } + /* (non-Javadoc) + * @see org.apache.poi.hssf.usermodel.DataValidation#getErrorBoxText() + */ + public String getErrorBoxText() { + return _error_text; + } - public DVRecord createDVRecord(HSSFSheet sheet) { + public DVRecord createDVRecord(HSSFSheet sheet) { - FormulaPair fp = _constraint.createFormulas(sheet); - - return new DVRecord(_constraint.getValidationType(), - _constraint.getOperator(), - _errorStyle, _emptyCellAllowed, getSuppressDropDownArrow(), - _constraint.getValidationType()==ValidationType.LIST && _constraint.getExplicitListValues()!=null, - _showPromptBox, _prompt_title, _prompt_text, - _showErrorBox, _error_title, _error_text, - fp.getFormula1(), fp.getFormula2(), - _regions); - } + FormulaPair fp = _constraint.createFormulas(sheet); + + return new DVRecord(_constraint.getValidationType(), + _constraint.getOperator(), + _errorStyle, _emptyCellAllowed, getSuppressDropDownArrow(), + _constraint.getValidationType()==ValidationType.LIST && _constraint.getExplicitListValues()!=null, + _showPromptBox, _prompt_title, _prompt_text, + _showErrorBox, _error_title, _error_text, + fp.getFormula1(), fp.getFormula2(), + _regions); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataValidationHelper.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataValidationHelper.java index 15161cb882..b755acd08f 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataValidationHelper.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDataValidationHelper.java @@ -27,106 +27,106 @@ import org.apache.poi.ss.util.CellRangeAddressList; * Helper for working with Data Validation */ public class HSSFDataValidationHelper implements DataValidationHelper { - // Findbugs: URF_UNREAD_FIELD . Do not delete without understanding how this class works. - //private HSSFSheet sheet; - - public HSSFDataValidationHelper(HSSFSheet sheet) { - super(); - // Findbugs: URF_UNREAD_FIELD . Do not delete without understanding how this class works. - //this.sheet = sheet; - } + // Findbugs: URF_UNREAD_FIELD . Do not delete without understanding how this class works. + //private HSSFSheet sheet; + + public HSSFDataValidationHelper(HSSFSheet sheet) { + super(); + // Findbugs: URF_UNREAD_FIELD . Do not delete without understanding how this class works. + //this.sheet = sheet; + } - /* - * (non-Javadoc) - * - * @see - * org.apache.poi.ss.usermodel.DataValidationHelper#createDateConstraint - * (int, java.lang.String, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createDateConstraint(int operatorType, String formula1, String formula2, String dateFormat) { - return DVConstraint.createDateConstraint(operatorType, formula1, formula2, dateFormat); - } + /* + * (non-Javadoc) + * + * @see + * org.apache.poi.ss.usermodel.DataValidationHelper#createDateConstraint + * (int, java.lang.String, java.lang.String, java.lang.String) + */ + public DataValidationConstraint createDateConstraint(int operatorType, String formula1, String formula2, String dateFormat) { + return DVConstraint.createDateConstraint(operatorType, formula1, formula2, dateFormat); + } - /* - * (non-Javadoc) - * - * @see - * org.apache.poi.ss.usermodel.DataValidationHelper#createExplicitListConstraint - * (java.lang.String[]) - */ - public DataValidationConstraint createExplicitListConstraint(String[] listOfValues) { - return DVConstraint.createExplicitListConstraint(listOfValues); - } + /* + * (non-Javadoc) + * + * @see + * org.apache.poi.ss.usermodel.DataValidationHelper#createExplicitListConstraint + * (java.lang.String[]) + */ + public DataValidationConstraint createExplicitListConstraint(String[] listOfValues) { + return DVConstraint.createExplicitListConstraint(listOfValues); + } - /* - * (non-Javadoc) - * - * @see - * org.apache.poi.ss.usermodel.DataValidationHelper#createFormulaListConstraint - * (java.lang.String) - */ - public DataValidationConstraint createFormulaListConstraint(String listFormula) { - return DVConstraint.createFormulaListConstraint(listFormula); - } + /* + * (non-Javadoc) + * + * @see + * org.apache.poi.ss.usermodel.DataValidationHelper#createFormulaListConstraint + * (java.lang.String) + */ + public DataValidationConstraint createFormulaListConstraint(String listFormula) { + return DVConstraint.createFormulaListConstraint(listFormula); + } - - - public DataValidationConstraint createNumericConstraint(int validationType,int operatorType, String formula1, String formula2) { - return DVConstraint.createNumericConstraint(validationType, operatorType, formula1, formula2); - } + + + public DataValidationConstraint createNumericConstraint(int validationType,int operatorType, String formula1, String formula2) { + return DVConstraint.createNumericConstraint(validationType, operatorType, formula1, formula2); + } - public DataValidationConstraint createIntegerConstraint(int operatorType, String formula1, String formula2) { - return DVConstraint.createNumericConstraint(ValidationType.INTEGER, operatorType, formula1, formula2); - } - - /* - * (non-Javadoc) - * - * @see - * org.apache.poi.ss.usermodel.DataValidationHelper#createNumericConstraint - * (int, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createDecimalConstraint(int operatorType, String formula1, String formula2) { - return DVConstraint.createNumericConstraint(ValidationType.DECIMAL, operatorType, formula1, formula2); - } + public DataValidationConstraint createIntegerConstraint(int operatorType, String formula1, String formula2) { + return DVConstraint.createNumericConstraint(ValidationType.INTEGER, operatorType, formula1, formula2); + } + + /* + * (non-Javadoc) + * + * @see + * org.apache.poi.ss.usermodel.DataValidationHelper#createNumericConstraint + * (int, java.lang.String, java.lang.String) + */ + public DataValidationConstraint createDecimalConstraint(int operatorType, String formula1, String formula2) { + return DVConstraint.createNumericConstraint(ValidationType.DECIMAL, operatorType, formula1, formula2); + } - /* - * (non-Javadoc) - * - * @see - * org.apache.poi.ss.usermodel.DataValidationHelper#createTextLengthConstraint - * (int, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createTextLengthConstraint(int operatorType, String formula1, String formula2) { - return DVConstraint.createNumericConstraint(ValidationType.TEXT_LENGTH, operatorType, formula1, formula2); - } + /* + * (non-Javadoc) + * + * @see + * org.apache.poi.ss.usermodel.DataValidationHelper#createTextLengthConstraint + * (int, java.lang.String, java.lang.String) + */ + public DataValidationConstraint createTextLengthConstraint(int operatorType, String formula1, String formula2) { + return DVConstraint.createNumericConstraint(ValidationType.TEXT_LENGTH, operatorType, formula1, formula2); + } - /* - * (non-Javadoc) - * - * @see - * org.apache.poi.ss.usermodel.DataValidationHelper#createTimeConstraint - * (int, java.lang.String, java.lang.String, java.lang.String) - */ - public DataValidationConstraint createTimeConstraint(int operatorType, String formula1, String formula2) { - return DVConstraint.createTimeConstraint(operatorType, formula1, formula2); - } + /* + * (non-Javadoc) + * + * @see + * org.apache.poi.ss.usermodel.DataValidationHelper#createTimeConstraint + * (int, java.lang.String, java.lang.String, java.lang.String) + */ + public DataValidationConstraint createTimeConstraint(int operatorType, String formula1, String formula2) { + return DVConstraint.createTimeConstraint(operatorType, formula1, formula2); + } - - - public DataValidationConstraint createCustomConstraint(String formula) { - return DVConstraint.createCustomFormulaConstraint(formula); - } + + + public DataValidationConstraint createCustomConstraint(String formula) { + return DVConstraint.createCustomFormulaConstraint(formula); + } - /* - * (non-Javadoc) - * - * @see - * org.apache.poi.ss.usermodel.DataValidationHelper#createValidation(org - * .apache.poi.ss.usermodel.DataValidationConstraint, - * org.apache.poi.ss.util.CellRangeAddressList) - */ - public DataValidation createValidation(DataValidationConstraint constraint, CellRangeAddressList cellRangeAddressList) { - return new HSSFDataValidation(cellRangeAddressList, constraint); - } + /* + * (non-Javadoc) + * + * @see + * org.apache.poi.ss.usermodel.DataValidationHelper#createValidation(org + * .apache.poi.ss.usermodel.DataValidationConstraint, + * org.apache.poi.ss.util.CellRangeAddressList) + */ + public DataValidation createValidation(DataValidationConstraint constraint, CellRangeAddressList cellRangeAddressList) { + return new HSSFDataValidation(cellRangeAddressList, constraint); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDateUtil.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDateUtil.java index f0ff039fd1..3a31f0cc70 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDateUtil.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFDateUtil.java @@ -34,7 +34,7 @@ import org.apache.poi.ss.usermodel.DateUtil; */ @Deprecated public final class HSSFDateUtil extends DateUtil { - protected static int absoluteDay(Calendar cal, boolean use1904windowing) { - return DateUtil.absoluteDay(cal, use1904windowing); - } + protected static int absoluteDay(Calendar cal, boolean use1904windowing) { + return DateUtil.absoluteDay(cal, use1904windowing); + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFEvaluationCell.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFEvaluationCell.java index 4b90599e43..5a393bee95 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFEvaluationCell.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFEvaluationCell.java @@ -27,76 +27,76 @@ import org.apache.poi.ss.util.CellRangeAddress; */ final class HSSFEvaluationCell implements EvaluationCell { - private final EvaluationSheet _evalSheet; - private final HSSFCell _cell; + private final EvaluationSheet _evalSheet; + private final HSSFCell _cell; - public HSSFEvaluationCell(HSSFCell cell, EvaluationSheet evalSheet) { - _cell = cell; - _evalSheet = evalSheet; - } - public HSSFEvaluationCell(HSSFCell cell) { - this(cell, new HSSFEvaluationSheet(cell.getSheet())); - } - @Override - public Object getIdentityKey() { - // save memory by just using the cell itself as the identity key - // Note - this assumes HSSFCell has not overridden hashCode and equals - return _cell; - } + public HSSFEvaluationCell(HSSFCell cell, EvaluationSheet evalSheet) { + _cell = cell; + _evalSheet = evalSheet; + } + public HSSFEvaluationCell(HSSFCell cell) { + this(cell, new HSSFEvaluationSheet(cell.getSheet())); + } + @Override + public Object getIdentityKey() { + // save memory by just using the cell itself as the identity key + // Note - this assumes HSSFCell has not overridden hashCode and equals + return _cell; + } - public HSSFCell getHSSFCell() { - return _cell; - } - @Override - public boolean getBooleanCellValue() { - return _cell.getBooleanCellValue(); - } - /** - * @return cell type - */ - @Override - public CellType getCellType() { - return _cell.getCellType(); - } - @Override - public int getColumnIndex() { - return _cell.getColumnIndex(); - } - @Override - public int getErrorCellValue() { - return _cell.getErrorCellValue(); - } - @Override - public double getNumericCellValue() { - return _cell.getNumericCellValue(); - } - @Override - public int getRowIndex() { - return _cell.getRowIndex(); - } - @Override - public EvaluationSheet getSheet() { - return _evalSheet; - } - @Override - public String getStringCellValue() { - return _cell.getRichStringCellValue().getString(); - } - - @Override - public CellRangeAddress getArrayFormulaRange() { - return _cell.getArrayFormulaRange(); - } - - @Override - public boolean isPartOfArrayFormulaGroup() { - return _cell.isPartOfArrayFormulaGroup(); - } - - /** - * @since POI 4.0 - * @return cell type of cached formula result - */ - @Override - public CellType getCachedFormulaResultType() { return _cell.getCachedFormulaResultType(); } + public HSSFCell getHSSFCell() { + return _cell; + } + @Override + public boolean getBooleanCellValue() { + return _cell.getBooleanCellValue(); + } + /** + * @return cell type + */ + @Override + public CellType getCellType() { + return _cell.getCellType(); + } + @Override + public int getColumnIndex() { + return _cell.getColumnIndex(); + } + @Override + public int getErrorCellValue() { + return _cell.getErrorCellValue(); + } + @Override + public double getNumericCellValue() { + return _cell.getNumericCellValue(); + } + @Override + public int getRowIndex() { + return _cell.getRowIndex(); + } + @Override + public EvaluationSheet getSheet() { + return _evalSheet; + } + @Override + public String getStringCellValue() { + return _cell.getRichStringCellValue().getString(); + } + + @Override + public CellRangeAddress getArrayFormulaRange() { + return _cell.getArrayFormulaRange(); + } + + @Override + public boolean isPartOfArrayFormulaGroup() { + return _cell.isPartOfArrayFormulaGroup(); + } + + /** + * @since POI 4.0 + * @return cell type of cached formula result + */ + @Override + public CellType getCachedFormulaResultType() { return _cell.getCachedFormulaResultType(); } } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFFont.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFFont.java index fb7a7a74cb..38998c6043 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFFont.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFFont.java @@ -358,24 +358,24 @@ public final class HSSFFont implements Font { "}"; } - public int hashCode() { + public int hashCode() { return Objects.hash(font,index); - } + } - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (obj instanceof HSSFFont) { - final HSSFFont other = (HSSFFont) obj; - if (font == null) { - if (other.font != null) { + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (obj instanceof HSSFFont) { + final HSSFFont other = (HSSFFont) obj; + if (font == null) { + if (other.font != null) { return false; } - } else if (!font.equals(other.font)) { + } else if (!font.equals(other.font)) { return false; } return index == other.index; } - return false; - } + return false; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFFooter.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFFooter.java index e23c21bea0..6e98483ec9 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFFooter.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFFooter.java @@ -32,28 +32,28 @@ import org.apache.poi.ss.usermodel.Footer; * fonts by using similar methods. */ public final class HSSFFooter extends HeaderFooter implements Footer { - private final PageSettingsBlock _psb; + private final PageSettingsBlock _psb; - protected HSSFFooter(PageSettingsBlock psb) { - _psb = psb; - } + protected HSSFFooter(PageSettingsBlock psb) { + _psb = psb; + } - protected String getRawText() { - FooterRecord hf = _psb.getFooter(); - if (hf == null) { - return ""; - } - return hf.getText(); - } + protected String getRawText() { + FooterRecord hf = _psb.getFooter(); + if (hf == null) { + return ""; + } + return hf.getText(); + } - @Override - protected void setHeaderFooterText(String text) { - FooterRecord hfr = _psb.getFooter(); - if (hfr == null) { - hfr = new FooterRecord(text); - _psb.setFooter(hfr); - } else { - hfr.setText(text); - } - } + @Override + protected void setHeaderFooterText(String text) { + FooterRecord hfr = _psb.getFooter(); + if (hfr == null) { + hfr = new FooterRecord(text); + _psb.setFooter(hfr); + } else { + hfr.setText(text); + } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFHeader.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFHeader.java index 41530874f1..3ae6c30ec5 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFHeader.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFHeader.java @@ -33,28 +33,28 @@ import org.apache.poi.ss.usermodel.Header; */ public final class HSSFHeader extends HeaderFooter implements Header { - private final PageSettingsBlock _psb; + private final PageSettingsBlock _psb; - protected HSSFHeader(PageSettingsBlock psb) { - _psb = psb; - } + protected HSSFHeader(PageSettingsBlock psb) { + _psb = psb; + } - protected String getRawText() { - HeaderRecord hf = _psb.getHeader(); - if (hf == null) { - return ""; - } - return hf.getText(); - } + protected String getRawText() { + HeaderRecord hf = _psb.getHeader(); + if (hf == null) { + return ""; + } + return hf.getText(); + } - @Override - protected void setHeaderFooterText(String text) { - HeaderRecord hfr = _psb.getHeader(); - if (hfr == null) { - hfr = new HeaderRecord(text); - _psb.setHeader(hfr); - } else { - hfr.setText(text); - } - } + @Override + protected void setHeaderFooterText(String text) { + HeaderRecord hfr = _psb.getHeader(); + if (hfr == null) { + hfr = new HeaderRecord(text); + _psb.setHeader(hfr); + } else { + hfr.setText(text); + } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFOptimiser.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFOptimiser.java index 40799029be..865ffc5d19 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFOptimiser.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFOptimiser.java @@ -39,131 +39,131 @@ import org.apache.poi.ss.usermodel.Row; * is where the use of this class comes in. */ public class HSSFOptimiser { - /** - * Goes through the Workbook, optimising the fonts by - * removing duplicate ones. - * For now, only works on fonts used in {@link HSSFCellStyle} - * and {@link HSSFRichTextString}. Any other font uses - * (eg charts, pictures) may well end up broken! - * This can be a slow operation, especially if you have - * lots of cells, cell styles or rich text strings - * @param workbook The workbook in which to optimise the fonts - */ - public static void optimiseFonts(HSSFWorkbook workbook) { - // Where each font has ended up, and if we need to - // delete the record for it. Start off with no change - short[] newPos = - new short[workbook.getWorkbook().getNumberOfFontRecords()+1]; - boolean[] zapRecords = new boolean[newPos.length]; - for(int i=0; i doneUnicodeStrings = new HashSet<>(); - for(int sheetNum=0; sheetNum doneUnicodeStrings = new HashSet<>(); + for(int sheetNum=0; sheetNum= newPos.length) { - continue; - } - HSSFCellStyle newStyle = workbook.getCellStyleAt(newPos[oldXf]); - cell.setCellStyle(newStyle); - } + // Finally, update the cells to point at their new extended format records + for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) { + HSSFSheet s = workbook.getSheetAt(sheetNum); + for (Row row : s) { + for (Cell cell : row) { + short oldXf = ((HSSFCell) cell).getCellValueRecord().getXFIndex(); + // some documents contain invalid values here + if(oldXf >= newPos.length) { + continue; + } + HSSFCellStyle newStyle = workbook.getCellStyleAt(newPos[oldXf]); + cell.setCellStyle(newStyle); + } - // adjust row column style - short oldXf = ((HSSFRow) row).getRowRecord().getXFIndex(); - // some documents contain invalid values here - if(oldXf >= newPos.length) { - continue; - } - HSSFCellStyle newStyle = workbook.getCellStyleAt(newPos[oldXf]); - row.setRowStyle(newStyle); - } + // adjust row column style + short oldXf = ((HSSFRow) row).getRowRecord().getXFIndex(); + // some documents contain invalid values here + if(oldXf >= newPos.length) { + continue; + } + HSSFCellStyle newStyle = workbook.getCellStyleAt(newPos[oldXf]); + row.setRowStyle(newStyle); + } - // adjust cell column style - for (int col = s.getSheet().getMinColumnIndex(); col <= s.getSheet().getMaxColumnIndex(); col++) { - short oldXf = s.getSheet().getXFIndexForColAt((short) col); - // some documents contain invalid values here - if(oldXf >= newPos.length) { - continue; - } - HSSFCellStyle newStyle = workbook.getCellStyleAt(newPos[oldXf]); - s.setDefaultColumnStyle(col, newStyle); - } - } + // adjust cell column style + for (int col = s.getSheet().getMinColumnIndex(); col <= s.getSheet().getMaxColumnIndex(); col++) { + short oldXf = s.getSheet().getXFIndexForColAt((short) col); + // some documents contain invalid values here + if(oldXf >= newPos.length) { + continue; + } + HSSFCellStyle newStyle = workbook.getCellStyleAt(newPos[oldXf]); + s.setDefaultColumnStyle(col, newStyle); + } + } } - private static boolean isUserDefined(HSSFWorkbook workbook, int index) { - StyleRecord styleRecord = workbook.getWorkbook().getStyleRecord(index); - return styleRecord != null && - !styleRecord.isBuiltin() && - styleRecord.getName() != null; - } + private static boolean isUserDefined(HSSFWorkbook workbook, int index) { + StyleRecord styleRecord = workbook.getWorkbook().getStyleRecord(index); + return styleRecord != null && + !styleRecord.isBuiltin() && + styleRecord.getName() != null; + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPalette.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPalette.java index b74bf1b570..3dcc5bccc0 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPalette.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPalette.java @@ -60,7 +60,7 @@ public final class HSSFPalette { * @return the color, or null if the index is not populated */ public HSSFColor getColor(int index) { - return getColor((short)index); + return getColor((short)index); } /** @@ -97,7 +97,7 @@ public final class HSSFPalette { * colors currently defined. */ public HSSFColor findSimilarColor(byte red, byte green, byte blue) { - return findSimilarColor(unsignedInt(red), unsignedInt(green), unsignedInt(blue)); + return findSimilarColor(unsignedInt(red), unsignedInt(green), unsignedInt(blue)); } /** * Finds the closest matching color in the custom palette. The @@ -118,8 +118,8 @@ public final class HSSFPalette { b = _palette.getColor(++i)) { int colorDistance = Math.abs(red - unsignedInt(b[0])) + - Math.abs(green - unsignedInt(b[1])) + - Math.abs(blue - unsignedInt(b[2])); + Math.abs(green - unsignedInt(b[1])) + + Math.abs(blue - unsignedInt(b[2])); if (colorDistance < minColorDistance) { minColorDistance = colorDistance; @@ -134,7 +134,7 @@ public final class HSSFPalette { * 0 and 255, so distance calculations work as expected. */ private int unsignedInt(byte b) { - return 0xFF & b; + return 0xFF & b; } /** diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPatriarch.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPatriarch.java index e5b6d668cc..bf68edf821 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPatriarch.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFPatriarch.java @@ -238,19 +238,19 @@ public final class HSSFPatriarch implements HSSFShapeContainer, Drawing * public static final short PRINTER_DEFAULT_PAPERSIZE = 0;
- * public static final short LETTER_PAPERSIZE = 1;
- * public static final short LEGAL_PAPERSIZE = 5;
- * public static final short EXECUTIVE_PAPERSIZE = 7;
- * public static final short A4_PAPERSIZE = 9;
- * public static final short A5_PAPERSIZE = 11;
- * public static final short ENVELOPE_10_PAPERSIZE = 20;
- * public static final short ENVELOPE_DL_PAPERSIZE = 27;
- * public static final short ENVELOPE_CS_PAPERSIZE = 28;
+ * public static final short LETTER_PAPERSIZE = 1;
+ * public static final short LEGAL_PAPERSIZE = 5;
+ * public static final short EXECUTIVE_PAPERSIZE = 7;
+ * public static final short A4_PAPERSIZE = 9;
+ * public static final short A5_PAPERSIZE = 11;
+ * public static final short ENVELOPE_10_PAPERSIZE = 20;
+ * public static final short ENVELOPE_DL_PAPERSIZE = 27;
+ * public static final short ENVELOPE_CS_PAPERSIZE = 28;
* public static final short ENVELOPE_MONARCH_PAPERSIZE = 37;
*/ public class HSSFPrintSetup implements PrintSetup { @@ -45,7 +45,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param printSetupRecord the low level print setup record */ protected HSSFPrintSetup(PrintSetupRecord printSetupRecord) { - this.printSetupRecord = printSetupRecord; + this.printSetupRecord = printSetupRecord; } /** @@ -53,7 +53,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param size the paper size. */ public void setPaperSize(short size) { - printSetupRecord.setPaperSize(size); + printSetupRecord.setPaperSize(size); } /** @@ -61,7 +61,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param scale the scale to use */ public void setScale(short scale) { - printSetupRecord.setScale(scale); + printSetupRecord.setScale(scale); } /** @@ -69,7 +69,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param start the page numbering start */ public void setPageStart(short start) { - printSetupRecord.setPageStart(start); + printSetupRecord.setPageStart(start); } /** @@ -77,7 +77,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param width the number of pages */ public void setFitWidth(short width) { - printSetupRecord.setFitWidth(width); + printSetupRecord.setFitWidth(width); } /** @@ -85,7 +85,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param height the number of pages */ public void setFitHeight(short height) { - printSetupRecord.setFitHeight(height); + printSetupRecord.setFitHeight(height); } /** @@ -93,7 +93,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param options The bit flags for the options */ public void setOptions(short options) { - printSetupRecord.setOptions(options); + printSetupRecord.setOptions(options); } /** @@ -101,7 +101,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param ltor left to right */ public void setLeftToRight(boolean ltor) { - printSetupRecord.setLeftToRight(ltor); + printSetupRecord.setLeftToRight(ltor); } /** @@ -109,7 +109,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param ls landscape */ public void setLandscape(boolean ls) { - printSetupRecord.setLandscape(!ls); + printSetupRecord.setLandscape(!ls); } /** @@ -117,7 +117,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param valid Valid */ public void setValidSettings(boolean valid) { - printSetupRecord.setValidSettings(valid); + printSetupRecord.setValidSettings(valid); } /** @@ -125,7 +125,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param mono Black and white */ public void setNoColor(boolean mono) { - printSetupRecord.setNoColor(mono); + printSetupRecord.setNoColor(mono); } /** @@ -133,7 +133,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param d draft */ public void setDraft(boolean d) { - printSetupRecord.setDraft(d); + printSetupRecord.setDraft(d); } /** @@ -141,7 +141,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param printnotes print the notes */ public void setNotes(boolean printnotes) { - printSetupRecord.setNotes(printnotes); + printSetupRecord.setNotes(printnotes); } /** @@ -149,7 +149,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param orientation Orientation. */ public void setNoOrientation(boolean orientation) { - printSetupRecord.setNoOrientation(orientation); + printSetupRecord.setNoOrientation(orientation); } /** @@ -157,7 +157,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param page Use page start */ public void setUsePage(boolean page) { - printSetupRecord.setUsePage(page); + printSetupRecord.setUsePage(page); } /** @@ -165,7 +165,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param resolution horizontal resolution */ public void setHResolution(short resolution) { - printSetupRecord.setHResolution(resolution); + printSetupRecord.setHResolution(resolution); } /** @@ -173,7 +173,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param resolution vertical resolution */ public void setVResolution(short resolution) { - printSetupRecord.setVResolution(resolution); + printSetupRecord.setVResolution(resolution); } /** @@ -181,7 +181,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param headermargin header margin */ public void setHeaderMargin(double headermargin) { - printSetupRecord.setHeaderMargin(headermargin); + printSetupRecord.setHeaderMargin(headermargin); } /** @@ -189,7 +189,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param footermargin footer margin */ public void setFooterMargin(double footermargin) { - printSetupRecord.setFooterMargin(footermargin); + printSetupRecord.setFooterMargin(footermargin); } /** @@ -197,7 +197,7 @@ public class HSSFPrintSetup implements PrintSetup { * @param copies number of copies */ public void setCopies(short copies) { - printSetupRecord.setCopies(copies); + printSetupRecord.setCopies(copies); } /** diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFRichTextString.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFRichTextString.java index fbb6eec534..e208fb3acb 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFRichTextString.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFRichTextString.java @@ -217,7 +217,7 @@ public final class HSSFRichTextString implements Comparable, * other RichTextStrings too! */ UnicodeString getRawUnicodeString() { - return _string; + return _string; } /** Used internally by the HSSFCell to set the internal string value*/ diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeFactory.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeFactory.java index c7dce30535..88c0a7d4d3 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeFactory.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFShapeFactory.java @@ -105,7 +105,7 @@ public class HSSFShapeFactory { case CommonObjectDataSubRecord.OBJECT_TYPE_MICROSOFT_OFFICE_DRAWING: EscherOptRecord optRecord = container.getChildById(EscherOptRecord.RECORD_ID); if(optRecord == null) { - shape = new HSSFSimpleShape(container, objRecord, txtRecord); + shape = new HSSFSimpleShape(container, objRecord, txtRecord); } else { EscherProperty property = optRecord.lookup(EscherPropertyTypes.GEOMETRY__VERTICES); if (null != property) { diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFSheetConditionalFormatting.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFSheetConditionalFormatting.java index 3f723de47f..69608bd0bd 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFSheetConditionalFormatting.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HSSFSheetConditionalFormatting.java @@ -48,16 +48,16 @@ public final class HSSFSheetConditionalFormatting implements SheetConditionalFor * TODO - formulas containing cell references are currently not parsed properly * * @param comparisonOperation - a constant value from - * {@code {@link org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator}}: + * {@code {@link org.apache.poi.hssf.record.CFRuleBase.ComparisonOperator}}: *

    - *
  • BETWEEN
  • - *
  • NOT_BETWEEN
  • - *
  • EQUAL
  • - *
  • NOT_EQUAL
  • - *
  • GT
  • - *
  • LT
  • - *
  • GE
  • - *
  • LE
  • + *
  • BETWEEN
  • + *
  • NOT_BETWEEN
  • + *
  • EQUAL
  • + *
  • NOT_EQUAL
  • + *
  • GT
  • + *
  • LT
  • + *
  • GE
  • + *
  • LE
  • *
* * @param formula1 - formula for the valued, compared with the cell @@ -247,7 +247,7 @@ public final class HSSFSheetConditionalFormatting implements SheetConditionalFor * gets Conditional Formatting object at a particular index * * @param index - * of the Conditional Formatting object to fetch + * of the Conditional Formatting object to fetch * @return Conditional Formatting object */ @Override diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/HeaderFooter.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/HeaderFooter.java index 38464490d6..1119c6c211 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/HeaderFooter.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/HeaderFooter.java @@ -23,325 +23,325 @@ package org.apache.poi.hssf.usermodel; */ public abstract class HeaderFooter implements org.apache.poi.ss.usermodel.HeaderFooter { - protected HeaderFooter() { - // - } - - /** - * @return the internal text representation (combining center, left and right parts). - * Possibly empty string if no header or footer is set. Never null. - */ - protected abstract String getRawText(); - - private String[] splitParts() { - String text = getRawText(); - // default values - String _left = ""; - String _center = ""; - String _right = ""; + protected HeaderFooter() { + // + } + + /** + * @return the internal text representation (combining center, left and right parts). + * Possibly empty string if no header or footer is set. Never null. + */ + protected abstract String getRawText(); + + private String[] splitParts() { + String text = getRawText(); + // default values + String _left = ""; + String _center = ""; + String _right = ""; // FIXME: replace outer goto. just eww. outer: - while (text.length() > 1) { - if (text.charAt(0) != '&') { - // Mimics the behaviour of Excel, which would put it in the center. - _center = text; - break; - } - int pos = text.length(); - switch (text.charAt(1)) { - case 'L': - if (text.contains("&C")) { - pos = Math.min(pos, text.indexOf("&C")); - } - if (text.contains("&R")) { - pos = Math.min(pos, text.indexOf("&R")); - } - _left = text.substring(2, pos); - text = text.substring(pos); - break; - case 'C': - if (text.contains("&L")) { - pos = Math.min(pos, text.indexOf("&L")); - } - if (text.contains("&R")) { - pos = Math.min(pos, text.indexOf("&R")); - } - _center = text.substring(2, pos); - text = text.substring(pos); - break; - case 'R': - if (text.contains("&C")) { - pos = Math.min(pos, text.indexOf("&C")); - } - if (text.contains("&L")) { - pos = Math.min(pos, text.indexOf("&L")); - } - _right = text.substring(2, pos); - text = text.substring(pos); - break; - default: - // Mimics the behaviour of Excel, which would put it in the center. - _center = text; - break outer; - } - } - return new String[] { _left, _center, _right, }; - } + while (text.length() > 1) { + if (text.charAt(0) != '&') { + // Mimics the behaviour of Excel, which would put it in the center. + _center = text; + break; + } + int pos = text.length(); + switch (text.charAt(1)) { + case 'L': + if (text.contains("&C")) { + pos = Math.min(pos, text.indexOf("&C")); + } + if (text.contains("&R")) { + pos = Math.min(pos, text.indexOf("&R")); + } + _left = text.substring(2, pos); + text = text.substring(pos); + break; + case 'C': + if (text.contains("&L")) { + pos = Math.min(pos, text.indexOf("&L")); + } + if (text.contains("&R")) { + pos = Math.min(pos, text.indexOf("&R")); + } + _center = text.substring(2, pos); + text = text.substring(pos); + break; + case 'R': + if (text.contains("&C")) { + pos = Math.min(pos, text.indexOf("&C")); + } + if (text.contains("&L")) { + pos = Math.min(pos, text.indexOf("&L")); + } + _right = text.substring(2, pos); + text = text.substring(pos); + break; + default: + // Mimics the behaviour of Excel, which would put it in the center. + _center = text; + break outer; + } + } + return new String[] { _left, _center, _right, }; + } - /** - * @return the left side of the header or footer. - */ - public final String getLeft() { - return splitParts()[0]; - } + /** + * @return the left side of the header or footer. + */ + public final String getLeft() { + return splitParts()[0]; + } - /** - * @param newLeft The string to set as the left side. - */ - public final void setLeft(String newLeft) { - updatePart(0, newLeft); - } + /** + * @param newLeft The string to set as the left side. + */ + public final void setLeft(String newLeft) { + updatePart(0, newLeft); + } - /** - * @return the center of the header or footer. - */ - public final String getCenter() { - return splitParts()[1]; - } + /** + * @return the center of the header or footer. + */ + public final String getCenter() { + return splitParts()[1]; + } - /** - * @param newCenter The string to set as the center. - */ - public final void setCenter(String newCenter) { - updatePart(1, newCenter); - } + /** + * @param newCenter The string to set as the center. + */ + public final void setCenter(String newCenter) { + updatePart(1, newCenter); + } - /** - * @return The right side of the header or footer. - */ - public final String getRight() { - return splitParts()[2]; - } + /** + * @return The right side of the header or footer. + */ + public final String getRight() { + return splitParts()[2]; + } - /** - * @param newRight The string to set as the right side. - */ - public final void setRight(String newRight) { - updatePart(2, newRight); - } - - private void updatePart(int partIndex, String newValue) { - String[] parts = splitParts(); - parts[partIndex] = newValue == null ? "" : newValue; - updateHeaderFooterText(parts); - } - /** - * Creates the complete footer string based on the left, center, and middle - * strings. - */ - private void updateHeaderFooterText(String[] parts) { - String _left = parts[0]; - String _center = parts[1]; - String _right = parts[2]; - - if (_center.length() < 1 && _left.length() < 1 && _right.length() < 1) { - setHeaderFooterText(""); - return; - } - StringBuilder sb = new StringBuilder(64); - sb.append("&C"); - sb.append(_center); - sb.append("&L"); - sb.append(_left); - sb.append("&R"); - sb.append(_right); - String text = sb.toString(); - setHeaderFooterText(text); - } + /** + * @param newRight The string to set as the right side. + */ + public final void setRight(String newRight) { + updatePart(2, newRight); + } + + private void updatePart(int partIndex, String newValue) { + String[] parts = splitParts(); + parts[partIndex] = newValue == null ? "" : newValue; + updateHeaderFooterText(parts); + } + /** + * Creates the complete footer string based on the left, center, and middle + * strings. + */ + private void updateHeaderFooterText(String[] parts) { + String _left = parts[0]; + String _center = parts[1]; + String _right = parts[2]; + + if (_center.length() < 1 && _left.length() < 1 && _right.length() < 1) { + setHeaderFooterText(""); + return; + } + StringBuilder sb = new StringBuilder(64); + sb.append("&C"); + sb.append(_center); + sb.append("&L"); + sb.append(_left); + sb.append("&R"); + sb.append(_right); + String text = sb.toString(); + setHeaderFooterText(text); + } - /** - * @param text the new header footer text (contains mark-up tags). Possibly - * empty string never null - */ - protected abstract void setHeaderFooterText(String text); + /** + * @param text the new header footer text (contains mark-up tags). Possibly + * empty string never null + */ + protected abstract void setHeaderFooterText(String text); - /** - * @param size - * the new font size - * @return The mark-up tag representing a new font size - */ - public static String fontSize(short size) { - return "&" + size; - } + /** + * @param size + * the new font size + * @return The mark-up tag representing a new font size + */ + public static String fontSize(short size) { + return "&" + size; + } - /** - * @param font - * the new font - * @param style - * the fonts style, one of regular, italic, bold, italic bold or - * bold italic - * @return The mark-up tag representing a new font size - */ - public static String font(String font, String style) { - return "&\"" + font + "," + style + "\""; - } + /** + * @param font + * the new font + * @param style + * the fonts style, one of regular, italic, bold, italic bold or + * bold italic + * @return The mark-up tag representing a new font size + */ + public static String font(String font, String style) { + return "&\"" + font + "," + style + "\""; + } - /** - * @return The mark-up tag representing the current page number - */ - public static String page() { - return MarkupTag.PAGE_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag representing the current page number + */ + public static String page() { + return MarkupTag.PAGE_FIELD.getRepresentation(); + } - /** - * @return The mark-up tag representing the number of pages - */ - public static String numPages() { - return MarkupTag.NUM_PAGES_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag representing the number of pages + */ + public static String numPages() { + return MarkupTag.NUM_PAGES_FIELD.getRepresentation(); + } - /** - * @return The mark-up tag representing the current date date - */ - public static String date() { - return MarkupTag.DATE_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag representing the current date date + */ + public static String date() { + return MarkupTag.DATE_FIELD.getRepresentation(); + } - /** - * @return The mark-up tag representing current time - */ - public static String time() { - return MarkupTag.TIME_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag representing current time + */ + public static String time() { + return MarkupTag.TIME_FIELD.getRepresentation(); + } - /** - * @return The mark-up tag representing the current file name - */ - public static String file() { - return MarkupTag.FILE_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag representing the current file name + */ + public static String file() { + return MarkupTag.FILE_FIELD.getRepresentation(); + } - /** - * @return The mark-up tag representing the current tab (sheet) name - */ - public static String tab() { - return MarkupTag.SHEET_NAME_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag representing the current tab (sheet) name + */ + public static String tab() { + return MarkupTag.SHEET_NAME_FIELD.getRepresentation(); + } - /** - * @return The mark-up tag for start bold - */ - public static String startBold() { - return MarkupTag.BOLD_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag for start bold + */ + public static String startBold() { + return MarkupTag.BOLD_FIELD.getRepresentation(); + } - /** - * @return The mark-up tag for end bold - */ - public static String endBold() { - return MarkupTag.BOLD_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag for end bold + */ + public static String endBold() { + return MarkupTag.BOLD_FIELD.getRepresentation(); + } - /** - * @return The mark-up tag for start underline - */ - public static String startUnderline() { - return MarkupTag.UNDERLINE_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag for start underline + */ + public static String startUnderline() { + return MarkupTag.UNDERLINE_FIELD.getRepresentation(); + } - /** - * @return The mark-up tag for end underline - */ - public static String endUnderline() { - return MarkupTag.UNDERLINE_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag for end underline + */ + public static String endUnderline() { + return MarkupTag.UNDERLINE_FIELD.getRepresentation(); + } - /** - * @return The mark-up tag for start double underline - */ - public static String startDoubleUnderline() { - return MarkupTag.DOUBLE_UNDERLINE_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag for start double underline + */ + public static String startDoubleUnderline() { + return MarkupTag.DOUBLE_UNDERLINE_FIELD.getRepresentation(); + } - /** - * @return The mark-up tag for end double underline - */ - public static String endDoubleUnderline() { - return MarkupTag.DOUBLE_UNDERLINE_FIELD.getRepresentation(); - } + /** + * @return The mark-up tag for end double underline + */ + public static String endDoubleUnderline() { + return MarkupTag.DOUBLE_UNDERLINE_FIELD.getRepresentation(); + } - /** - * Removes any fields (eg macros, page markers etc) from the string. - * Normally used to make some text suitable for showing to humans, and the - * resultant text should not normally be saved back into the document! - */ - public static String stripFields(String pText) { - int pos; + /** + * Removes any fields (eg macros, page markers etc) from the string. + * Normally used to make some text suitable for showing to humans, and the + * resultant text should not normally be saved back into the document! + */ + public static String stripFields(String pText) { + int pos; - // Check we really got something to work on - if (pText == null || pText.length() == 0) { - return pText; - } + // Check we really got something to work on + if (pText == null || pText.length() == 0) { + return pText; + } - String text = pText; + String text = pText; - // Firstly, do the easy ones which are static - for (MarkupTag mt : MarkupTag.values()) { - String seq = mt.getRepresentation(); - while ((pos = text.indexOf(seq)) >= 0) { - text = text.substring(0, pos) + text.substring(pos + seq.length()); - } - } + // Firstly, do the easy ones which are static + for (MarkupTag mt : MarkupTag.values()) { + String seq = mt.getRepresentation(); + while ((pos = text.indexOf(seq)) >= 0) { + text = text.substring(0, pos) + text.substring(pos + seq.length()); + } + } - // Now do the tricky, dynamic ones - // These are things like font sizes and font names - text = text.replaceAll("\\&\\d+", ""); - text = text.replaceAll("\\&\".*?,.*?\"", ""); + // Now do the tricky, dynamic ones + // These are things like font sizes and font names + text = text.replaceAll("\\&\\d+", ""); + text = text.replaceAll("\\&\".*?,.*?\"", ""); - // All done - return text; - } + // All done + return text; + } - private enum MarkupTag { - SHEET_NAME_FIELD ("&A", false), - DATE_FIELD ("&D", false), - FILE_FIELD ("&F", false), - FULL_FILE_FIELD ("&Z", false), - PAGE_FIELD ("&P", false), - TIME_FIELD ("&T", false), - NUM_PAGES_FIELD ("&N", false), + private enum MarkupTag { + SHEET_NAME_FIELD ("&A", false), + DATE_FIELD ("&D", false), + FILE_FIELD ("&F", false), + FULL_FILE_FIELD ("&Z", false), + PAGE_FIELD ("&P", false), + TIME_FIELD ("&T", false), + NUM_PAGES_FIELD ("&N", false), - PICTURE_FIELD ("&G", false), + PICTURE_FIELD ("&G", false), - BOLD_FIELD ("&B", true), - ITALIC_FIELD ("&I", true), - STRIKETHROUGH_FIELD ("&S", true), - SUBSCRIPT_FIELD ("&Y", true), - SUPERSCRIPT_FIELD ("&X", true), - UNDERLINE_FIELD ("&U", true), - DOUBLE_UNDERLINE_FIELD ("&E", true), - ; - - private final String _representation; - private final boolean _occursInPairs; - private MarkupTag(String sequence, boolean occursInPairs) { - _representation = sequence; - _occursInPairs = occursInPairs; - } - /** - * @return The character sequence that marks this field - */ - public String getRepresentation() { - return _representation; - } + BOLD_FIELD ("&B", true), + ITALIC_FIELD ("&I", true), + STRIKETHROUGH_FIELD ("&S", true), + SUBSCRIPT_FIELD ("&Y", true), + SUPERSCRIPT_FIELD ("&X", true), + UNDERLINE_FIELD ("&U", true), + DOUBLE_UNDERLINE_FIELD ("&E", true), + ; + + private final String _representation; + private final boolean _occursInPairs; + private MarkupTag(String sequence, boolean occursInPairs) { + _representation = sequence; + _occursInPairs = occursInPairs; + } + /** + * @return The character sequence that marks this field + */ + public String getRepresentation() { + return _representation; + } - /** - * @return true if this markup tag normally comes in a pair, eg turn on - * underline / turn off underline - */ - public boolean occursPairs() { - return _occursInPairs; - } - } + /** + * @return true if this markup tag normally comes in a pair, eg turn on + * underline / turn off underline + */ + public boolean occursPairs() { + return _occursInPairs; + } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java b/poi/src/main/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java index 453f3db384..6bf3b6ca87 100644 --- a/poi/src/main/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java +++ b/poi/src/main/java/org/apache/poi/hssf/usermodel/StaticFontMetrics.java @@ -38,69 +38,69 @@ import org.apache.logging.log4j.Logger; */ final class StaticFontMetrics { private static final Logger LOGGER = LogManager.getLogger(StaticFontMetrics.class); - /** The font metrics property file we're using */ - private static Properties fontMetricsProps; - /** Our cache of font details we've already looked up */ - private static final Map fontDetailsMap = new HashMap<>(); + /** The font metrics property file we're using */ + private static Properties fontMetricsProps; + /** Our cache of font details we've already looked up */ + private static final Map fontDetailsMap = new HashMap<>(); - private StaticFontMetrics() {} + private StaticFontMetrics() {} - /** - * Retrieves the fake font details for a given font. - * - * @param font - * the font to lookup. - * @return the fake font. - */ - public static synchronized FontDetails getFontDetails(Font font) { - // If we haven't already identified out font metrics file, - // figure out which one to use and load it - if (fontMetricsProps == null) { - try { - fontMetricsProps = loadMetrics(); - } catch (IOException e) { - throw new RuntimeException("Could not load font metrics", e); - } - } + /** + * Retrieves the fake font details for a given font. + * + * @param font + * the font to lookup. + * @return the fake font. + */ + public static synchronized FontDetails getFontDetails(Font font) { + // If we haven't already identified out font metrics file, + // figure out which one to use and load it + if (fontMetricsProps == null) { + try { + fontMetricsProps = loadMetrics(); + } catch (IOException e) { + throw new RuntimeException("Could not load font metrics", e); + } + } - // Grab the base name of the font they've asked about - String fontName = font.getName(); + // Grab the base name of the font they've asked about + String fontName = font.getName(); - // Some fonts support plain/bold/italic/bolditalic variants - // Others have different font instances for bold etc - // (eg font.dialog.plain.* vs font.Californian FB Bold.*) - String fontStyle = ""; - if (font.isPlain()) { - fontStyle += "plain"; - } - if (font.isBold()) { - fontStyle += "bold"; - } - if (font.isItalic()) { - fontStyle += "italic"; - } + // Some fonts support plain/bold/italic/bolditalic variants + // Others have different font instances for bold etc + // (eg font.dialog.plain.* vs font.Californian FB Bold.*) + String fontStyle = ""; + if (font.isPlain()) { + fontStyle += "plain"; + } + if (font.isBold()) { + fontStyle += "bold"; + } + if (font.isItalic()) { + fontStyle += "italic"; + } - // Do we have a definition for this font with just the name? - // If not, check with the font style added - String fontHeight = FontDetails.buildFontHeightProperty(fontName); - String styleHeight = FontDetails.buildFontHeightProperty(fontName + "." + fontStyle); + // Do we have a definition for this font with just the name? + // If not, check with the font style added + String fontHeight = FontDetails.buildFontHeightProperty(fontName); + String styleHeight = FontDetails.buildFontHeightProperty(fontName + "." + fontStyle); - if (fontMetricsProps.get(fontHeight) == null - && fontMetricsProps.get(styleHeight) != null) { - // Need to add on the style to the font name - fontName += "." + fontStyle; - } + if (fontMetricsProps.get(fontHeight) == null + && fontMetricsProps.get(styleHeight) != null) { + // Need to add on the style to the font name + fontName += "." + fontStyle; + } - // Get the details on this font - FontDetails fontDetails = fontDetailsMap.get(fontName); - if (fontDetails == null) { - fontDetails = FontDetails.create(fontName, fontMetricsProps); - fontDetailsMap.put(fontName, fontDetails); - } + // Get the details on this font + FontDetails fontDetails = fontDetailsMap.get(fontName); + if (fontDetails == null) { + fontDetails = FontDetails.create(fontName, fontMetricsProps); + fontDetailsMap.put(fontName, fontDetails); + } return fontDetails; - } + } - private static Properties loadMetrics() throws IOException { + private static Properties loadMetrics() throws IOException { // Check to see if the font metric file was specified // as a system property File propFile = null; @@ -109,7 +109,7 @@ final class StaticFontMetrics { if (propFileName != null) { propFile = new File(propFileName); if (!propFile.exists()) { - LOGGER.atWarn().log("font_metrics.properties not found at path {}", propFile.getAbsolutePath()); + LOGGER.atWarn().log("font_metrics.properties not found at path {}", propFile.getAbsolutePath()); propFile = null; } } @@ -118,18 +118,18 @@ final class StaticFontMetrics { } try (InputStream metricsIn = (propFile != null) - ? new FileInputStream(propFile) - : FontDetails.class.getResourceAsStream("/font_metrics.properties") - ) { - // Use the built-in font metrics file off the classpath - if (metricsIn == null) { - String err = "font_metrics.properties not found in classpath"; - throw new IOException(err); - } + ? new FileInputStream(propFile) + : FontDetails.class.getResourceAsStream("/font_metrics.properties") + ) { + // Use the built-in font metrics file off the classpath + if (metricsIn == null) { + String err = "font_metrics.properties not found in classpath"; + throw new IOException(err); + } Properties props = new Properties(); props.load(metricsIn); return props; } - } + } } diff --git a/poi/src/main/java/org/apache/poi/hssf/util/CellRangeAddress8Bit.java b/poi/src/main/java/org/apache/poi/hssf/util/CellRangeAddress8Bit.java index c70e525667..a3d53894c0 100644 --- a/poi/src/main/java/org/apache/poi/hssf/util/CellRangeAddress8Bit.java +++ b/poi/src/main/java/org/apache/poi/hssf/util/CellRangeAddress8Bit.java @@ -28,37 +28,37 @@ import org.apache.poi.util.LittleEndianOutput; */ public final class CellRangeAddress8Bit extends CellRangeAddressBase { - public static final int ENCODED_SIZE = 6; + public static final int ENCODED_SIZE = 6; - public CellRangeAddress8Bit(int firstRow, int lastRow, int firstCol, int lastCol) { - super(firstRow, lastRow, firstCol, lastCol); - } + public CellRangeAddress8Bit(int firstRow, int lastRow, int firstCol, int lastCol) { + super(firstRow, lastRow, firstCol, lastCol); + } - public CellRangeAddress8Bit(LittleEndianInput in) { - super(readUShortAndCheck(in), in.readUShort(), in.readUByte(), in.readUByte()); - } + public CellRangeAddress8Bit(LittleEndianInput in) { + super(readUShortAndCheck(in), in.readUShort(), in.readUByte(), in.readUByte()); + } - private static int readUShortAndCheck(LittleEndianInput in) { - if (in.available() < ENCODED_SIZE) { - // Ran out of data - throw new RuntimeException("Ran out of data reading CellRangeAddress"); - } - return in.readUShort(); - } + private static int readUShortAndCheck(LittleEndianInput in) { + if (in.available() < ENCODED_SIZE) { + // Ran out of data + throw new RuntimeException("Ran out of data reading CellRangeAddress"); + } + return in.readUShort(); + } - public void serialize(LittleEndianOutput out) { - out.writeShort(getFirstRow()); - out.writeShort(getLastRow()); - out.writeByte(getFirstColumn()); - out.writeByte(getLastColumn()); - } + public void serialize(LittleEndianOutput out) { + out.writeShort(getFirstRow()); + out.writeShort(getLastRow()); + out.writeByte(getFirstColumn()); + out.writeByte(getLastColumn()); + } - @Override - public CellRangeAddress8Bit copy() { - return new CellRangeAddress8Bit(getFirstRow(), getLastRow(), getFirstColumn(), getLastColumn()); - } + @Override + public CellRangeAddress8Bit copy() { + return new CellRangeAddress8Bit(getFirstRow(), getLastRow(), getFirstColumn(), getLastColumn()); + } - public static int getEncodedSize(int numberOfItems) { - return numberOfItems * ENCODED_SIZE; - } + public static int getEncodedSize(int numberOfItems) { + return numberOfItems * ENCODED_SIZE; + } } diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/EncryptionHeader.java b/poi/src/main/java/org/apache/poi/poifs/crypt/EncryptionHeader.java index b39ec150cd..8543d6828c 100644 --- a/poi/src/main/java/org/apache/poi/poifs/crypt/EncryptionHeader.java +++ b/poi/src/main/java/org/apache/poi/poifs/crypt/EncryptionHeader.java @@ -119,7 +119,7 @@ public abstract class EncryptionHeader implements GenericRecord, Duplicatable { } public int getBlockSize() { - return blockSize; + return blockSize; } public void setBlockSize(int blockSize) { diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/Encryptor.java b/poi/src/main/java/org/apache/poi/poifs/crypt/Encryptor.java index 9c2041d72a..d6af6d44f7 100644 --- a/poi/src/main/java/org/apache/poi/poifs/crypt/Encryptor.java +++ b/poi/src/main/java/org/apache/poi/poifs/crypt/Encryptor.java @@ -57,8 +57,8 @@ public abstract class Encryptor implements GenericRecord { public abstract void confirmPassword(String password); - public static Encryptor getInstance(EncryptionInfo info) { - return info.getEncryptor(); + public static Encryptor getInstance(EncryptionInfo info) { + return info.getEncryptor(); } public OutputStream getDataStream(POIFSFileSystem fs) throws IOException, GeneralSecurityException { diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/HashAlgorithm.java b/poi/src/main/java/org/apache/poi/poifs/crypt/HashAlgorithm.java index b4618dc0b5..10daa97b01 100644 --- a/poi/src/main/java/org/apache/poi/poifs/crypt/HashAlgorithm.java +++ b/poi/src/main/java/org/apache/poi/poifs/crypt/HashAlgorithm.java @@ -39,10 +39,10 @@ public enum HashAlgorithm { ; /** the id used for initializing the JCE message digest **/ - public final String jceId; - /** the id used for the BIFF encryption info header **/ - public final int ecmaId; - /** the id used for OOXML encryption info header **/ + public final String jceId; + /** the id used for the BIFF encryption info header **/ + public final int ecmaId; + /** the id used for OOXML encryption info header **/ public final String ecmaString; /** the length of the digest byte array **/ public final int hashSize; diff --git a/poi/src/main/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java b/poi/src/main/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java index 9200fb3830..97e172915e 100644 --- a/poi/src/main/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java +++ b/poi/src/main/java/org/apache/poi/poifs/crypt/agile/AgileEncryptor.java @@ -73,12 +73,12 @@ public class AgileEncryptor extends Encryptor { private byte[] integritySalt; private byte[] pwHash; - protected AgileEncryptor() {} + protected AgileEncryptor() {} protected AgileEncryptor(AgileEncryptor other) { - super(other); - integritySalt = (other.integritySalt == null) ? null : other.integritySalt.clone(); - pwHash = (other.pwHash == null) ? null : other.pwHash.clone(); + super(other); + integritySalt = (other.integritySalt == null) ? null : other.integritySalt.clone(); + pwHash = (other.pwHash == null) ? null : other.pwHash.clone(); } @Override @@ -104,7 +104,7 @@ public class AgileEncryptor extends Encryptor { confirmPassword(password, newKeySpec, newKeySalt, newVerifierSalt, newVerifier, newIntegritySalt); } - @Override + @Override public void confirmPassword(String password, byte[] keySpec, byte[] keySalt, byte[] verifier, byte[] verifierSalt, byte[] integritySalt) { AgileEncryptionVerifier ver = (AgileEncryptionVerifier)getEncryptionInfo().getVerifier(); AgileEncryptionHeader header = (AgileEncryptionHeader)getEncryptionInfo().getHeader(); @@ -204,7 +204,7 @@ public class AgileEncryptor extends Encryptor { } catch (GeneralSecurityException e) { throw new EncryptedDocumentException(e); } - } + } @Override public OutputStream getDataStream(DirectoryNode dir) diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentInputStream.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentInputStream.java index bf07261ef9..86b9fcd492 100644 --- a/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentInputStream.java +++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentInputStream.java @@ -201,72 +201,72 @@ public final class DocumentInputStream extends InputStream implements LittleEndi // Start again, then wind on to the required block _data = _document.getBlockIterator(); _current_offset = 0; - for(int i=0; i<_marked_offset_count; i++) { - _buffer = _data.next(); - _current_offset += _buffer.remaining(); - } + for(int i=0; i<_marked_offset_count; i++) { + _buffer = _data.next(); + _current_offset += _buffer.remaining(); + } _current_block_count = _marked_offset_count; // Do we need to position within it? if(_current_offset != _marked_offset) { - // Grab the right block + // Grab the right block _buffer = _data.next(); _current_block_count++; - // Skip to the right place in it + // Skip to the right place in it // (It should be positioned already at the start of the block, // we need to move further inside the block) int skipBy = _marked_offset - _current_offset; - _buffer.position(_buffer.position() + skipBy); + _buffer.position(_buffer.position() + skipBy); } // All done _current_offset = _marked_offset; - } + } @Override - public long skip(long n) throws IOException { - dieIfClosed(); - if (n < 0) { - return 0; - } - long new_offset = _current_offset + n; + public long skip(long n) throws IOException { + dieIfClosed(); + if (n < 0) { + return 0; + } + long new_offset = _current_offset + n; - if (new_offset < _current_offset) { - // wrap around in converting a VERY large long to an int - new_offset = _document_size; - } else if (new_offset > _document_size) { - new_offset = _document_size; - } + if (new_offset < _current_offset) { + // wrap around in converting a VERY large long to an int + new_offset = _document_size; + } else if (new_offset > _document_size) { + new_offset = _document_size; + } - long rval = new_offset - _current_offset; + long rval = new_offset - _current_offset; - // TODO Do this better - byte[] skip = IOUtils.safelyAllocate(rval, Integer.MAX_VALUE); - readFully(skip); - return rval; - } + // TODO Do this better + byte[] skip = IOUtils.safelyAllocate(rval, Integer.MAX_VALUE); + readFully(skip); + return rval; + } - private void dieIfClosed() throws IOException { - if (_closed) { - throw new IOException("cannot perform requested operation on a closed stream"); - } - } + private void dieIfClosed() throws IOException { + if (_closed) { + throw new IOException("cannot perform requested operation on a closed stream"); + } + } - private boolean atEOD() { - return _current_offset == _document_size; - } + private boolean atEOD() { + return _current_offset == _document_size; + } - private void checkAvaliable(int requestedSize) { - if (_closed) { - throw new IllegalStateException("cannot perform requested operation on a closed stream"); - } - if (requestedSize > _document_size - _current_offset) { - throw new RuntimeException("Buffer underrun - requested " + requestedSize - + " bytes but " + (_document_size - _current_offset) + " was available"); - } - } + private void checkAvaliable(int requestedSize) { + if (_closed) { + throw new IllegalStateException("cannot perform requested operation on a closed stream"); + } + if (requestedSize > _document_size - _current_offset) { + throw new RuntimeException("Buffer underrun - requested " + requestedSize + + " bytes but " + (_document_size - _current_offset) + " was available"); + } + } @Override public void readFully(byte[] buf) { @@ -274,26 +274,26 @@ public final class DocumentInputStream extends InputStream implements LittleEndi } @Override - public void readFully(byte[] buf, int off, int len) { + public void readFully(byte[] buf, int off, int len) { if (len < 0) { throw new RuntimeException("Can't read negative number of bytes"); } - checkAvaliable(len); + checkAvaliable(len); - int read = 0; - while(read < len) { - if(_buffer == null || _buffer.remaining() == 0) { - _current_block_count++; - _buffer = _data.next(); - } + int read = 0; + while(read < len) { + if(_buffer == null || _buffer.remaining() == 0) { + _current_block_count++; + _buffer = _data.next(); + } - int limit = Math.min(len-read, _buffer.remaining()); - _buffer.get(buf, off+read, limit); + int limit = Math.min(len-read, _buffer.remaining()); + _buffer.get(buf, off+read, limit); _current_offset += limit; - read += limit; - } - } + read += limit; + } + } @Override public void readPlain(byte[] buf, int off, int len) { @@ -312,12 +312,12 @@ public final class DocumentInputStream extends InputStream implements LittleEndi } @Override - public long readLong() { - checkAvaliable(LONG_SIZE); - byte[] data = new byte[LONG_SIZE]; - readFully(data, 0, LONG_SIZE); - return LittleEndian.getLong(data, 0); - } + public long readLong() { + checkAvaliable(LONG_SIZE); + byte[] data = new byte[LONG_SIZE]; + readFully(data, 0, LONG_SIZE); + return LittleEndian.getLong(data, 0); + } @Override public short readShort() { @@ -328,12 +328,12 @@ public final class DocumentInputStream extends InputStream implements LittleEndi } @Override - public int readInt() { - checkAvaliable(INT_SIZE); + public int readInt() { + checkAvaliable(INT_SIZE); byte[] data = new byte[INT_SIZE]; readFully(data, 0, INT_SIZE); return LittleEndian.getInt(data); - } + } public long readUInt() { int i = readInt(); @@ -341,12 +341,12 @@ public final class DocumentInputStream extends InputStream implements LittleEndi } @Override - public int readUShort() { - checkAvaliable(SHORT_SIZE); + public int readUShort() { + checkAvaliable(SHORT_SIZE); byte[] data = new byte[SHORT_SIZE]; readFully(data, 0, SHORT_SIZE); return LittleEndian.getUShort(data); - } + } @Override public int readUByte() { diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java index f8b948ee38..ec15c11446 100644 --- a/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java +++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/DocumentOutputStream.java @@ -30,48 +30,48 @@ import org.apache.poi.poifs.property.DocumentProperty; * {@link POIFSFileSystem} instance. */ public final class DocumentOutputStream extends OutputStream { - /** the Document's size, i.e. the size of the big block data - mini block data is cached and not counted */ - private int _document_size = 0; + /** the Document's size, i.e. the size of the big block data - mini block data is cached and not counted */ + private int _document_size = 0; /** have we been closed? */ - private boolean _closed = false; + private boolean _closed = false; - /** the actual Document */ - private final POIFSDocument _document; - /** and its Property */ - private final DocumentProperty _property; + /** the actual Document */ + private final POIFSDocument _document; + /** and its Property */ + private final DocumentProperty _property; - /** our buffer, when null we're into normal blocks */ - private UnsynchronizedByteArrayOutputStream _buffer = - new UnsynchronizedByteArrayOutputStream(POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE); + /** our buffer, when null we're into normal blocks */ + private UnsynchronizedByteArrayOutputStream _buffer = + new UnsynchronizedByteArrayOutputStream(POIFSConstants.BIG_BLOCK_MINIMUM_DOCUMENT_SIZE); - /** our main block stream, when we're into normal blocks */ - private POIFSStream _stream; - private OutputStream _stream_output; + /** our main block stream, when we're into normal blocks */ + private POIFSStream _stream; + private OutputStream _stream_output; /** a write limit or -1 if unlimited */ private final long _limit; - /** - * Create an OutputStream from the specified DocumentEntry. - * The specified entry will be emptied. - * - * @param document the DocumentEntry to be written - */ - public DocumentOutputStream(DocumentEntry document) throws IOException { - this(document, -1); - } + /** + * Create an OutputStream from the specified DocumentEntry. + * The specified entry will be emptied. + * + * @param document the DocumentEntry to be written + */ + public DocumentOutputStream(DocumentEntry document) throws IOException { + this(document, -1); + } /** - * Create an OutputStream to create the specified new Entry - * - * @param parent Where to create the Entry - * @param name Name of the new entry - */ - public DocumentOutputStream(DirectoryEntry parent, String name) throws IOException { - this(createDocument(parent, name), -1); - } + * Create an OutputStream to create the specified new Entry + * + * @param parent Where to create the Entry + * @param name Name of the new entry + */ + public DocumentOutputStream(DirectoryEntry parent, String name) throws IOException { + this(createDocument(parent, name), -1); + } /** * Create a DocumentOutputStream @@ -169,6 +169,6 @@ public final class DocumentOutputStream extends OutputStream { * @return the amount of written bytes */ public long size() { - return _document_size + (_buffer == null ? 0L : _buffer.size()); + return _document_size + (_buffer == null ? 0L : _buffer.size()); } } \ No newline at end of file diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java index 81dd891a8c..b6a24873c3 100644 --- a/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java +++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/EntryUtils.java @@ -41,7 +41,7 @@ public final class EntryUtils { public static void copyNodeRecursively( Entry entry, DirectoryEntry target ) throws IOException { if ( entry.isDirectoryEntry() ) { - DirectoryEntry dirEntry = (DirectoryEntry)entry; + DirectoryEntry dirEntry = (DirectoryEntry)entry; DirectoryEntry newTarget = target.createDirectory( entry.getName() ); newTarget.setStorageClsid( dirEntry.getStorageClsid() ); Iterator entries = dirEntry.getEntries(); diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/NotOLE2FileException.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/NotOLE2FileException.java index 18387cfb77..f23c327601 100644 --- a/poi/src/main/java/org/apache/poi/poifs/filesystem/NotOLE2FileException.java +++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/NotOLE2FileException.java @@ -24,7 +24,7 @@ import java.io.IOException; * seem to actually be an OLE2 file after all */ public class NotOLE2FileException extends IOException { - public NotOLE2FileException(String s) { - super(s); - } + public NotOLE2FileException(String s) { + super(s); + } } diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/OfficeXmlFileException.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/OfficeXmlFileException.java index ac2404b72a..2ec0d2b77b 100644 --- a/poi/src/main/java/org/apache/poi/poifs/filesystem/OfficeXmlFileException.java +++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/OfficeXmlFileException.java @@ -25,7 +25,7 @@ import org.apache.poi.UnsupportedFileFormatException; * POIFS works with) */ public class OfficeXmlFileException extends UnsupportedFileFormatException { - public OfficeXmlFileException(String s) { - super(s); - } + public OfficeXmlFileException(String s) { + super(s); + } } diff --git a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSDocument.java b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSDocument.java index 05881561b1..2dfb4c3c62 100644 --- a/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSDocument.java +++ b/poi/src/main/java/org/apache/poi/poifs/filesystem/POIFSDocument.java @@ -48,7 +48,7 @@ public final class POIFSDocument implements POIFSViewable, Iterable private POIFSFileSystem _filesystem; private POIFSStream _stream; private int _block_size; - + /** * Constructor for an existing Document */ @@ -232,7 +232,7 @@ public final class POIFSDocument implements POIFSViewable, Iterable * Get an Iterator of objects, some of which may implement POIFSViewable * * @return an Iterator; may not be null, but may have an empty back end - * store + * store */ public Iterator getViewableIterator() { return emptyIterator(); @@ -243,7 +243,7 @@ public final class POIFSDocument implements POIFSViewable, Iterable * getViewableIterator * * @return true if a viewer should call getViewableArray, - * false if a viewer should call getViewableIterator + * false if a viewer should call getViewableIterator */ public boolean preferArray() { return true; diff --git a/poi/src/main/java/org/apache/poi/poifs/storage/HeaderBlock.java b/poi/src/main/java/org/apache/poi/poifs/storage/HeaderBlock.java index 24b1a99008..190afb71dc 100644 --- a/poi/src/main/java/org/apache/poi/poifs/storage/HeaderBlock.java +++ b/poi/src/main/java/org/apache/poi/poifs/storage/HeaderBlock.java @@ -42,135 +42,135 @@ import org.apache.poi.util.ShortField; */ public final class HeaderBlock implements HeaderBlockConstants { - //arbitrarily selected; may need to increase - private static final int MAX_RECORD_LENGTH = 100_000; + //arbitrarily selected; may need to increase + private static final int MAX_RECORD_LENGTH = 100_000; - private static final byte _default_value = ( byte ) 0xFF; + private static final byte _default_value = ( byte ) 0xFF; /** - * What big block size the file uses. Most files - * use 512 bytes, but a few use 4096 - */ - private final POIFSBigBlockSize bigBlockSize; + * What big block size the file uses. Most files + * use 512 bytes, but a few use 4096 + */ + private final POIFSBigBlockSize bigBlockSize; - /** - * Number of big block allocation table blocks (int). - * (Number of FAT Sectors in Microsoft parlance). - */ - private int _bat_count; + /** + * Number of big block allocation table blocks (int). + * (Number of FAT Sectors in Microsoft parlance). + */ + private int _bat_count; - /** - * Start of the property set block (int index of the property set - * chain's first big block). - */ - private int _property_start; + /** + * Start of the property set block (int index of the property set + * chain's first big block). + */ + private int _property_start; - /** - * start of the small block allocation table (int index of small - * block allocation table's first big block) - */ - private int _sbat_start; - /** - * Number of small block allocation table blocks (int) - * (Number of MiniFAT Sectors in Microsoft parlance) - */ - private int _sbat_count; + /** + * start of the small block allocation table (int index of small + * block allocation table's first big block) + */ + private int _sbat_start; + /** + * Number of small block allocation table blocks (int) + * (Number of MiniFAT Sectors in Microsoft parlance) + */ + private int _sbat_count; - /** - * Big block index for extension to the big block allocation table - */ - private int _xbat_start; - /** - * Number of big block allocation table blocks (int) - * (Number of DIFAT Sectors in Microsoft parlance) - */ - private int _xbat_count; - - /** - * The data. Only ever 512 bytes, because 4096 byte - * files use zeros for the extra header space. - */ - private final byte[] _data; - - /** - * create a new HeaderBlockReader from an InputStream - * - * @param stream the source InputStream - * - * @exception IOException on errors or bad data - */ - public HeaderBlock(InputStream stream) throws IOException { - // Grab the first 512 bytes - // (For 4096 sized blocks, the remaining 3584 bytes are zero) - // Then, process the contents - this(readFirst512(stream)); - - // Fetch the rest of the block if needed - if(bigBlockSize.getBigBlockSize() != 512) { - int rest = bigBlockSize.getBigBlockSize() - 512; - byte[] tmp = IOUtils.safelyAllocate(rest, MAX_RECORD_LENGTH); - IOUtils.readFully(stream, tmp); - } - } - - public HeaderBlock(ByteBuffer buffer) throws IOException { - this(IOUtils.toByteArray(buffer, POIFSConstants.SMALLER_BIG_BLOCK_SIZE)); - } - - private HeaderBlock(byte[] data) throws IOException { - this._data = data.clone(); - - // verify signature - FileMagic fm = FileMagic.valueOf(data); - - switch (fm) { - case OLE2: - break; - case OOXML: + /** + * Big block index for extension to the big block allocation table + */ + private int _xbat_start; + /** + * Number of big block allocation table blocks (int) + * (Number of DIFAT Sectors in Microsoft parlance) + */ + private int _xbat_count; + + /** + * The data. Only ever 512 bytes, because 4096 byte + * files use zeros for the extra header space. + */ + private final byte[] _data; + + /** + * create a new HeaderBlockReader from an InputStream + * + * @param stream the source InputStream + * + * @exception IOException on errors or bad data + */ + public HeaderBlock(InputStream stream) throws IOException { + // Grab the first 512 bytes + // (For 4096 sized blocks, the remaining 3584 bytes are zero) + // Then, process the contents + this(readFirst512(stream)); + + // Fetch the rest of the block if needed + if(bigBlockSize.getBigBlockSize() != 512) { + int rest = bigBlockSize.getBigBlockSize() - 512; + byte[] tmp = IOUtils.safelyAllocate(rest, MAX_RECORD_LENGTH); + IOUtils.readFully(stream, tmp); + } + } + + public HeaderBlock(ByteBuffer buffer) throws IOException { + this(IOUtils.toByteArray(buffer, POIFSConstants.SMALLER_BIG_BLOCK_SIZE)); + } + + private HeaderBlock(byte[] data) throws IOException { + this._data = data.clone(); + + // verify signature + FileMagic fm = FileMagic.valueOf(data); + + switch (fm) { + case OLE2: + break; + case OOXML: throw new OfficeXmlFileException("The supplied data appears to be in the Office 2007+ XML. " + "You are calling the part of POI that deals with OLE2 Office Documents. " + "You need to call a different part of POI to process this data (eg XSSF instead of HSSF)"); - case XML: + case XML: throw new NotOLE2FileException("The supplied data appears to be a raw XML file. " + "Formats such as Office 2003 XML are not supported"); - case MSWRITE: + case MSWRITE: throw new NotOLE2FileException("The supplied data appears to be in the old MS Write format. " + "Apache POI doesn't currently support this format"); - case WORD2: - throw new NotOLE2FileException("The supplied data appears to be an old Word version 2 file. " - + "Apache POI doesn't currently support this format"); + case WORD2: + throw new NotOLE2FileException("The supplied data appears to be an old Word version 2 file. " + + "Apache POI doesn't currently support this format"); case BIFF2: case BIFF3: case BIFF4: throw new OldExcelFormatException("The supplied data appears to be in "+fm+" format. " + "HSSF only supports the BIFF8 format, try OldExcelExtractor"); - default: + default: // Give a generic error if the OLE2 signature isn't found - String exp = HexDump.longToHex(_signature); - String act = HexDump.longToHex(LittleEndian.getLong(data, 0)); + String exp = HexDump.longToHex(_signature); + String act = HexDump.longToHex(LittleEndian.getLong(data, 0)); throw new NotOLE2FileException( "Invalid header signature; read " + act + ", expected " + exp + " - Your file appears not to be a valid OLE2 document"); - } - - // Figure out our block size - if (_data[30] == 12) { - this.bigBlockSize = POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS; - } else if(_data[30] == 9) { - this.bigBlockSize = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS; - } else { - throw new IOException("Unsupported blocksize (2^"+ _data[30] + "). Expected 2^9 or 2^12."); - } + } + + // Figure out our block size + if (_data[30] == 12) { + this.bigBlockSize = POIFSConstants.LARGER_BIG_BLOCK_SIZE_DETAILS; + } else if(_data[30] == 9) { + this.bigBlockSize = POIFSConstants.SMALLER_BIG_BLOCK_SIZE_DETAILS; + } else { + throw new IOException("Unsupported blocksize (2^"+ _data[30] + "). Expected 2^9 or 2^12."); + } - // Setup the fields to read and write the counts and starts + // Setup the fields to read and write the counts and starts _bat_count = new IntegerField(_bat_count_offset, data).get(); _property_start = new IntegerField(_property_start_offset,_data).get(); _sbat_start = new IntegerField(_sbat_start_offset, _data).get(); _sbat_count = new IntegerField(_sbat_block_count_offset, _data).get(); _xbat_start = new IntegerField(_xbat_start_offset, _data).get(); _xbat_count = new IntegerField(_xbat_count_offset, _data).get(); - } - + } + /** * Create a single instance initialized with default values */ @@ -208,7 +208,7 @@ public final class HeaderBlock implements HeaderBlockConstants { _xbat_start = POIFSConstants.END_OF_CHAIN; } - private static byte[] readFirst512(InputStream stream) throws IOException { + private static byte[] readFirst512(InputStream stream) throws IOException { // Grab the first 512 bytes // (For 4096 sized blocks, the remaining 3584 bytes are zero) byte[] data = new byte[512]; @@ -217,30 +217,30 @@ public final class HeaderBlock implements HeaderBlockConstants { throw alertShortRead(bsCount); } return data; - } + } - private static IOException alertShortRead(int pRead) { - int read; - if (pRead < 0) { - //Can't have -1 bytes read in the error message! - read = 0; - } else { - read = pRead; - } - String type = " byte" + (read == 1 ? (""): ("s")); + private static IOException alertShortRead(int pRead) { + int read; + if (pRead < 0) { + //Can't have -1 bytes read in the error message! + read = 0; + } else { + read = pRead; + } + String type = " byte" + (read == 1 ? (""): ("s")); - return new IOException("Unable to read entire header; " - + read + type + " read; expected 512 bytes"); - } + return new IOException("Unable to read entire header; " + + read + type + " read; expected 512 bytes"); + } - /** - * get start of Property Table - * - * @return the index of the first block of the Property Table - */ - public int getPropertyStart() { - return _property_start; - } + /** + * get start of Property Table + * + * @return the index of the first block of the Property Table + */ + public int getPropertyStart() { + return _property_start; + } /** * Set start of Property Table * @@ -250,16 +250,16 @@ public final class HeaderBlock implements HeaderBlockConstants { _property_start = startBlock; } - /** - * @return start of small block (MiniFAT) allocation table - */ - public int getSBATStart() { - return _sbat_start; - } - public int getSBATCount() { - return _sbat_count; - } - + /** + * @return start of small block (MiniFAT) allocation table + */ + public int getSBATStart() { + return _sbat_start; + } + public int getSBATCount() { + return _sbat_count; + } + /** * Set start of small block allocation table * @@ -279,12 +279,12 @@ public final class HeaderBlock implements HeaderBlockConstants { _sbat_count = count; } - /** - * @return number of BAT blocks - */ - public int getBATCount() { - return _bat_count; - } + /** + * @return number of BAT blocks + */ + public int getBATCount() { + return _bat_count; + } /** * Sets the number of BAT blocks that are used. * This is the number used in both the BAT and XBAT. @@ -293,75 +293,75 @@ public final class HeaderBlock implements HeaderBlockConstants { _bat_count = count; } - /** - * Returns the offsets to the first (up to) 109 - * BAT sectors. - * Any additional BAT sectors are held in the XBAT (DIFAT) - * sectors in a chain. - * @return BAT offset array - */ - public int[] getBATArray() { + /** + * Returns the offsets to the first (up to) 109 + * BAT sectors. + * Any additional BAT sectors are held in the XBAT (DIFAT) + * sectors in a chain. + * @return BAT offset array + */ + public int[] getBATArray() { // Read them in - int[] result = new int[ Math.min(_bat_count,_max_bats_in_header) ]; - int offset = _bat_array_offset; - for (int j = 0; j < result.length; j++) { - result[ j ] = LittleEndian.getInt(_data, offset); - offset += LittleEndianConsts.INT_SIZE; - } - return result; - } - /** - * Sets the offsets of the first (up to) 109 - * BAT sectors. - */ - public void setBATArray(int[] bat_array) { - int count = Math.min(bat_array.length, _max_bats_in_header); - int blank = _max_bats_in_header - count; - + int[] result = new int[ Math.min(_bat_count,_max_bats_in_header) ]; + int offset = _bat_array_offset; + for (int j = 0; j < result.length; j++) { + result[ j ] = LittleEndian.getInt(_data, offset); + offset += LittleEndianConsts.INT_SIZE; + } + return result; + } + /** + * Sets the offsets of the first (up to) 109 + * BAT sectors. + */ + public void setBATArray(int[] bat_array) { + int count = Math.min(bat_array.length, _max_bats_in_header); + int blank = _max_bats_in_header - count; + int offset = _bat_array_offset; - for(int i=0; i, P extends TextParagraph > extends Sheet { - /** - * Return the placeholder shape for the specified type - * - * @return the shape or {@code null} if it is not defined in this mastersheet - * - * @since POI 4.0.0 - */ + /** + * Return the placeholder shape for the specified type + * + * @return the shape or {@code null} if it is not defined in this mastersheet + * + * @since POI 4.0.0 + */ SimpleShape getPlaceholder(Placeholder type); } diff --git a/poi/src/main/java/org/apache/poi/sl/usermodel/Notes.java b/poi/src/main/java/org/apache/poi/sl/usermodel/Notes.java index 377ad24c40..fc289ae124 100644 --- a/poi/src/main/java/org/apache/poi/sl/usermodel/Notes.java +++ b/poi/src/main/java/org/apache/poi/sl/usermodel/Notes.java @@ -23,5 +23,5 @@ public interface Notes< S extends Shape, P extends TextParagraph > extends Sheet { - List> getTextParagraphs(); + List> getTextParagraphs(); } diff --git a/poi/src/main/java/org/apache/poi/sl/usermodel/PictureData.java b/poi/src/main/java/org/apache/poi/sl/usermodel/PictureData.java index df2ca79b01..5ade4d33f1 100644 --- a/poi/src/main/java/org/apache/poi/sl/usermodel/PictureData.java +++ b/poi/src/main/java/org/apache/poi/sl/usermodel/PictureData.java @@ -90,18 +90,18 @@ public interface PictureData { * * @return content type of this picture. */ - String getContentType(); - - /** - * @return the picture type - */ - PictureType getType(); + String getContentType(); + + /** + * @return the picture type + */ + PictureType getType(); /** * Returns the binary data of this Picture * @return picture data */ - byte[] getData(); + byte[] getData(); /** * Sets the binary picture data @@ -111,26 +111,26 @@ public interface PictureData { * * @param data picture data */ - void setData(byte[] data) throws IOException; - - /** - * Gets the checksum - the checksum can be of various length - - * mostly it's 8 (XSLF) or 16 (HSLF) bytes long. - * @return the checksum - */ - byte[] getChecksum(); - + void setData(byte[] data) throws IOException; + + /** + * Gets the checksum - the checksum can be of various length - + * mostly it's 8 (XSLF) or 16 (HSLF) bytes long. + * @return the checksum + */ + byte[] getChecksum(); + /** * Return the original image dimensions in points * (for formats supported by BufferedImage). * * Will return a Dimension with a default width of 200x200 if the format unsupported. */ - Dimension getImageDimension(); - + Dimension getImageDimension(); + /** * Return the original image dimensions in pixels * @see PictureData#getImageDimension() */ - Dimension getImageDimensionInPixels(); + Dimension getImageDimensionInPixels(); } \ No newline at end of file diff --git a/poi/src/main/java/org/apache/poi/sl/usermodel/PictureShape.java b/poi/src/main/java/org/apache/poi/sl/usermodel/PictureShape.java index 03b2f642a4..4712ed03d4 100644 --- a/poi/src/main/java/org/apache/poi/sl/usermodel/PictureShape.java +++ b/poi/src/main/java/org/apache/poi/sl/usermodel/PictureShape.java @@ -30,21 +30,21 @@ public interface PictureShape< */ PictureData getPictureData(); - /** - * Returns an alternative picture data, e.g. an embedded SVG image - * - * @return an alternative picture data - * - * @since POI 4.1.0 - */ + /** + * Returns an alternative picture data, e.g. an embedded SVG image + * + * @return an alternative picture data + * + * @since POI 4.1.0 + */ default PictureData getAlternativePictureData() { return null; } - /** - * Returns the clipping values as percent ratio relatively to the image size. - * The clipping are returned as insets converted/scaled to 100000 (=100%). - * - * @return the clipping rectangle, which is given in percent in relation to the image width/height - */ - Insets getClipping(); + /** + * Returns the clipping values as percent ratio relatively to the image size. + * The clipping are returned as insets converted/scaled to 100000 (=100%). + * + * @return the clipping rectangle, which is given in percent in relation to the image width/height + */ + Insets getClipping(); } diff --git a/poi/src/main/java/org/apache/poi/sl/usermodel/Shape.java b/poi/src/main/java/org/apache/poi/sl/usermodel/Shape.java index 4929f48bb8..143c601983 100644 --- a/poi/src/main/java/org/apache/poi/sl/usermodel/Shape.java +++ b/poi/src/main/java/org/apache/poi/sl/usermodel/Shape.java @@ -24,7 +24,7 @@ public interface Shape< S extends Shape, P extends TextParagraph > { - ShapeContainer getParent(); + ShapeContainer getParent(); /** * @return the sheet this shape belongs to diff --git a/poi/src/main/java/org/apache/poi/sl/usermodel/ShapeContainer.java b/poi/src/main/java/org/apache/poi/sl/usermodel/ShapeContainer.java index bd6b6e72c3..bbb879762e 100644 --- a/poi/src/main/java/org/apache/poi/sl/usermodel/ShapeContainer.java +++ b/poi/src/main/java/org/apache/poi/sl/usermodel/ShapeContainer.java @@ -31,9 +31,9 @@ public interface ShapeContainer< * @return an list containing all of the elements in this container in proper * sequence */ - List getShapes(); + List getShapes(); - void addShape(S shape); + void addShape(S shape); /** * Removes the specified shape from this sheet, if it is present @@ -45,7 +45,7 @@ public interface ShapeContainer< * @throws IllegalArgumentException if the type of the specified shape * is incompatible with this sheet (optional) */ - boolean removeShape(S shape); + boolean removeShape(S shape); /** * create a new shape with a predefined geometry and add it to this shape container @@ -60,22 +60,22 @@ public interface ShapeContainer< /** * create a text box */ - TextBox createTextBox(); + TextBox createTextBox(); /** * create a connector */ - ConnectorShape createConnector(); + ConnectorShape createConnector(); /** * create a group of shapes belonging to this container */ - GroupShape createGroup(); + GroupShape createGroup(); /** * create a picture belonging to this container */ - PictureShape createPicture(PictureData pictureData); + PictureShape createPicture(PictureData pictureData); /** * Create a new Table of the given number of rows and columns @@ -83,12 +83,12 @@ public interface ShapeContainer< * @param numRows the number of rows * @param numCols the number of columns */ - TableShape createTable(int numRows, int numCols); + TableShape createTable(int numRows, int numCols); - /** - * Create a new OLE object shape with the given pictureData as preview image - * - * @param pictureData the preview image - */ + /** + * Create a new OLE object shape with the given pictureData as preview image + * + * @param pictureData the preview image + */ ObjectShape createOleShape(PictureData pictureData); } diff --git a/poi/src/main/java/org/apache/poi/sl/usermodel/Sheet.java b/poi/src/main/java/org/apache/poi/sl/usermodel/Sheet.java index 347c19f23d..ab187cbc5d 100644 --- a/poi/src/main/java/org/apache/poi/sl/usermodel/Sheet.java +++ b/poi/src/main/java/org/apache/poi/sl/usermodel/Sheet.java @@ -27,33 +27,33 @@ public interface Sheet< S extends Shape, P extends TextParagraph > extends ShapeContainer { - SlideShow getSlideShow(); + SlideShow getSlideShow(); /** * @return whether shapes on the master sheet should be shown. By default master graphics is turned off. * Sheets that support the notion of master (slide, slideLayout) should override it and * check this setting in the sheet XML */ - boolean getFollowMasterGraphics(); + boolean getFollowMasterGraphics(); - MasterSheet getMasterSheet(); + MasterSheet getMasterSheet(); - Background getBackground(); + Background getBackground(); - /** - * Convenience method to draw a sheet to a graphics context - */ - void draw(Graphics2D graphics); + /** + * Convenience method to draw a sheet to a graphics context + */ + void draw(Graphics2D graphics); - /** - * Get the placeholder details for the given placeholder type. Not all placeholders are also shapes - - * this is especially true for old HSLF slideshows, which notes have header/footers elements which - * aren't shapes. - * - * @param placeholder the placeholder type - * @return the placeholder details or {@code null}, if the placeholder isn't contained in the sheet - * - * @since POI 4.0.0 - */ - PlaceholderDetails getPlaceholderDetails(Placeholder placeholder); + /** + * Get the placeholder details for the given placeholder type. Not all placeholders are also shapes - + * this is especially true for old HSLF slideshows, which notes have header/footers elements which + * aren't shapes. + * + * @param placeholder the placeholder type + * @return the placeholder details or {@code null}, if the placeholder isn't contained in the sheet + * + * @since POI 4.0.0 + */ + PlaceholderDetails getPlaceholderDetails(Placeholder placeholder); } diff --git a/poi/src/main/java/org/apache/poi/sl/usermodel/SimpleShape.java b/poi/src/main/java/org/apache/poi/sl/usermodel/SimpleShape.java index ec31b5cc65..507c3a7efe 100644 --- a/poi/src/main/java/org/apache/poi/sl/usermodel/SimpleShape.java +++ b/poi/src/main/java/org/apache/poi/sl/usermodel/SimpleShape.java @@ -83,7 +83,7 @@ public interface SimpleShape< boolean isPlaceholder(); - Shadow getShadow(); + Shadow getShadow(); /** * Returns the solid color fill. @@ -91,7 +91,7 @@ public interface SimpleShape< * @return solid fill color of null if not set or fill color * is not solid (pattern or gradient) */ - Color getFillColor(); + Color getFillColor(); /** * Specifies a solid color fill. The shape is filled entirely with the @@ -100,7 +100,7 @@ public interface SimpleShape< * @param color the solid color fill. The value of null unsets * the solid fill attribute from the underlying implementation */ - void setFillColor(Color color); + void setFillColor(Color color); /** * Returns the hyperlink assigned to this shape @@ -110,9 +110,9 @@ public interface SimpleShape< * * @since POI 3.14-Beta1 */ - Hyperlink getHyperlink(); - - /** + Hyperlink getHyperlink(); + + /** * Creates a hyperlink and asigns it to this shape. * If the shape has already a hyperlink assigned, return it instead * diff --git a/poi/src/main/java/org/apache/poi/sl/usermodel/SlideShow.java b/poi/src/main/java/org/apache/poi/sl/usermodel/SlideShow.java index 751379de92..eaca055dfe 100644 --- a/poi/src/main/java/org/apache/poi/sl/usermodel/SlideShow.java +++ b/poi/src/main/java/org/apache/poi/sl/usermodel/SlideShow.java @@ -33,17 +33,17 @@ public interface SlideShow< S extends Shape, P extends TextParagraph > extends Closeable { - Slide createSlide() throws IOException; + Slide createSlide() throws IOException; - List> getSlides(); + List> getSlides(); MasterSheet createMasterSheet() throws IOException; - /** + /** * Returns all slide masters. * This doesn't include notes master and other arbitrary masters. */ - List> getSlideMasters(); + List> getSlideMasters(); /** * Returns the current page size @@ -79,7 +79,7 @@ public interface SlideShow< /** * Adds a picture to the presentation. * - * @param is The stream to read the image from + * @param is The stream to read the image from * @param format The format of the picture. * * @return the picture data reference. diff --git a/poi/src/main/java/org/apache/poi/ss/formula/CellCacheEntry.java b/poi/src/main/java/org/apache/poi/ss/formula/CellCacheEntry.java index 22db400533..79cc5301b6 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/CellCacheEntry.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/CellCacheEntry.java @@ -29,108 +29,108 @@ import org.apache.poi.ss.formula.IEvaluationListener.ICacheEntry; * Stores the parameters that identify the evaluation of one cell.
*/ abstract class CellCacheEntry implements ICacheEntry { - public static final CellCacheEntry[] EMPTY_ARRAY = { }; + public static final CellCacheEntry[] EMPTY_ARRAY = { }; - private final FormulaCellCacheEntrySet _consumingCells; - private ValueEval _value; + private final FormulaCellCacheEntrySet _consumingCells; + private ValueEval _value; - protected CellCacheEntry() { - _consumingCells = new FormulaCellCacheEntrySet(); - } - protected final void clearValue() { - _value = null; - } + protected CellCacheEntry() { + _consumingCells = new FormulaCellCacheEntrySet(); + } + protected final void clearValue() { + _value = null; + } - public final boolean updateValue(ValueEval value) { - if (value == null) { - throw new IllegalArgumentException("Did not expect to update to null"); - } - boolean result = !areValuesEqual(_value, value); - _value = value; - return result; - } - public final ValueEval getValue() { - return _value; - } + public final boolean updateValue(ValueEval value) { + if (value == null) { + throw new IllegalArgumentException("Did not expect to update to null"); + } + boolean result = !areValuesEqual(_value, value); + _value = value; + return result; + } + public final ValueEval getValue() { + return _value; + } - private static boolean areValuesEqual(ValueEval a, ValueEval b) { - if (a == null) { - return false; - } - Class cls = a.getClass(); - if (cls != b.getClass()) { - // value type is changing - return false; - } - if (a == BlankEval.instance) { - return b == a; - } - if (cls == NumberEval.class) { - return ((NumberEval)a).getNumberValue() == ((NumberEval)b).getNumberValue(); - } - if (cls == StringEval.class) { - return ((StringEval)a).getStringValue().equals(((StringEval)b).getStringValue()); - } - if (cls == BoolEval.class) { - return ((BoolEval)a).getBooleanValue() == ((BoolEval)b).getBooleanValue(); - } - if (cls == ErrorEval.class) { - return ((ErrorEval)a).getErrorCode() == ((ErrorEval)b).getErrorCode(); - } - throw new IllegalStateException("Unexpected value class (" + cls.getName() + ")"); - } + private static boolean areValuesEqual(ValueEval a, ValueEval b) { + if (a == null) { + return false; + } + Class cls = a.getClass(); + if (cls != b.getClass()) { + // value type is changing + return false; + } + if (a == BlankEval.instance) { + return b == a; + } + if (cls == NumberEval.class) { + return ((NumberEval)a).getNumberValue() == ((NumberEval)b).getNumberValue(); + } + if (cls == StringEval.class) { + return ((StringEval)a).getStringValue().equals(((StringEval)b).getStringValue()); + } + if (cls == BoolEval.class) { + return ((BoolEval)a).getBooleanValue() == ((BoolEval)b).getBooleanValue(); + } + if (cls == ErrorEval.class) { + return ((ErrorEval)a).getErrorCode() == ((ErrorEval)b).getErrorCode(); + } + throw new IllegalStateException("Unexpected value class (" + cls.getName() + ")"); + } - public final void addConsumingCell(FormulaCellCacheEntry cellLoc) { - _consumingCells.add(cellLoc); + public final void addConsumingCell(FormulaCellCacheEntry cellLoc) { + _consumingCells.add(cellLoc); - } - public final FormulaCellCacheEntry[] getConsumingCells() { - return _consumingCells.toArray(); - } + } + public final FormulaCellCacheEntry[] getConsumingCells() { + return _consumingCells.toArray(); + } - public final void clearConsumingCell(FormulaCellCacheEntry cce) { - if(!_consumingCells.remove(cce)) { - throw new IllegalStateException("Specified formula cell is not consumed by this cell"); - } - } - public final void recurseClearCachedFormulaResults(IEvaluationListener listener) { - if (listener == null) { - recurseClearCachedFormulaResults(); - } else { - listener.onClearCachedValue(this); - recurseClearCachedFormulaResults(listener, 1); - } - } + public final void clearConsumingCell(FormulaCellCacheEntry cce) { + if(!_consumingCells.remove(cce)) { + throw new IllegalStateException("Specified formula cell is not consumed by this cell"); + } + } + public final void recurseClearCachedFormulaResults(IEvaluationListener listener) { + if (listener == null) { + recurseClearCachedFormulaResults(); + } else { + listener.onClearCachedValue(this); + recurseClearCachedFormulaResults(listener, 1); + } + } - /** - * Calls formulaCell.setFormulaResult(null, null) recursively all the way up the tree of - * dependencies. Calls usedCell.clearConsumingCell(fc) for each child of a cell that is - * cleared along the way. - * @param formulaCells - */ - protected final void recurseClearCachedFormulaResults() { - FormulaCellCacheEntry[] formulaCells = getConsumingCells(); + /** + * Calls formulaCell.setFormulaResult(null, null) recursively all the way up the tree of + * dependencies. Calls usedCell.clearConsumingCell(fc) for each child of a cell that is + * cleared along the way. + * @param formulaCells + */ + protected final void recurseClearCachedFormulaResults() { + FormulaCellCacheEntry[] formulaCells = getConsumingCells(); - for (int i = 0; i < formulaCells.length; i++) { - FormulaCellCacheEntry fc = formulaCells[i]; - fc.clearFormulaEntry(); - fc.recurseClearCachedFormulaResults(); - } - } + for (int i = 0; i < formulaCells.length; i++) { + FormulaCellCacheEntry fc = formulaCells[i]; + fc.clearFormulaEntry(); + fc.recurseClearCachedFormulaResults(); + } + } - /** - * Identical to {@link #recurseClearCachedFormulaResults()} except for the listener call-backs - */ - protected final void recurseClearCachedFormulaResults(IEvaluationListener listener, int depth) { - FormulaCellCacheEntry[] formulaCells = getConsumingCells(); + /** + * Identical to {@link #recurseClearCachedFormulaResults()} except for the listener call-backs + */ + protected final void recurseClearCachedFormulaResults(IEvaluationListener listener, int depth) { + FormulaCellCacheEntry[] formulaCells = getConsumingCells(); - listener.sortDependentCachedValues(formulaCells); - for (int i = 0; i < formulaCells.length; i++) { - FormulaCellCacheEntry fc = formulaCells[i]; - listener.onClearDependentCachedValue(fc, depth); - fc.clearFormulaEntry(); - fc.recurseClearCachedFormulaResults(listener, depth+1); - } - } + listener.sortDependentCachedValues(formulaCells); + for (int i = 0; i < formulaCells.length; i++) { + FormulaCellCacheEntry fc = formulaCells[i]; + listener.onClearDependentCachedValue(fc, depth); + fc.clearFormulaEntry(); + fc.recurseClearCachedFormulaResults(listener, depth+1); + } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/CellEvaluationFrame.java b/poi/src/main/java/org/apache/poi/ss/formula/CellEvaluationFrame.java index b9c7efc678..378aa589f7 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/CellEvaluationFrame.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/CellEvaluationFrame.java @@ -27,51 +27,51 @@ import org.apache.poi.ss.formula.eval.ValueEval; */ final class CellEvaluationFrame { - private final FormulaCellCacheEntry _cce; - private final Set _sensitiveInputCells; - private FormulaUsedBlankCellSet _usedBlankCellGroup; + private final FormulaCellCacheEntry _cce; + private final Set _sensitiveInputCells; + private FormulaUsedBlankCellSet _usedBlankCellGroup; - public CellEvaluationFrame(FormulaCellCacheEntry cce) { - _cce = cce; - _sensitiveInputCells = new HashSet<>(); - } - public CellCacheEntry getCCE() { - return _cce; - } + public CellEvaluationFrame(FormulaCellCacheEntry cce) { + _cce = cce; + _sensitiveInputCells = new HashSet<>(); + } + public CellCacheEntry getCCE() { + return _cce; + } - public String toString() { - StringBuilder sb = new StringBuilder(64); - sb.append(getClass().getName()).append(" ["); - sb.append("]"); - return sb.toString(); - } - /** - * @param inputCell a cell directly used by the formula of this evaluation frame - */ - public void addSensitiveInputCell(CellCacheEntry inputCell) { - _sensitiveInputCells.add(inputCell); - } - /** - * @return never null, (possibly empty) array of all cells directly used while - * evaluating the formula of this frame. - */ - private CellCacheEntry[] getSensitiveInputCells() { - int nItems = _sensitiveInputCells.size(); - if (nItems < 1) { - return CellCacheEntry.EMPTY_ARRAY; - } - CellCacheEntry[] result = new CellCacheEntry[nItems]; - _sensitiveInputCells.toArray(result); - return result; - } - public void addUsedBlankCell(EvaluationWorkbook evalWorkbook, int bookIndex, int sheetIndex, int rowIndex, int columnIndex) { - if (_usedBlankCellGroup == null) { - _usedBlankCellGroup = new FormulaUsedBlankCellSet(); - } - _usedBlankCellGroup.addCell(evalWorkbook, bookIndex, sheetIndex, rowIndex, columnIndex); - } + public String toString() { + StringBuilder sb = new StringBuilder(64); + sb.append(getClass().getName()).append(" ["); + sb.append("]"); + return sb.toString(); + } + /** + * @param inputCell a cell directly used by the formula of this evaluation frame + */ + public void addSensitiveInputCell(CellCacheEntry inputCell) { + _sensitiveInputCells.add(inputCell); + } + /** + * @return never null, (possibly empty) array of all cells directly used while + * evaluating the formula of this frame. + */ + private CellCacheEntry[] getSensitiveInputCells() { + int nItems = _sensitiveInputCells.size(); + if (nItems < 1) { + return CellCacheEntry.EMPTY_ARRAY; + } + CellCacheEntry[] result = new CellCacheEntry[nItems]; + _sensitiveInputCells.toArray(result); + return result; + } + public void addUsedBlankCell(EvaluationWorkbook evalWorkbook, int bookIndex, int sheetIndex, int rowIndex, int columnIndex) { + if (_usedBlankCellGroup == null) { + _usedBlankCellGroup = new FormulaUsedBlankCellSet(); + } + _usedBlankCellGroup.addCell(evalWorkbook, bookIndex, sheetIndex, rowIndex, columnIndex); + } - public void updateFormulaResult(ValueEval result) { - _cce.updateFormulaResult(result, getSensitiveInputCells(), _usedBlankCellGroup); - } + public void updateFormulaResult(ValueEval result) { + _cce.updateFormulaResult(result, getSensitiveInputCells(), _usedBlankCellGroup); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/EvaluationCache.java b/poi/src/main/java/org/apache/poi/ss/formula/EvaluationCache.java index be8c5a09ef..cd7539a675 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/EvaluationCache.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/EvaluationCache.java @@ -35,178 +35,178 @@ import org.apache.poi.ss.usermodel.CellType; */ final class EvaluationCache { - private final PlainCellCache _plainCellCache; - private final FormulaCellCache _formulaCellCache; - /** only used for testing. null otherwise */ - final IEvaluationListener _evaluationListener; + private final PlainCellCache _plainCellCache; + private final FormulaCellCache _formulaCellCache; + /** only used for testing. null otherwise */ + final IEvaluationListener _evaluationListener; - /* package */EvaluationCache(IEvaluationListener evaluationListener) { - _evaluationListener = evaluationListener; - _plainCellCache = new PlainCellCache(); - _formulaCellCache = new FormulaCellCache(); - } + /* package */EvaluationCache(IEvaluationListener evaluationListener) { + _evaluationListener = evaluationListener; + _plainCellCache = new PlainCellCache(); + _formulaCellCache = new FormulaCellCache(); + } - public void notifyUpdateCell(int bookIndex, int sheetIndex, EvaluationCell cell) { - FormulaCellCacheEntry fcce = _formulaCellCache.get(cell); + public void notifyUpdateCell(int bookIndex, int sheetIndex, EvaluationCell cell) { + FormulaCellCacheEntry fcce = _formulaCellCache.get(cell); - int rowIndex = cell.getRowIndex(); - int columnIndex = cell.getColumnIndex(); - Loc loc = new Loc(bookIndex, sheetIndex, rowIndex, columnIndex); - PlainValueCellCacheEntry pcce = _plainCellCache.get(loc); + int rowIndex = cell.getRowIndex(); + int columnIndex = cell.getColumnIndex(); + Loc loc = new Loc(bookIndex, sheetIndex, rowIndex, columnIndex); + PlainValueCellCacheEntry pcce = _plainCellCache.get(loc); - if (cell.getCellType() == CellType.FORMULA) { - if (fcce == null) { - fcce = new FormulaCellCacheEntry(); - if (pcce == null) { - if (_evaluationListener != null) { - _evaluationListener.onChangeFromBlankValue(sheetIndex, rowIndex, - columnIndex, cell, fcce); - } - updateAnyBlankReferencingFormulas(bookIndex, sheetIndex, rowIndex, - columnIndex); - } - _formulaCellCache.put(cell, fcce); - } else { - fcce.recurseClearCachedFormulaResults(_evaluationListener); - fcce.clearFormulaEntry(); - } - if (pcce == null) { - // was formula cell before - no change of type - } else { - // changing from plain cell to formula cell - pcce.recurseClearCachedFormulaResults(_evaluationListener); - _plainCellCache.remove(loc); - } - } else { - ValueEval value = WorkbookEvaluator.getValueFromNonFormulaCell(cell); - if (pcce == null) { - if (value != BlankEval.instance) { - // only cache non-blank values in the plain cell cache - // (dependencies on blank cells are managed by - // FormulaCellCacheEntry._usedBlankCellGroup) - pcce = new PlainValueCellCacheEntry(value); - if (fcce == null) { - if (_evaluationListener != null) { - _evaluationListener.onChangeFromBlankValue(sheetIndex, rowIndex, columnIndex, cell, pcce); - } - updateAnyBlankReferencingFormulas(bookIndex, sheetIndex, - rowIndex, columnIndex); - } - _plainCellCache.put(loc, pcce); - } - } else { - if (pcce.updateValue(value)) { - pcce.recurseClearCachedFormulaResults(_evaluationListener); - } - if (value == BlankEval.instance) { - _plainCellCache.remove(loc); - } - } - if (fcce == null) { - // was plain cell before - no change of type - } else { - // was formula cell before - now a plain value - _formulaCellCache.remove(cell); - fcce.setSensitiveInputCells(null); - fcce.recurseClearCachedFormulaResults(_evaluationListener); - } - } - } + if (cell.getCellType() == CellType.FORMULA) { + if (fcce == null) { + fcce = new FormulaCellCacheEntry(); + if (pcce == null) { + if (_evaluationListener != null) { + _evaluationListener.onChangeFromBlankValue(sheetIndex, rowIndex, + columnIndex, cell, fcce); + } + updateAnyBlankReferencingFormulas(bookIndex, sheetIndex, rowIndex, + columnIndex); + } + _formulaCellCache.put(cell, fcce); + } else { + fcce.recurseClearCachedFormulaResults(_evaluationListener); + fcce.clearFormulaEntry(); + } + if (pcce == null) { + // was formula cell before - no change of type + } else { + // changing from plain cell to formula cell + pcce.recurseClearCachedFormulaResults(_evaluationListener); + _plainCellCache.remove(loc); + } + } else { + ValueEval value = WorkbookEvaluator.getValueFromNonFormulaCell(cell); + if (pcce == null) { + if (value != BlankEval.instance) { + // only cache non-blank values in the plain cell cache + // (dependencies on blank cells are managed by + // FormulaCellCacheEntry._usedBlankCellGroup) + pcce = new PlainValueCellCacheEntry(value); + if (fcce == null) { + if (_evaluationListener != null) { + _evaluationListener.onChangeFromBlankValue(sheetIndex, rowIndex, columnIndex, cell, pcce); + } + updateAnyBlankReferencingFormulas(bookIndex, sheetIndex, + rowIndex, columnIndex); + } + _plainCellCache.put(loc, pcce); + } + } else { + if (pcce.updateValue(value)) { + pcce.recurseClearCachedFormulaResults(_evaluationListener); + } + if (value == BlankEval.instance) { + _plainCellCache.remove(loc); + } + } + if (fcce == null) { + // was plain cell before - no change of type + } else { + // was formula cell before - now a plain value + _formulaCellCache.remove(cell); + fcce.setSensitiveInputCells(null); + fcce.recurseClearCachedFormulaResults(_evaluationListener); + } + } + } - private void updateAnyBlankReferencingFormulas(int bookIndex, int sheetIndex, - final int rowIndex, final int columnIndex) { - final BookSheetKey bsk = new BookSheetKey(bookIndex, sheetIndex); - _formulaCellCache.applyOperation(entry -> entry.notifyUpdatedBlankCell(bsk, rowIndex, columnIndex, _evaluationListener)); - } + private void updateAnyBlankReferencingFormulas(int bookIndex, int sheetIndex, + final int rowIndex, final int columnIndex) { + final BookSheetKey bsk = new BookSheetKey(bookIndex, sheetIndex); + _formulaCellCache.applyOperation(entry -> entry.notifyUpdatedBlankCell(bsk, rowIndex, columnIndex, _evaluationListener)); + } - public PlainValueCellCacheEntry getPlainValueEntry(int bookIndex, int sheetIndex, - int rowIndex, int columnIndex, ValueEval value) { + public PlainValueCellCacheEntry getPlainValueEntry(int bookIndex, int sheetIndex, + int rowIndex, int columnIndex, ValueEval value) { - Loc loc = new Loc(bookIndex, sheetIndex, rowIndex, columnIndex); - PlainValueCellCacheEntry result = _plainCellCache.get(loc); - if (result == null) { - result = new PlainValueCellCacheEntry(value); - _plainCellCache.put(loc, result); - if (_evaluationListener != null) { - _evaluationListener.onReadPlainValue(sheetIndex, rowIndex, columnIndex, result); - } - } else { - // TODO - if we are confident that this sanity check is not required, we can remove 'value' from plain value cache entry - if (!areValuesEqual(result.getValue(), value)) { - throw new IllegalStateException("value changed"); - } - if (_evaluationListener != null) { - _evaluationListener.onCacheHit(sheetIndex, rowIndex, columnIndex, value); - } - } - return result; - } - private boolean areValuesEqual(ValueEval a, ValueEval b) { - if (a == null) { - return false; - } - Class cls = a.getClass(); - if (cls != b.getClass()) { - // value type is changing - return false; - } - if (a == BlankEval.instance) { - return b == a; - } - if (cls == NumberEval.class) { - return ((NumberEval)a).getNumberValue() == ((NumberEval)b).getNumberValue(); - } - if (cls == StringEval.class) { - return ((StringEval)a).getStringValue().equals(((StringEval)b).getStringValue()); - } - if (cls == BoolEval.class) { - return ((BoolEval)a).getBooleanValue() == ((BoolEval)b).getBooleanValue(); - } - if (cls == ErrorEval.class) { - return ((ErrorEval)a).getErrorCode() == ((ErrorEval)b).getErrorCode(); - } - throw new IllegalStateException("Unexpected value class (" + cls.getName() + ")"); - } + Loc loc = new Loc(bookIndex, sheetIndex, rowIndex, columnIndex); + PlainValueCellCacheEntry result = _plainCellCache.get(loc); + if (result == null) { + result = new PlainValueCellCacheEntry(value); + _plainCellCache.put(loc, result); + if (_evaluationListener != null) { + _evaluationListener.onReadPlainValue(sheetIndex, rowIndex, columnIndex, result); + } + } else { + // TODO - if we are confident that this sanity check is not required, we can remove 'value' from plain value cache entry + if (!areValuesEqual(result.getValue(), value)) { + throw new IllegalStateException("value changed"); + } + if (_evaluationListener != null) { + _evaluationListener.onCacheHit(sheetIndex, rowIndex, columnIndex, value); + } + } + return result; + } + private boolean areValuesEqual(ValueEval a, ValueEval b) { + if (a == null) { + return false; + } + Class cls = a.getClass(); + if (cls != b.getClass()) { + // value type is changing + return false; + } + if (a == BlankEval.instance) { + return b == a; + } + if (cls == NumberEval.class) { + return ((NumberEval)a).getNumberValue() == ((NumberEval)b).getNumberValue(); + } + if (cls == StringEval.class) { + return ((StringEval)a).getStringValue().equals(((StringEval)b).getStringValue()); + } + if (cls == BoolEval.class) { + return ((BoolEval)a).getBooleanValue() == ((BoolEval)b).getBooleanValue(); + } + if (cls == ErrorEval.class) { + return ((ErrorEval)a).getErrorCode() == ((ErrorEval)b).getErrorCode(); + } + throw new IllegalStateException("Unexpected value class (" + cls.getName() + ")"); + } - public FormulaCellCacheEntry getOrCreateFormulaCellEntry(EvaluationCell cell) { - FormulaCellCacheEntry result = _formulaCellCache.get(cell); - if (result == null) { + public FormulaCellCacheEntry getOrCreateFormulaCellEntry(EvaluationCell cell) { + FormulaCellCacheEntry result = _formulaCellCache.get(cell); + if (result == null) { - result = new FormulaCellCacheEntry(); - _formulaCellCache.put(cell, result); - } - return result; - } + result = new FormulaCellCacheEntry(); + _formulaCellCache.put(cell, result); + } + return result; + } - /** - * Should be called whenever there are changes to input cells in the evaluated workbook. - */ - public void clear() { - if(_evaluationListener != null) { - _evaluationListener.onClearWholeCache(); - } - _plainCellCache.clear(); - _formulaCellCache.clear(); - } - public void notifyDeleteCell(int bookIndex, int sheetIndex, EvaluationCell cell) { + /** + * Should be called whenever there are changes to input cells in the evaluated workbook. + */ + public void clear() { + if(_evaluationListener != null) { + _evaluationListener.onClearWholeCache(); + } + _plainCellCache.clear(); + _formulaCellCache.clear(); + } + public void notifyDeleteCell(int bookIndex, int sheetIndex, EvaluationCell cell) { - if (cell.getCellType() == CellType.FORMULA) { - FormulaCellCacheEntry fcce = _formulaCellCache.remove(cell); - if (fcce == null) { - // formula cell has not been evaluated yet - } else { - fcce.setSensitiveInputCells(null); - fcce.recurseClearCachedFormulaResults(_evaluationListener); - } - } else { - Loc loc = new Loc(bookIndex, sheetIndex, cell.getRowIndex(), cell.getColumnIndex()); - PlainValueCellCacheEntry pcce = _plainCellCache.get(loc); + if (cell.getCellType() == CellType.FORMULA) { + FormulaCellCacheEntry fcce = _formulaCellCache.remove(cell); + if (fcce == null) { + // formula cell has not been evaluated yet + } else { + fcce.setSensitiveInputCells(null); + fcce.recurseClearCachedFormulaResults(_evaluationListener); + } + } else { + Loc loc = new Loc(bookIndex, sheetIndex, cell.getRowIndex(), cell.getColumnIndex()); + PlainValueCellCacheEntry pcce = _plainCellCache.get(loc); - if (pcce == null) { - // cache entry doesn't exist. nothing to do - } else { - pcce.recurseClearCachedFormulaResults(_evaluationListener); - } - } - } + if (pcce == null) { + // cache entry doesn't exist. nothing to do + } else { + pcce.recurseClearCachedFormulaResults(_evaluationListener); + } + } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/EvaluationCell.java b/poi/src/main/java/org/apache/poi/ss/formula/EvaluationCell.java index 5dafd4aec7..91b5df31b7 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/EvaluationCell.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/EvaluationCell.java @@ -27,26 +27,26 @@ import org.apache.poi.util.Internal; */ @Internal public interface EvaluationCell { - /** - * @return an Object that identifies the underlying cell, - * suitable for use as a key in a {@link java.util.HashMap} - */ - Object getIdentityKey(); + /** + * @return an Object that identifies the underlying cell, + * suitable for use as a key in a {@link java.util.HashMap} + */ + Object getIdentityKey(); - EvaluationSheet getSheet(); - int getRowIndex(); - int getColumnIndex(); - CellType getCellType(); + EvaluationSheet getSheet(); + int getRowIndex(); + int getColumnIndex(); + CellType getCellType(); - double getNumericCellValue(); - String getStringCellValue(); - boolean getBooleanCellValue(); - int getErrorCellValue(); - CellRangeAddress getArrayFormulaRange(); - boolean isPartOfArrayFormulaGroup(); + double getNumericCellValue(); + String getStringCellValue(); + boolean getBooleanCellValue(); + int getErrorCellValue(); + CellRangeAddress getArrayFormulaRange(); + boolean isPartOfArrayFormulaGroup(); - /** - * @return cell type of cached formula result - */ - CellType getCachedFormulaResultType(); + /** + * @return cell type of cached formula result + */ + CellType getCachedFormulaResultType(); } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/EvaluationName.java b/poi/src/main/java/org/apache/poi/ss/formula/EvaluationName.java index c7931069cc..51901597c2 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/EvaluationName.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/EvaluationName.java @@ -27,14 +27,14 @@ import org.apache.poi.util.Internal; @Internal public interface EvaluationName { - String getNameText(); + String getNameText(); - boolean isFunctionName(); + boolean isFunctionName(); - boolean hasFormula(); + boolean hasFormula(); - Ptg[] getNameDefinition(); + Ptg[] getNameDefinition(); - boolean isRange(); - NamePtg createPtg(); + boolean isRange(); + NamePtg createPtg(); } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/EvaluationTracker.java b/poi/src/main/java/org/apache/poi/ss/formula/EvaluationTracker.java index 30b9a45469..4086664c62 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/EvaluationTracker.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/EvaluationTracker.java @@ -34,116 +34,116 @@ import org.apache.poi.ss.formula.eval.ValueEval; * references in spreadsheet formulas. */ final class EvaluationTracker { - // TODO - consider deleting this class and letting CellEvaluationFrame take care of itself - private final List _evaluationFrames; - private final Set _currentlyEvaluatingCells; - private final EvaluationCache _cache; + // TODO - consider deleting this class and letting CellEvaluationFrame take care of itself + private final List _evaluationFrames; + private final Set _currentlyEvaluatingCells; + private final EvaluationCache _cache; - public EvaluationTracker(EvaluationCache cache) { - _cache = cache; - _evaluationFrames = new ArrayList<>(); - _currentlyEvaluatingCells = new HashSet<>(); - } + public EvaluationTracker(EvaluationCache cache) { + _cache = cache; + _evaluationFrames = new ArrayList<>(); + _currentlyEvaluatingCells = new HashSet<>(); + } - /** - * Notifies this evaluation tracker that evaluation of the specified cell is - * about to start.
- * - * In the case of a {@code true} return code, the caller should - * continue evaluation of the specified cell, and also be sure to call - * {@code endEvaluate()} when complete.
- * - * In the case of a {@code null} return code, the caller should - * return an evaluation result of - * {@code ErrorEval.CIRCULAR_REF_ERROR}, and not call {@code endEvaluate()}. - *
- * @return {@code false} if the specified cell is already being evaluated - */ - public boolean startEvaluate(FormulaCellCacheEntry cce) { - if (cce == null) { - throw new IllegalArgumentException("cellLoc must not be null"); - } - if (_currentlyEvaluatingCells.contains(cce)) { - return false; - } - _currentlyEvaluatingCells.add(cce); - _evaluationFrames.add(new CellEvaluationFrame(cce)); - return true; - } + /** + * Notifies this evaluation tracker that evaluation of the specified cell is + * about to start.
+ * + * In the case of a {@code true} return code, the caller should + * continue evaluation of the specified cell, and also be sure to call + * {@code endEvaluate()} when complete.
+ * + * In the case of a {@code null} return code, the caller should + * return an evaluation result of + * {@code ErrorEval.CIRCULAR_REF_ERROR}, and not call {@code endEvaluate()}. + *
+ * @return {@code false} if the specified cell is already being evaluated + */ + public boolean startEvaluate(FormulaCellCacheEntry cce) { + if (cce == null) { + throw new IllegalArgumentException("cellLoc must not be null"); + } + if (_currentlyEvaluatingCells.contains(cce)) { + return false; + } + _currentlyEvaluatingCells.add(cce); + _evaluationFrames.add(new CellEvaluationFrame(cce)); + return true; + } - public void updateCacheResult(ValueEval result) { + public void updateCacheResult(ValueEval result) { - int nFrames = _evaluationFrames.size(); - if (nFrames < 1) { - throw new IllegalStateException("Call to endEvaluate without matching call to startEvaluate"); - } - CellEvaluationFrame frame = _evaluationFrames.get(nFrames-1); - if (result == ErrorEval.CIRCULAR_REF_ERROR && nFrames > 1) { - // Don't cache a circular ref error result if this cell is not the top evaluated cell. - // A true circular ref error will propagate all the way around the loop. However, it's - // possible to have parts of the formula tree (/ parts of the loop) to evaluate to - // CIRCULAR_REF_ERROR, and that value not get used in the final cell result (see the - // unit tests for a simple example). Thus, the only CIRCULAR_REF_ERROR result that can - // safely be cached is that of the top evaluated cell. - return; - } + int nFrames = _evaluationFrames.size(); + if (nFrames < 1) { + throw new IllegalStateException("Call to endEvaluate without matching call to startEvaluate"); + } + CellEvaluationFrame frame = _evaluationFrames.get(nFrames-1); + if (result == ErrorEval.CIRCULAR_REF_ERROR && nFrames > 1) { + // Don't cache a circular ref error result if this cell is not the top evaluated cell. + // A true circular ref error will propagate all the way around the loop. However, it's + // possible to have parts of the formula tree (/ parts of the loop) to evaluate to + // CIRCULAR_REF_ERROR, and that value not get used in the final cell result (see the + // unit tests for a simple example). Thus, the only CIRCULAR_REF_ERROR result that can + // safely be cached is that of the top evaluated cell. + return; + } - frame.updateFormulaResult(result); - } + frame.updateFormulaResult(result); + } - /** - * Notifies this evaluation tracker that the evaluation of the specified cell is complete.

- * - * Every successful call to {@code startEvaluate} must be followed by a call to {@code endEvaluate} (recommended in a finally block) to enable - * proper tracking of which cells are being evaluated at any point in time.

- * - * Assuming a well behaved client, parameters to this method would not be - * required. However, they have been included to assert correct behaviour, - * and form more meaningful error messages. - */ - public void endEvaluate(CellCacheEntry cce) { + /** + * Notifies this evaluation tracker that the evaluation of the specified cell is complete.

+ * + * Every successful call to {@code startEvaluate} must be followed by a call to {@code endEvaluate} (recommended in a finally block) to enable + * proper tracking of which cells are being evaluated at any point in time.

+ * + * Assuming a well behaved client, parameters to this method would not be + * required. However, they have been included to assert correct behaviour, + * and form more meaningful error messages. + */ + public void endEvaluate(CellCacheEntry cce) { - int nFrames = _evaluationFrames.size(); - if (nFrames < 1) { - throw new IllegalStateException("Call to endEvaluate without matching call to startEvaluate"); - } + int nFrames = _evaluationFrames.size(); + if (nFrames < 1) { + throw new IllegalStateException("Call to endEvaluate without matching call to startEvaluate"); + } - nFrames--; - CellEvaluationFrame frame = _evaluationFrames.get(nFrames); - if (cce != frame.getCCE()) { - throw new IllegalStateException("Wrong cell specified. "); - } - // else - no problems so pop current frame - _evaluationFrames.remove(nFrames); - _currentlyEvaluatingCells.remove(cce); - } + nFrames--; + CellEvaluationFrame frame = _evaluationFrames.get(nFrames); + if (cce != frame.getCCE()) { + throw new IllegalStateException("Wrong cell specified. "); + } + // else - no problems so pop current frame + _evaluationFrames.remove(nFrames); + _currentlyEvaluatingCells.remove(cce); + } - public void acceptFormulaDependency(CellCacheEntry cce) { - // Tell the currently evaluating cell frame that it has a dependency on the specified - int prevFrameIndex = _evaluationFrames.size()-1; - if (prevFrameIndex < 0) { - // Top level frame, there is no 'cell' above this frame that is using the current cell - } else { - CellEvaluationFrame consumingFrame = _evaluationFrames.get(prevFrameIndex); - consumingFrame.addSensitiveInputCell(cce); - } - } + public void acceptFormulaDependency(CellCacheEntry cce) { + // Tell the currently evaluating cell frame that it has a dependency on the specified + int prevFrameIndex = _evaluationFrames.size()-1; + if (prevFrameIndex < 0) { + // Top level frame, there is no 'cell' above this frame that is using the current cell + } else { + CellEvaluationFrame consumingFrame = _evaluationFrames.get(prevFrameIndex); + consumingFrame.addSensitiveInputCell(cce); + } + } - public void acceptPlainValueDependency(EvaluationWorkbook evalWorkbook, int bookIndex, int sheetIndex, - int rowIndex, int columnIndex, ValueEval value) { - // Tell the currently evaluating cell frame that it has a dependency on the specified - int prevFrameIndex = _evaluationFrames.size() - 1; - if (prevFrameIndex < 0) { - // Top level frame, there is no 'cell' above this frame that is using the current cell - } else { - CellEvaluationFrame consumingFrame = _evaluationFrames.get(prevFrameIndex); - if (value == BlankEval.instance) { - consumingFrame.addUsedBlankCell(evalWorkbook, bookIndex, sheetIndex, rowIndex, columnIndex); - } else { - PlainValueCellCacheEntry cce = _cache.getPlainValueEntry(bookIndex, sheetIndex, - rowIndex, columnIndex, value); - consumingFrame.addSensitiveInputCell(cce); - } - } - } + public void acceptPlainValueDependency(EvaluationWorkbook evalWorkbook, int bookIndex, int sheetIndex, + int rowIndex, int columnIndex, ValueEval value) { + // Tell the currently evaluating cell frame that it has a dependency on the specified + int prevFrameIndex = _evaluationFrames.size() - 1; + if (prevFrameIndex < 0) { + // Top level frame, there is no 'cell' above this frame that is using the current cell + } else { + CellEvaluationFrame consumingFrame = _evaluationFrames.get(prevFrameIndex); + if (value == BlankEval.instance) { + consumingFrame.addUsedBlankCell(evalWorkbook, bookIndex, sheetIndex, rowIndex, columnIndex); + } else { + PlainValueCellCacheEntry cce = _cache.getPlainValueEntry(bookIndex, sheetIndex, + rowIndex, columnIndex, value); + consumingFrame.addSensitiveInputCell(cce); + } + } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/ExternSheetReferenceToken.java b/poi/src/main/java/org/apache/poi/ss/formula/ExternSheetReferenceToken.java index 72adc88e2c..4ba6ac39ce 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/ExternSheetReferenceToken.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/ExternSheetReferenceToken.java @@ -23,9 +23,9 @@ package org.apache.poi.ss.formula; * For POI internal use only */ public interface ExternSheetReferenceToken { - int getExternSheetIndex(); - /** - * @return formula text for this reference token without the qualifying sheet name - */ - String format2DRefAsString(); + int getExternSheetIndex(); + /** + * @return formula text for this reference token without the qualifying sheet name + */ + String format2DRefAsString(); } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/Formula.java b/poi/src/main/java/org/apache/poi/ss/formula/Formula.java index 05516e0953..0c4cc68859 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/Formula.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/Formula.java @@ -38,173 +38,173 @@ import org.apache.poi.util.LittleEndianOutput; */ public class Formula implements GenericRecord { - //Arbitrarily set. May need to increase. - private static final int MAX_ENCODED_LEN = 100000; + //Arbitrarily set. May need to increase. + private static final int MAX_ENCODED_LEN = 100000; - private static final Formula EMPTY = new Formula(new byte[0], 0); + private static final Formula EMPTY = new Formula(new byte[0], 0); - /** immutable */ - private final byte[] _byteEncoding; - private final int _encodedTokenLen; + /** immutable */ + private final byte[] _byteEncoding; + private final int _encodedTokenLen; - public Formula(Formula other) { - _byteEncoding = (other._byteEncoding == null) ? null : other._byteEncoding.clone(); - _encodedTokenLen = other._encodedTokenLen; - } + public Formula(Formula other) { + _byteEncoding = (other._byteEncoding == null) ? null : other._byteEncoding.clone(); + _encodedTokenLen = other._encodedTokenLen; + } - private Formula(byte[] byteEncoding, int encodedTokenLen) { - _byteEncoding = byteEncoding.clone(); - _encodedTokenLen = encodedTokenLen; + private Formula(byte[] byteEncoding, int encodedTokenLen) { + _byteEncoding = byteEncoding.clone(); + _encodedTokenLen = encodedTokenLen; - // TODO - this seems to occur when IntersectionPtg is present - // This example file "IntersectionPtg.xls" - // used by test: TestIntersectionPtg.testReading() - // has 10 bytes unused at the end of the formula - // 10 extra bytes are just 0x01 and 0x00 - // LittleEndianByteArrayInputStream in = new LittleEndianByteArrayInputStream(byteEncoding); - // Ptg.readTokens(encodedTokenLen, in); - // int nUnusedBytes = _byteEncoding.length - in.getReadIndex(); - } - /** - * Convenience method for {@link #read(int, LittleEndianInput, int)} - */ - public static Formula read(int encodedTokenLen, LittleEndianInput in) { - return read(encodedTokenLen, in, encodedTokenLen); - } - /** - * When there are no array constants present, {@code encodedTokenLen}=={@code totalEncodedLen} - * @param encodedTokenLen number of bytes in the stream taken by the plain formula tokens - * @param totalEncodedLen the total number of bytes in the formula (includes trailing encoding - * for array constants, but does not include 2 bytes for initial {@code ushort encodedTokenLen} field. - * @return A new formula object as read from the stream. Possibly empty, never {@code null}. - */ - public static Formula read(int encodedTokenLen, LittleEndianInput in, int totalEncodedLen) { - byte[] byteEncoding = IOUtils.safelyAllocate(totalEncodedLen, MAX_ENCODED_LEN); - in.readFully(byteEncoding); - return new Formula(byteEncoding, encodedTokenLen); - } + // TODO - this seems to occur when IntersectionPtg is present + // This example file "IntersectionPtg.xls" + // used by test: TestIntersectionPtg.testReading() + // has 10 bytes unused at the end of the formula + // 10 extra bytes are just 0x01 and 0x00 + // LittleEndianByteArrayInputStream in = new LittleEndianByteArrayInputStream(byteEncoding); + // Ptg.readTokens(encodedTokenLen, in); + // int nUnusedBytes = _byteEncoding.length - in.getReadIndex(); + } + /** + * Convenience method for {@link #read(int, LittleEndianInput, int)} + */ + public static Formula read(int encodedTokenLen, LittleEndianInput in) { + return read(encodedTokenLen, in, encodedTokenLen); + } + /** + * When there are no array constants present, {@code encodedTokenLen}=={@code totalEncodedLen} + * @param encodedTokenLen number of bytes in the stream taken by the plain formula tokens + * @param totalEncodedLen the total number of bytes in the formula (includes trailing encoding + * for array constants, but does not include 2 bytes for initial {@code ushort encodedTokenLen} field. + * @return A new formula object as read from the stream. Possibly empty, never {@code null}. + */ + public static Formula read(int encodedTokenLen, LittleEndianInput in, int totalEncodedLen) { + byte[] byteEncoding = IOUtils.safelyAllocate(totalEncodedLen, MAX_ENCODED_LEN); + in.readFully(byteEncoding); + return new Formula(byteEncoding, encodedTokenLen); + } - public Ptg[] getTokens() { - LittleEndianInput in = new LittleEndianByteArrayInputStream(_byteEncoding); - return Ptg.readTokens(_encodedTokenLen, in); - } - /** - * Writes The formula encoding is includes: - *

    - *
  • ushort tokenDataLen
  • - *
  • tokenData
  • - *
  • arrayConstantData (if present)
  • - *
- */ - public void serialize(LittleEndianOutput out) { - out.writeShort(_encodedTokenLen); - out.write(_byteEncoding); - } + public Ptg[] getTokens() { + LittleEndianInput in = new LittleEndianByteArrayInputStream(_byteEncoding); + return Ptg.readTokens(_encodedTokenLen, in); + } + /** + * Writes The formula encoding is includes: + *
    + *
  • ushort tokenDataLen
  • + *
  • tokenData
  • + *
  • arrayConstantData (if present)
  • + *
+ */ + public void serialize(LittleEndianOutput out) { + out.writeShort(_encodedTokenLen); + out.write(_byteEncoding); + } - public void serializeTokens(LittleEndianOutput out) { - out.write(_byteEncoding, 0, _encodedTokenLen); - } - public void serializeArrayConstantData(LittleEndianOutput out) { - int len = _byteEncoding.length-_encodedTokenLen; - out.write(_byteEncoding, _encodedTokenLen, len); - } + public void serializeTokens(LittleEndianOutput out) { + out.write(_byteEncoding, 0, _encodedTokenLen); + } + public void serializeArrayConstantData(LittleEndianOutput out) { + int len = _byteEncoding.length-_encodedTokenLen; + out.write(_byteEncoding, _encodedTokenLen, len); + } - /** - * @return total formula encoding length. The formula encoding includes: - *
    - *
  • ushort tokenDataLen
  • - *
  • tokenData
  • - *
  • arrayConstantData (optional)
  • - *
- * Note - this value is different to {@code tokenDataLength} - */ - public int getEncodedSize() { - return 2 + _byteEncoding.length; - } - /** - * This method is often used when the formula length does not appear immediately before - * the encoded token data. - * - * @return the encoded length of the plain formula tokens. This does not include - * the leading ushort field, nor any trailing array constant data. - */ - public int getEncodedTokenSize() { - return _encodedTokenLen; - } + /** + * @return total formula encoding length. The formula encoding includes: + *
    + *
  • ushort tokenDataLen
  • + *
  • tokenData
  • + *
  • arrayConstantData (optional)
  • + *
+ * Note - this value is different to {@code tokenDataLength} + */ + public int getEncodedSize() { + return 2 + _byteEncoding.length; + } + /** + * This method is often used when the formula length does not appear immediately before + * the encoded token data. + * + * @return the encoded length of the plain formula tokens. This does not include + * the leading ushort field, nor any trailing array constant data. + */ + public int getEncodedTokenSize() { + return _encodedTokenLen; + } - /** - * Creates a Formula object from a supplied {@link Ptg} array. - * Handles {@code null}s OK. - * @param ptgs may be {@code null} - * @return Never {@code null} (Possibly empty if the supplied {@code ptgs} is {@code null}) - */ - public static Formula create(Ptg[] ptgs) { - if (ptgs == null || ptgs.length < 1) { - return EMPTY; - } - int totalSize = Ptg.getEncodedSize(ptgs); - byte[] encodedData = new byte[totalSize]; - Ptg.serializePtgs(ptgs, encodedData, 0); - int encodedTokenLen = Ptg.getEncodedSizeWithoutArrayData(ptgs); - return new Formula(encodedData, encodedTokenLen); - } - /** - * Gets the {@link Ptg} array from the supplied Formula. - * Handles {@code null}s OK. - * - * @param formula may be {@code null} - * @return possibly {@code null} (if the supplied {@code formula} is {@code null}) - */ - public static Ptg[] getTokens(Formula formula) { - if (formula == null) { - return null; - } - return formula.getTokens(); - } + /** + * Creates a Formula object from a supplied {@link Ptg} array. + * Handles {@code null}s OK. + * @param ptgs may be {@code null} + * @return Never {@code null} (Possibly empty if the supplied {@code ptgs} is {@code null}) + */ + public static Formula create(Ptg[] ptgs) { + if (ptgs == null || ptgs.length < 1) { + return EMPTY; + } + int totalSize = Ptg.getEncodedSize(ptgs); + byte[] encodedData = new byte[totalSize]; + Ptg.serializePtgs(ptgs, encodedData, 0); + int encodedTokenLen = Ptg.getEncodedSizeWithoutArrayData(ptgs); + return new Formula(encodedData, encodedTokenLen); + } + /** + * Gets the {@link Ptg} array from the supplied Formula. + * Handles {@code null}s OK. + * + * @param formula may be {@code null} + * @return possibly {@code null} (if the supplied {@code formula} is {@code null}) + */ + public static Ptg[] getTokens(Formula formula) { + if (formula == null) { + return null; + } + return formula.getTokens(); + } - public Formula copy() { - // OK to return this because immutable - return this; - } + public Formula copy() { + // OK to return this because immutable + return this; + } - /** - * Gets the locator for the corresponding {@link org.apache.poi.hssf.record.SharedFormulaRecord}, + /** + * Gets the locator for the corresponding {@link org.apache.poi.hssf.record.SharedFormulaRecord}, * {@link org.apache.poi.hssf.record.ArrayRecord} or {@link org.apache.poi.hssf.record.TableRecord} * if this formula belongs to such a grouping. The {@link CellReference} - * returned by this method will match the top left corner of the range of that grouping. - * The return value is usually not the same as the location of the cell containing this formula. - * - * @return the firstRow & firstColumn of an array formula or shared formula that this formula - * belongs to. {@code null} if this formula is not part of an array or shared formula. - */ - public CellReference getExpReference() { - byte[] data = _byteEncoding; - if (data.length != 5) { - // tExp and tTbl are always 5 bytes long, and the only ptg in the formula - return null; - } - switch (data[0]) { - case ExpPtg.sid: - break; - case TblPtg.sid: - break; - default: - return null; - } - int firstRow = LittleEndian.getUShort(data, 1); - int firstColumn = LittleEndian.getUShort(data, 3); - return new CellReference(firstRow, firstColumn); - } - public boolean isSame(Formula other) { - return Arrays.equals(_byteEncoding, other._byteEncoding); - } + * returned by this method will match the top left corner of the range of that grouping. + * The return value is usually not the same as the location of the cell containing this formula. + * + * @return the firstRow & firstColumn of an array formula or shared formula that this formula + * belongs to. {@code null} if this formula is not part of an array or shared formula. + */ + public CellReference getExpReference() { + byte[] data = _byteEncoding; + if (data.length != 5) { + // tExp and tTbl are always 5 bytes long, and the only ptg in the formula + return null; + } + switch (data[0]) { + case ExpPtg.sid: + break; + case TblPtg.sid: + break; + default: + return null; + } + int firstRow = LittleEndian.getUShort(data, 1); + int firstColumn = LittleEndian.getUShort(data, 3); + return new CellReference(firstRow, firstColumn); + } + public boolean isSame(Formula other) { + return Arrays.equals(_byteEncoding, other._byteEncoding); + } - @Override - public Map> getGenericProperties() { - return GenericRecordUtil.getGenericProperties( - "tokens", this::getTokens, - "expReference", this::getExpReference - ); - } + @Override + public Map> getGenericProperties() { + return GenericRecordUtil.getGenericProperties( + "tokens", this::getTokens, + "expReference", this::getExpReference + ); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCache.java b/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCache.java index 41317f934a..ccb808bbe0 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCache.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCache.java @@ -23,47 +23,47 @@ import java.util.Map; final class FormulaCellCache { - static interface IEntryOperation { - void processEntry(FormulaCellCacheEntry entry); - } + static interface IEntryOperation { + void processEntry(FormulaCellCacheEntry entry); + } - private final Map _formulaEntriesByCell; + private final Map _formulaEntriesByCell; - public FormulaCellCache() { - // assumes the object returned by EvaluationCell.getIdentityKey() has a well behaved hashCode+equals - _formulaEntriesByCell = new HashMap<>(); - } + public FormulaCellCache() { + // assumes the object returned by EvaluationCell.getIdentityKey() has a well behaved hashCode+equals + _formulaEntriesByCell = new HashMap<>(); + } - public CellCacheEntry[] getCacheEntries() { + public CellCacheEntry[] getCacheEntries() { - FormulaCellCacheEntry[] result = new FormulaCellCacheEntry[_formulaEntriesByCell.size()]; - _formulaEntriesByCell.values().toArray(result); - return result; - } + FormulaCellCacheEntry[] result = new FormulaCellCacheEntry[_formulaEntriesByCell.size()]; + _formulaEntriesByCell.values().toArray(result); + return result; + } - public void clear() { - _formulaEntriesByCell.clear(); - } + public void clear() { + _formulaEntriesByCell.clear(); + } - /** - * @return null if not found - */ - public FormulaCellCacheEntry get(EvaluationCell cell) { - return _formulaEntriesByCell.get(cell.getIdentityKey()); - } + /** + * @return null if not found + */ + public FormulaCellCacheEntry get(EvaluationCell cell) { + return _formulaEntriesByCell.get(cell.getIdentityKey()); + } - public void put(EvaluationCell cell, FormulaCellCacheEntry entry) { - _formulaEntriesByCell.put(cell.getIdentityKey(), entry); - } + public void put(EvaluationCell cell, FormulaCellCacheEntry entry) { + _formulaEntriesByCell.put(cell.getIdentityKey(), entry); + } - public FormulaCellCacheEntry remove(EvaluationCell cell) { - return _formulaEntriesByCell.remove(cell.getIdentityKey()); - } + public FormulaCellCacheEntry remove(EvaluationCell cell) { + return _formulaEntriesByCell.remove(cell.getIdentityKey()); + } - public void applyOperation(IEntryOperation operation) { - Iterator i = _formulaEntriesByCell.values().iterator(); - while (i.hasNext()) { - operation.processEntry(i.next()); - } - } + public void applyOperation(IEntryOperation operation) { + Iterator i = _formulaEntriesByCell.values().iterator(); + while (i.hasNext()) { + operation.processEntry(i.next()); + } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCacheEntry.java b/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCacheEntry.java index 9dbb7248c8..0a7b8fbdbf 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCacheEntry.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCacheEntry.java @@ -30,94 +30,94 @@ import org.apache.poi.ss.formula.FormulaUsedBlankCellSet.BookSheetKey; * Stores the cached result of a formula evaluation, along with the set of sensitive input cells */ final class FormulaCellCacheEntry extends CellCacheEntry { - - /** - * Cells 'used' in the current evaluation of the formula corresponding to this cache entry - * - * If any of the following cells change, this cache entry needs to be cleared - */ - private CellCacheEntry[] _sensitiveInputCells; + + /** + * Cells 'used' in the current evaluation of the formula corresponding to this cache entry + * + * If any of the following cells change, this cache entry needs to be cleared + */ + private CellCacheEntry[] _sensitiveInputCells; - private FormulaUsedBlankCellSet _usedBlankCellGroup; + private FormulaUsedBlankCellSet _usedBlankCellGroup; - public FormulaCellCacheEntry() { - // leave fields un-set - } - - public boolean isInputSensitive() { - if (_sensitiveInputCells != null) { - if (_sensitiveInputCells.length > 0 ) { - return true; - } - } - return _usedBlankCellGroup == null ? false : !_usedBlankCellGroup.isEmpty(); - } + public FormulaCellCacheEntry() { + // leave fields un-set + } + + public boolean isInputSensitive() { + if (_sensitiveInputCells != null) { + if (_sensitiveInputCells.length > 0 ) { + return true; + } + } + return _usedBlankCellGroup == null ? false : !_usedBlankCellGroup.isEmpty(); + } - public void setSensitiveInputCells(CellCacheEntry[] sensitiveInputCells) { - // need to tell all cells that were previously used, but no longer are, - // that they are not consumed by this cell any more - if (sensitiveInputCells == null) { + public void setSensitiveInputCells(CellCacheEntry[] sensitiveInputCells) { + // need to tell all cells that were previously used, but no longer are, + // that they are not consumed by this cell any more + if (sensitiveInputCells == null) { _sensitiveInputCells = null; - changeConsumingCells(CellCacheEntry.EMPTY_ARRAY); - } else { - _sensitiveInputCells = sensitiveInputCells.clone(); - changeConsumingCells(_sensitiveInputCells); - } - } + changeConsumingCells(CellCacheEntry.EMPTY_ARRAY); + } else { + _sensitiveInputCells = sensitiveInputCells.clone(); + changeConsumingCells(_sensitiveInputCells); + } + } - public void clearFormulaEntry() { - CellCacheEntry[] usedCells = _sensitiveInputCells; - if (usedCells != null) { - for (int i = usedCells.length-1; i>=0; i--) { - usedCells[i].clearConsumingCell(this); - } - } - _sensitiveInputCells = null; - clearValue(); - } - - private void changeConsumingCells(CellCacheEntry[] usedCells) { + public void clearFormulaEntry() { + CellCacheEntry[] usedCells = _sensitiveInputCells; + if (usedCells != null) { + for (int i = usedCells.length-1; i>=0; i--) { + usedCells[i].clearConsumingCell(this); + } + } + _sensitiveInputCells = null; + clearValue(); + } + + private void changeConsumingCells(CellCacheEntry[] usedCells) { - CellCacheEntry[] prevUsedCells = _sensitiveInputCells; - int nUsed = usedCells.length; - for (int i = 0; i < nUsed; i++) { - usedCells[i].addConsumingCell(this); - } - if (prevUsedCells == null) { - return; - } - int nPrevUsed = prevUsedCells.length; - if (nPrevUsed < 1) { - return; - } - Set usedSet; - if (nUsed < 1) { - usedSet = Collections.emptySet(); - } else { - usedSet = new HashSet<>(nUsed * 3 / 2); - usedSet.addAll(Arrays.asList(usedCells).subList(0, nUsed)); - } - for (int i = 0; i < nPrevUsed; i++) { - CellCacheEntry prevUsed = prevUsedCells[i]; - if (!usedSet.contains(prevUsed)) { - // previously was used by cellLoc, but not anymore - prevUsed.clearConsumingCell(this); - } - } - } + CellCacheEntry[] prevUsedCells = _sensitiveInputCells; + int nUsed = usedCells.length; + for (int i = 0; i < nUsed; i++) { + usedCells[i].addConsumingCell(this); + } + if (prevUsedCells == null) { + return; + } + int nPrevUsed = prevUsedCells.length; + if (nPrevUsed < 1) { + return; + } + Set usedSet; + if (nUsed < 1) { + usedSet = Collections.emptySet(); + } else { + usedSet = new HashSet<>(nUsed * 3 / 2); + usedSet.addAll(Arrays.asList(usedCells).subList(0, nUsed)); + } + for (int i = 0; i < nPrevUsed; i++) { + CellCacheEntry prevUsed = prevUsedCells[i]; + if (!usedSet.contains(prevUsed)) { + // previously was used by cellLoc, but not anymore + prevUsed.clearConsumingCell(this); + } + } + } - public void updateFormulaResult(ValueEval result, CellCacheEntry[] sensitiveInputCells, FormulaUsedBlankCellSet usedBlankAreas) { - updateValue(result); - setSensitiveInputCells(sensitiveInputCells); - _usedBlankCellGroup = usedBlankAreas; - } + public void updateFormulaResult(ValueEval result, CellCacheEntry[] sensitiveInputCells, FormulaUsedBlankCellSet usedBlankAreas) { + updateValue(result); + setSensitiveInputCells(sensitiveInputCells); + _usedBlankCellGroup = usedBlankAreas; + } - public void notifyUpdatedBlankCell(BookSheetKey bsk, int rowIndex, int columnIndex, IEvaluationListener evaluationListener) { - if (_usedBlankCellGroup != null) { - if (_usedBlankCellGroup.containsCell(bsk, rowIndex, columnIndex)) { - clearFormulaEntry(); - recurseClearCachedFormulaResults(evaluationListener); - } - } - } + public void notifyUpdatedBlankCell(BookSheetKey bsk, int rowIndex, int columnIndex, IEvaluationListener evaluationListener) { + if (_usedBlankCellGroup != null) { + if (_usedBlankCellGroup.containsCell(bsk, rowIndex, columnIndex)) { + clearFormulaEntry(); + recurseClearCachedFormulaResults(evaluationListener); + } + } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCacheEntrySet.java b/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCacheEntrySet.java index aff5522755..d4a376c4d6 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCacheEntrySet.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/FormulaCellCacheEntrySet.java @@ -25,129 +25,129 @@ package org.apache.poi.ss.formula; * thousands of formula cells with multiple interdependencies, the savings can be very significant. */ final class FormulaCellCacheEntrySet { - private static final FormulaCellCacheEntry[] EMPTY_ARRAY = { }; + private static final FormulaCellCacheEntry[] EMPTY_ARRAY = { }; - private int _size; - private FormulaCellCacheEntry[] _arr; + private int _size; + private FormulaCellCacheEntry[] _arr; - public FormulaCellCacheEntrySet() { - _arr = EMPTY_ARRAY; - } + public FormulaCellCacheEntrySet() { + _arr = EMPTY_ARRAY; + } - public FormulaCellCacheEntry[] toArray() { - int nItems = _size; - if (nItems < 1) { - return EMPTY_ARRAY; - } - FormulaCellCacheEntry[] result = new FormulaCellCacheEntry[nItems]; - int j=0; - for(int i=0; i<_arr.length; i++) { - FormulaCellCacheEntry cce = _arr[i]; - if (cce != null) { - result[j++] = cce; - } - } - if (j!= nItems) { - throw new IllegalStateException("size mismatch"); - } - return result; - } + public FormulaCellCacheEntry[] toArray() { + int nItems = _size; + if (nItems < 1) { + return EMPTY_ARRAY; + } + FormulaCellCacheEntry[] result = new FormulaCellCacheEntry[nItems]; + int j=0; + for(int i=0; i<_arr.length; i++) { + FormulaCellCacheEntry cce = _arr[i]; + if (cce != null) { + result[j++] = cce; + } + } + if (j!= nItems) { + throw new IllegalStateException("size mismatch"); + } + return result; + } - public void add(CellCacheEntry cce) { - if (_size * 3 >= _arr.length * 2) { - // re-hash - FormulaCellCacheEntry[] prevArr = _arr; - FormulaCellCacheEntry[] newArr = new FormulaCellCacheEntry[4 + _arr.length * 3 / 2]; // grow 50% - for(int i=0; i= _arr.length * 2) { + // re-hash + FormulaCellCacheEntry[] prevArr = _arr; + FormulaCellCacheEntry[] newArr = new FormulaCellCacheEntry[4 + _arr.length * 3 / 2]; // grow 50% + for(int i=0; i 8) { - // re-hash - boolean found = false; - FormulaCellCacheEntry[] prevArr = _arr; - FormulaCellCacheEntry[] newArr = new FormulaCellCacheEntry[_arr.length / 2]; // shrink 50% - for(int i=0; i 8) { + // re-hash + boolean found = false; + FormulaCellCacheEntry[] prevArr = _arr; + FormulaCellCacheEntry[] newArr = new FormulaCellCacheEntry[_arr.length / 2]; // shrink 50% + for(int i=0; i _rectangleGroups; - private int _currentRowIndex; - private int _firstColumnIndex; - private int _lastColumnIndex; - private BlankCellRectangleGroup _currentRectangleGroup; + private static final class BlankCellSheetGroup { + private final List _rectangleGroups; + private int _currentRowIndex; + private int _firstColumnIndex; + private int _lastColumnIndex; + private BlankCellRectangleGroup _currentRectangleGroup; private int _lastDefinedRow; - public BlankCellSheetGroup(int lastDefinedRow) { - _rectangleGroups = new ArrayList<>(); - _currentRowIndex = -1; - _lastDefinedRow = lastDefinedRow; - } + public BlankCellSheetGroup(int lastDefinedRow) { + _rectangleGroups = new ArrayList<>(); + _currentRowIndex = -1; + _lastDefinedRow = lastDefinedRow; + } - public void addCell(int rowIndex, int columnIndex) { - if (rowIndex > _lastDefinedRow) return; - - if (_currentRowIndex == -1) { - _currentRowIndex = rowIndex; - _firstColumnIndex = columnIndex; - _lastColumnIndex = columnIndex; - } else { - if (_currentRowIndex == rowIndex && _lastColumnIndex+1 == columnIndex) { - _lastColumnIndex = columnIndex; - } else { - // cell does not fit on end of current row - if (_currentRectangleGroup == null) { - _currentRectangleGroup = new BlankCellRectangleGroup(_currentRowIndex, _firstColumnIndex, _lastColumnIndex); - } else { - if (!_currentRectangleGroup.acceptRow(_currentRowIndex, _firstColumnIndex, _lastColumnIndex)) { - _rectangleGroups.add(_currentRectangleGroup); - _currentRectangleGroup = new BlankCellRectangleGroup(_currentRowIndex, _firstColumnIndex, _lastColumnIndex); - } - } - _currentRowIndex = rowIndex; - _firstColumnIndex = columnIndex; - _lastColumnIndex = columnIndex; - } - } - } + public void addCell(int rowIndex, int columnIndex) { + if (rowIndex > _lastDefinedRow) return; + + if (_currentRowIndex == -1) { + _currentRowIndex = rowIndex; + _firstColumnIndex = columnIndex; + _lastColumnIndex = columnIndex; + } else { + if (_currentRowIndex == rowIndex && _lastColumnIndex+1 == columnIndex) { + _lastColumnIndex = columnIndex; + } else { + // cell does not fit on end of current row + if (_currentRectangleGroup == null) { + _currentRectangleGroup = new BlankCellRectangleGroup(_currentRowIndex, _firstColumnIndex, _lastColumnIndex); + } else { + if (!_currentRectangleGroup.acceptRow(_currentRowIndex, _firstColumnIndex, _lastColumnIndex)) { + _rectangleGroups.add(_currentRectangleGroup); + _currentRectangleGroup = new BlankCellRectangleGroup(_currentRowIndex, _firstColumnIndex, _lastColumnIndex); + } + } + _currentRowIndex = rowIndex; + _firstColumnIndex = columnIndex; + _lastColumnIndex = columnIndex; + } + } + } - public boolean containsCell(int rowIndex, int columnIndex) { - if (rowIndex > _lastDefinedRow) return true; - - for (int i=_rectangleGroups.size()-1; i>=0; i--) { - BlankCellRectangleGroup bcrg = _rectangleGroups.get(i); - if (bcrg.containsCell(rowIndex, columnIndex)) { - return true; - } - } - if(_currentRectangleGroup != null && _currentRectangleGroup.containsCell(rowIndex, columnIndex)) { - return true; - } - if (_currentRowIndex != -1 && _currentRowIndex == rowIndex) { - if (_firstColumnIndex <= columnIndex && columnIndex <= _lastColumnIndex) { - return true; - } - } - return false; - } - } + public boolean containsCell(int rowIndex, int columnIndex) { + if (rowIndex > _lastDefinedRow) return true; + + for (int i=_rectangleGroups.size()-1; i>=0; i--) { + BlankCellRectangleGroup bcrg = _rectangleGroups.get(i); + if (bcrg.containsCell(rowIndex, columnIndex)) { + return true; + } + } + if(_currentRectangleGroup != null && _currentRectangleGroup.containsCell(rowIndex, columnIndex)) { + return true; + } + if (_currentRowIndex != -1 && _currentRowIndex == rowIndex) { + if (_firstColumnIndex <= columnIndex && columnIndex <= _lastColumnIndex) { + return true; + } + } + return false; + } + } - private static final class BlankCellRectangleGroup { + private static final class BlankCellRectangleGroup { - private final int _firstRowIndex; - private final int _firstColumnIndex; - private final int _lastColumnIndex; - private int _lastRowIndex; + private final int _firstRowIndex; + private final int _firstColumnIndex; + private final int _lastColumnIndex; + private int _lastRowIndex; - public BlankCellRectangleGroup(int firstRowIndex, int firstColumnIndex, int lastColumnIndex) { - _firstRowIndex = firstRowIndex; - _firstColumnIndex = firstColumnIndex; - _lastColumnIndex = lastColumnIndex; - _lastRowIndex = firstRowIndex; - } + public BlankCellRectangleGroup(int firstRowIndex, int firstColumnIndex, int lastColumnIndex) { + _firstRowIndex = firstRowIndex; + _firstColumnIndex = firstColumnIndex; + _lastColumnIndex = lastColumnIndex; + _lastRowIndex = firstRowIndex; + } - public boolean containsCell(int rowIndex, int columnIndex) { - if (columnIndex < _firstColumnIndex) { - return false; - } - if (columnIndex > _lastColumnIndex) { - return false; - } - if (rowIndex < _firstRowIndex) { - return false; - } - if (rowIndex > _lastRowIndex) { - return false; - } - return true; - } + public boolean containsCell(int rowIndex, int columnIndex) { + if (columnIndex < _firstColumnIndex) { + return false; + } + if (columnIndex > _lastColumnIndex) { + return false; + } + if (rowIndex < _firstRowIndex) { + return false; + } + if (rowIndex > _lastRowIndex) { + return false; + } + return true; + } - public boolean acceptRow(int rowIndex, int firstColumnIndex, int lastColumnIndex) { - if (firstColumnIndex != _firstColumnIndex) { - return false; - } - if (lastColumnIndex != _lastColumnIndex) { - return false; - } - if (rowIndex != _lastRowIndex+1) { - return false; - } - _lastRowIndex = rowIndex; - return true; - } - @Override + public boolean acceptRow(int rowIndex, int firstColumnIndex, int lastColumnIndex) { + if (firstColumnIndex != _firstColumnIndex) { + return false; + } + if (lastColumnIndex != _lastColumnIndex) { + return false; + } + if (rowIndex != _lastRowIndex+1) { + return false; + } + _lastRowIndex = rowIndex; + return true; + } + @Override public String toString() { - StringBuilder sb = new StringBuilder(64); - CellReference crA = new CellReference(_firstRowIndex, _firstColumnIndex, false, false); - CellReference crB = new CellReference(_lastRowIndex, _lastColumnIndex, false, false); - sb.append(getClass().getName()); - sb.append(" [").append(crA.formatAsString()).append(':').append(crB.formatAsString()).append("]"); - return sb.toString(); - } - } + StringBuilder sb = new StringBuilder(64); + CellReference crA = new CellReference(_firstRowIndex, _firstColumnIndex, false, false); + CellReference crB = new CellReference(_lastRowIndex, _lastColumnIndex, false, false); + sb.append(getClass().getName()); + sb.append(" [").append(crA.formatAsString()).append(':').append(crB.formatAsString()).append("]"); + return sb.toString(); + } + } - private final Map _sheetGroupsByBookSheet; + private final Map _sheetGroupsByBookSheet; - public FormulaUsedBlankCellSet() { - _sheetGroupsByBookSheet = new HashMap<>(); - } + public FormulaUsedBlankCellSet() { + _sheetGroupsByBookSheet = new HashMap<>(); + } - public void addCell(EvaluationWorkbook evalWorkbook, int bookIndex, int sheetIndex, int rowIndex, int columnIndex) { - BlankCellSheetGroup sbcg = getSheetGroup(evalWorkbook, bookIndex, sheetIndex); - sbcg.addCell(rowIndex, columnIndex); - } + public void addCell(EvaluationWorkbook evalWorkbook, int bookIndex, int sheetIndex, int rowIndex, int columnIndex) { + BlankCellSheetGroup sbcg = getSheetGroup(evalWorkbook, bookIndex, sheetIndex); + sbcg.addCell(rowIndex, columnIndex); + } - private BlankCellSheetGroup getSheetGroup(EvaluationWorkbook evalWorkbook, int bookIndex, int sheetIndex) { - BookSheetKey key = new BookSheetKey(bookIndex, sheetIndex); + private BlankCellSheetGroup getSheetGroup(EvaluationWorkbook evalWorkbook, int bookIndex, int sheetIndex) { + BookSheetKey key = new BookSheetKey(bookIndex, sheetIndex); - BlankCellSheetGroup result = _sheetGroupsByBookSheet.get(key); - if (result == null) { - result = new BlankCellSheetGroup(evalWorkbook.getSheet(sheetIndex).getLastRowNum()); - _sheetGroupsByBookSheet.put(key, result); - } - return result; - } + BlankCellSheetGroup result = _sheetGroupsByBookSheet.get(key); + if (result == null) { + result = new BlankCellSheetGroup(evalWorkbook.getSheet(sheetIndex).getLastRowNum()); + _sheetGroupsByBookSheet.put(key, result); + } + return result; + } - public boolean containsCell(BookSheetKey key, int rowIndex, int columnIndex) { - BlankCellSheetGroup bcsg = _sheetGroupsByBookSheet.get(key); - if (bcsg == null) { - return false; - } - return bcsg.containsCell(rowIndex, columnIndex); - } + public boolean containsCell(BookSheetKey key, int rowIndex, int columnIndex) { + BlankCellSheetGroup bcsg = _sheetGroupsByBookSheet.get(key); + if (bcsg == null) { + return false; + } + return bcsg.containsCell(rowIndex, columnIndex); + } - public boolean isEmpty() { - return _sheetGroupsByBookSheet.isEmpty(); - } + public boolean isEmpty() { + return _sheetGroupsByBookSheet.isEmpty(); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/IEvaluationListener.java b/poi/src/main/java/org/apache/poi/ss/formula/IEvaluationListener.java index a7e34fae86..9a36315473 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/IEvaluationListener.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/IEvaluationListener.java @@ -25,28 +25,28 @@ import org.apache.poi.ss.formula.eval.ValueEval; * For POI internal testing use only */ interface IEvaluationListener { - /** - * A (mostly) opaque interface to allow test clients to trace cache values - * Each spreadsheet cell gets one unique cache entry instance. These objects - * are safe to use as keys in {@link java.util.HashMap}s - */ - interface ICacheEntry { - ValueEval getValue(); - } + /** + * A (mostly) opaque interface to allow test clients to trace cache values + * Each spreadsheet cell gets one unique cache entry instance. These objects + * are safe to use as keys in {@link java.util.HashMap}s + */ + interface ICacheEntry { + ValueEval getValue(); + } - void onCacheHit(int sheetIndex, int rowIndex, int columnIndex, ValueEval result); - void onReadPlainValue(int sheetIndex, int rowIndex, int columnIndex, ICacheEntry entry); - void onStartEvaluate(EvaluationCell cell, ICacheEntry entry); - void onEndEvaluate(ICacheEntry entry, ValueEval result); - void onClearWholeCache(); - void onClearCachedValue(ICacheEntry entry); - /** - * Internally, formula {@link ICacheEntry}s are stored in sets which may change ordering due - * to seemingly trivial changes. This method is provided to make the order of call-backs to - * {@link #onClearDependentCachedValue(ICacheEntry, int)} more deterministic. - */ - void sortDependentCachedValues(ICacheEntry[] formulaCells); - void onClearDependentCachedValue(ICacheEntry formulaCell, int depth); - void onChangeFromBlankValue(int sheetIndex, int rowIndex, int columnIndex, - EvaluationCell cell, ICacheEntry entry); + void onCacheHit(int sheetIndex, int rowIndex, int columnIndex, ValueEval result); + void onReadPlainValue(int sheetIndex, int rowIndex, int columnIndex, ICacheEntry entry); + void onStartEvaluate(EvaluationCell cell, ICacheEntry entry); + void onEndEvaluate(ICacheEntry entry, ValueEval result); + void onClearWholeCache(); + void onClearCachedValue(ICacheEntry entry); + /** + * Internally, formula {@link ICacheEntry}s are stored in sets which may change ordering due + * to seemingly trivial changes. This method is provided to make the order of call-backs to + * {@link #onClearDependentCachedValue(ICacheEntry, int)} more deterministic. + */ + void sortDependentCachedValues(ICacheEntry[] formulaCells); + void onClearDependentCachedValue(ICacheEntry formulaCell, int depth); + void onChangeFromBlankValue(int sheetIndex, int rowIndex, int columnIndex, + EvaluationCell cell, ICacheEntry entry); } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/IStabilityClassifier.java b/poi/src/main/java/org/apache/poi/ss/formula/IStabilityClassifier.java index 7d1fbedad6..ec20d26ca3 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/IStabilityClassifier.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/IStabilityClassifier.java @@ -55,26 +55,26 @@ package org.apache.poi.ss.formula; */ public interface IStabilityClassifier { - /** - * Convenience implementation for situations where all cell definitions remain fixed after - * evaluation begins. - */ - IStabilityClassifier TOTALLY_IMMUTABLE = new IStabilityClassifier() { - public boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex) { - return true; - } - }; + /** + * Convenience implementation for situations where all cell definitions remain fixed after + * evaluation begins. + */ + IStabilityClassifier TOTALLY_IMMUTABLE = new IStabilityClassifier() { + public boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex) { + return true; + } + }; - /** - * Checks if a cell's value(/formula) is fixed - in other words - not expected to be modified - * between calls to the evaluator. (Note - this is an independent concept from whether a - * formula cell's evaluated value may change during successive calls to the evaluator). - * - * @param sheetIndex zero based index into workbook sheet list - * @param rowIndex zero based row index of cell - * @param columnIndex zero based column index of cell - * @return false if the evaluating application may need to modify the specified - * cell between calls to the evaluator. - */ - boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex); + /** + * Checks if a cell's value(/formula) is fixed - in other words - not expected to be modified + * between calls to the evaluator. (Note - this is an independent concept from whether a + * formula cell's evaluated value may change during successive calls to the evaluator). + * + * @param sheetIndex zero based index into workbook sheet list + * @param rowIndex zero based row index of cell + * @param columnIndex zero based column index of cell + * @return false if the evaluating application may need to modify the specified + * cell between calls to the evaluator. + */ + boolean isCellFinal(int sheetIndex, int rowIndex, int columnIndex); } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/LazyAreaEval.java b/poi/src/main/java/org/apache/poi/ss/formula/LazyAreaEval.java index 5510b72e19..bb33f870f8 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/LazyAreaEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/LazyAreaEval.java @@ -28,74 +28,74 @@ import org.apache.poi.ss.util.CellReference; * Provides Lazy Evaluation to 3D Ranges */ final class LazyAreaEval extends AreaEvalBase { - private final SheetRangeEvaluator _evaluator; + private final SheetRangeEvaluator _evaluator; - LazyAreaEval(AreaI ptg, SheetRangeEvaluator evaluator) { - super(ptg, evaluator); - _evaluator = evaluator; - } + LazyAreaEval(AreaI ptg, SheetRangeEvaluator evaluator) { + super(ptg, evaluator); + _evaluator = evaluator; + } - public LazyAreaEval(int firstRowIndex, int firstColumnIndex, int lastRowIndex, - int lastColumnIndex, SheetRangeEvaluator evaluator) { - super(evaluator, firstRowIndex, firstColumnIndex, lastRowIndex, lastColumnIndex); - _evaluator = evaluator; - } + public LazyAreaEval(int firstRowIndex, int firstColumnIndex, int lastRowIndex, + int lastColumnIndex, SheetRangeEvaluator evaluator) { + super(evaluator, firstRowIndex, firstColumnIndex, lastRowIndex, lastColumnIndex); + _evaluator = evaluator; + } @Override - public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) { + public ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex) { return getRelativeValue(getFirstSheetIndex(), relativeRowIndex, relativeColumnIndex); } @Override - public ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex) { - int rowIx = (relativeRowIndex + getFirstRow() ) ; - int colIx = (relativeColumnIndex + getFirstColumn() ) ; + public ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex) { + int rowIx = (relativeRowIndex + getFirstRow() ) ; + int colIx = (relativeColumnIndex + getFirstColumn() ) ; - return _evaluator.getEvalForCell(sheetIndex, rowIx, colIx); - } + return _evaluator.getEvalForCell(sheetIndex, rowIx, colIx); + } - @Override - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { - AreaI area = new OffsetArea(getFirstRow(), getFirstColumn(), - relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); + @Override + public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { + AreaI area = new OffsetArea(getFirstRow(), getFirstColumn(), + relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); - return new LazyAreaEval(area, _evaluator); - } - @Override + return new LazyAreaEval(area, _evaluator); + } + @Override public LazyAreaEval getRow(int rowIndex) { - if (rowIndex >= getHeight()) { - throw new IllegalArgumentException("Invalid rowIndex " + rowIndex - + ". Allowable range is (0.." + getHeight() + ")."); - } - int absRowIx = getFirstRow() + rowIndex; - return new LazyAreaEval(absRowIx, getFirstColumn(), absRowIx, getLastColumn(), _evaluator); - } - @Override - public LazyAreaEval getColumn(int columnIndex) { - if (columnIndex >= getWidth()) { - throw new IllegalArgumentException("Invalid columnIndex " + columnIndex - + ". Allowable range is (0.." + getWidth() + ")."); - } - int absColIx = getFirstColumn() + columnIndex; - return new LazyAreaEval(getFirstRow(), absColIx, getLastRow(), absColIx, _evaluator); - } + if (rowIndex >= getHeight()) { + throw new IllegalArgumentException("Invalid rowIndex " + rowIndex + + ". Allowable range is (0.." + getHeight() + ")."); + } + int absRowIx = getFirstRow() + rowIndex; + return new LazyAreaEval(absRowIx, getFirstColumn(), absRowIx, getLastColumn(), _evaluator); + } + @Override + public LazyAreaEval getColumn(int columnIndex) { + if (columnIndex >= getWidth()) { + throw new IllegalArgumentException("Invalid columnIndex " + columnIndex + + ". Allowable range is (0.." + getWidth() + ")."); + } + int absColIx = getFirstColumn() + columnIndex; + return new LazyAreaEval(getFirstRow(), absColIx, getLastRow(), absColIx, _evaluator); + } - public String toString() { - CellReference crA = new CellReference(getFirstRow(), getFirstColumn()); - CellReference crB = new CellReference(getLastRow(), getLastColumn()); - return getClass().getName() + "[" + - _evaluator.getSheetNameRange() + - '!' + - crA.formatAsString() + - ':' + - crB.formatAsString() + - "]"; - } + public String toString() { + CellReference crA = new CellReference(getFirstRow(), getFirstColumn()); + CellReference crB = new CellReference(getLastRow(), getLastColumn()); + return getClass().getName() + "[" + + _evaluator.getSheetNameRange() + + '!' + + crA.formatAsString() + + ':' + + crB.formatAsString() + + "]"; + } /** * @return whether cell at rowIndex and columnIndex is a subtotal */ @Override - public boolean isSubTotal(int rowIndex, int columnIndex){ + public boolean isSubTotal(int rowIndex, int columnIndex){ // delegate the query to the sheet evaluator which has access to internal ptgs SheetRefEvaluator _sre = _evaluator.getSheetEvaluator(_evaluator.getFirstSheetIndex()); return _sre.isSubTotal(getFirstRow() + rowIndex, getFirstColumn() + columnIndex); @@ -105,7 +105,7 @@ final class LazyAreaEval extends AreaEvalBase { * @return whether the row at rowIndex is hidden */ @Override - public boolean isRowHidden(int rowIndex) { + public boolean isRowHidden(int rowIndex) { // delegate the query to the sheet evaluator which has access to internal ptgs SheetRefEvaluator _sre = _evaluator.getSheetEvaluator(_evaluator.getFirstSheetIndex()); return _sre.isRowHidden(getFirstRow() + rowIndex); diff --git a/poi/src/main/java/org/apache/poi/ss/formula/LazyRefEval.java b/poi/src/main/java/org/apache/poi/ss/formula/LazyRefEval.java index 4456c23a62..709756da66 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/LazyRefEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/LazyRefEval.java @@ -28,32 +28,32 @@ import org.apache.poi.ss.util.CellReference; * Provides Lazy Evaluation to a 3D Reference */ public final class LazyRefEval extends RefEvalBase { - private final SheetRangeEvaluator _evaluator; + private final SheetRangeEvaluator _evaluator; - public LazyRefEval(int rowIndex, int columnIndex, SheetRangeEvaluator sre) { - super(sre, rowIndex, columnIndex); - _evaluator = sre; - } + public LazyRefEval(int rowIndex, int columnIndex, SheetRangeEvaluator sre) { + super(sre, rowIndex, columnIndex); + _evaluator = sre; + } - public ValueEval getInnerValueEval(int sheetIndex) { - return _evaluator.getEvalForCell(sheetIndex, getRow(), getColumn()); - } + public ValueEval getInnerValueEval(int sheetIndex) { + return _evaluator.getEvalForCell(sheetIndex, getRow(), getColumn()); + } - public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { + public AreaEval offset(int relFirstRowIx, int relLastRowIx, int relFirstColIx, int relLastColIx) { - AreaI area = new OffsetArea(getRow(), getColumn(), - relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); + AreaI area = new OffsetArea(getRow(), getColumn(), + relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); - return new LazyAreaEval(area, _evaluator); - } + return new LazyAreaEval(area, _evaluator); + } - /** - * @return true if the cell is a subtotal - */ - public boolean isSubTotal() { - SheetRefEvaluator sheetEvaluator = _evaluator.getSheetEvaluator(getFirstSheetIndex()); - return sheetEvaluator.isSubTotal(getRow(), getColumn()); - } + /** + * @return true if the cell is a subtotal + */ + public boolean isSubTotal() { + SheetRefEvaluator sheetEvaluator = _evaluator.getSheetEvaluator(getFirstSheetIndex()); + return sheetEvaluator.isSubTotal(getRow(), getColumn()); + } /** * @return whether the row at rowIndex is hidden @@ -64,12 +64,12 @@ public final class LazyRefEval extends RefEvalBase { return _sre.isRowHidden(getRow()); } - public String toString() { - CellReference cr = new CellReference(getRow(), getColumn()); - return getClass().getName() + "[" + - _evaluator.getSheetNameRange() + - '!' + - cr.formatAsString() + - "]"; - } + public String toString() { + CellReference cr = new CellReference(getRow(), getColumn()); + return getClass().getName() + "[" + + _evaluator.getSheetNameRange() + + '!' + + cr.formatAsString() + + "]"; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/OperandClassTransformer.java b/poi/src/main/java/org/apache/poi/ss/formula/OperandClassTransformer.java index ce5e5b539c..732ee145be 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/OperandClassTransformer.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/OperandClassTransformer.java @@ -55,237 +55,237 @@ import org.apache.poi.ss.formula.ptg.ValueOperatorPtg; */ final class OperandClassTransformer { - private final FormulaType _formulaType; + private final FormulaType _formulaType; - public OperandClassTransformer(FormulaType formulaType) { - _formulaType = formulaType; - } + public OperandClassTransformer(FormulaType formulaType) { + _formulaType = formulaType; + } - /** - * Traverses the supplied formula parse tree, calling {@code Ptg.setClass()} for each non-base - * token to set its operand class. - */ - public void transformFormula(ParseNode rootNode) { - byte rootNodeOperandClass; - switch (_formulaType) { - case CELL: - rootNodeOperandClass = Ptg.CLASS_VALUE; - break; - case ARRAY: - rootNodeOperandClass = Ptg.CLASS_ARRAY; - break; - case NAMEDRANGE: - case DATAVALIDATION_LIST: - rootNodeOperandClass = Ptg.CLASS_REF; - break; - default: - throw new RuntimeException("Incomplete code - formula type (" - + _formulaType + ") not supported yet"); + /** + * Traverses the supplied formula parse tree, calling {@code Ptg.setClass()} for each non-base + * token to set its operand class. + */ + public void transformFormula(ParseNode rootNode) { + byte rootNodeOperandClass; + switch (_formulaType) { + case CELL: + rootNodeOperandClass = Ptg.CLASS_VALUE; + break; + case ARRAY: + rootNodeOperandClass = Ptg.CLASS_ARRAY; + break; + case NAMEDRANGE: + case DATAVALIDATION_LIST: + rootNodeOperandClass = Ptg.CLASS_REF; + break; + default: + throw new RuntimeException("Incomplete code - formula type (" + + _formulaType + ") not supported yet"); - } - transformNode(rootNode, rootNodeOperandClass, false); - } + } + transformNode(rootNode, rootNodeOperandClass, false); + } - /** - * @param callerForceArrayFlag {@code true} if one of the current node's parents is a - * function Ptg which has been changed from default 'V' to 'A' type (due to requirements on - * the function return value). - */ - private void transformNode(ParseNode node, byte desiredOperandClass, - boolean callerForceArrayFlag) { - Ptg token = node.getToken(); - ParseNode[] children = node.getChildren(); - boolean isSimpleValueFunc = isSimpleValueFunction(token); + /** + * @param callerForceArrayFlag {@code true} if one of the current node's parents is a + * function Ptg which has been changed from default 'V' to 'A' type (due to requirements on + * the function return value). + */ + private void transformNode(ParseNode node, byte desiredOperandClass, + boolean callerForceArrayFlag) { + Ptg token = node.getToken(); + ParseNode[] children = node.getChildren(); + boolean isSimpleValueFunc = isSimpleValueFunction(token); - if (isSimpleValueFunc) { - boolean localForceArray = desiredOperandClass == Ptg.CLASS_ARRAY; - for (ParseNode child : children) { - transformNode(child, desiredOperandClass, localForceArray); - } - setSimpleValueFuncClass((AbstractFunctionPtg) token, desiredOperandClass, callerForceArrayFlag); - return; - } + if (isSimpleValueFunc) { + boolean localForceArray = desiredOperandClass == Ptg.CLASS_ARRAY; + for (ParseNode child : children) { + transformNode(child, desiredOperandClass, localForceArray); + } + setSimpleValueFuncClass((AbstractFunctionPtg) token, desiredOperandClass, callerForceArrayFlag); + return; + } - if (isSingleArgSum(token)) { - // Need to process the argument of SUM with transformFunctionNode below - // so make a dummy FuncVarPtg for that call. - token = FuncVarPtg.SUM; - // Note - the tAttrSum token (node.getToken()) is a base - // token so does not need to have its operand class set - } - if (token instanceof ValueOperatorPtg || token instanceof ControlPtg - || token instanceof MemFuncPtg - || token instanceof MemAreaPtg - || token instanceof UnionPtg - || token instanceof IntersectionPtg) { - // Value Operator Ptgs and Control are base tokens, so token will be unchanged - // but any child nodes are processed according to desiredOperandClass and callerForceArrayFlag + if (isSingleArgSum(token)) { + // Need to process the argument of SUM with transformFunctionNode below + // so make a dummy FuncVarPtg for that call. + token = FuncVarPtg.SUM; + // Note - the tAttrSum token (node.getToken()) is a base + // token so does not need to have its operand class set + } + if (token instanceof ValueOperatorPtg || token instanceof ControlPtg + || token instanceof MemFuncPtg + || token instanceof MemAreaPtg + || token instanceof UnionPtg + || token instanceof IntersectionPtg) { + // Value Operator Ptgs and Control are base tokens, so token will be unchanged + // but any child nodes are processed according to desiredOperandClass and callerForceArrayFlag - // As per OOO documentation Sec 3.2.4 "Token Class Transformation", "Step 1" - // All direct operands of value operators that are initially 'R' type will - // be converted to 'V' type. - byte localDesiredOperandClass = desiredOperandClass == Ptg.CLASS_REF ? Ptg.CLASS_VALUE : desiredOperandClass; - for (ParseNode child : children) { - transformNode(child, localDesiredOperandClass, callerForceArrayFlag); - } - return; - } - if (token instanceof AbstractFunctionPtg) { - transformFunctionNode((AbstractFunctionPtg) token, children, desiredOperandClass, callerForceArrayFlag); - return; - } - if (children.length > 0) { - if (token == RangePtg.instance) { - // TODO is any token transformation required under the various ref operators? - return; - } - throw new IllegalStateException("Node should not have any children"); - } + // As per OOO documentation Sec 3.2.4 "Token Class Transformation", "Step 1" + // All direct operands of value operators that are initially 'R' type will + // be converted to 'V' type. + byte localDesiredOperandClass = desiredOperandClass == Ptg.CLASS_REF ? Ptg.CLASS_VALUE : desiredOperandClass; + for (ParseNode child : children) { + transformNode(child, localDesiredOperandClass, callerForceArrayFlag); + } + return; + } + if (token instanceof AbstractFunctionPtg) { + transformFunctionNode((AbstractFunctionPtg) token, children, desiredOperandClass, callerForceArrayFlag); + return; + } + if (children.length > 0) { + if (token == RangePtg.instance) { + // TODO is any token transformation required under the various ref operators? + return; + } + throw new IllegalStateException("Node should not have any children"); + } - if (token.isBaseToken()) { - // nothing to do - return; - } - token.setClass(transformClass(token.getPtgClass(), desiredOperandClass, callerForceArrayFlag)); - } + if (token.isBaseToken()) { + // nothing to do + return; + } + token.setClass(transformClass(token.getPtgClass(), desiredOperandClass, callerForceArrayFlag)); + } - private static boolean isSingleArgSum(Ptg token) { - if (token instanceof AttrPtg) { - AttrPtg attrPtg = (AttrPtg) token; - return attrPtg.isSum(); - } - return false; - } + private static boolean isSingleArgSum(Ptg token) { + if (token instanceof AttrPtg) { + AttrPtg attrPtg = (AttrPtg) token; + return attrPtg.isSum(); + } + return false; + } - private static boolean isSimpleValueFunction(Ptg token) { - if (token instanceof AbstractFunctionPtg) { - AbstractFunctionPtg aptg = (AbstractFunctionPtg) token; - if (aptg.getDefaultOperandClass() != Ptg.CLASS_VALUE) { - return false; - } - int numberOfOperands = aptg.getNumberOfOperands(); - for (int i=numberOfOperands-1; i>=0; i--) { - if (aptg.getParameterClass(i) != Ptg.CLASS_VALUE) { - return false; - } - } - return true; - } - return false; - } + private static boolean isSimpleValueFunction(Ptg token) { + if (token instanceof AbstractFunctionPtg) { + AbstractFunctionPtg aptg = (AbstractFunctionPtg) token; + if (aptg.getDefaultOperandClass() != Ptg.CLASS_VALUE) { + return false; + } + int numberOfOperands = aptg.getNumberOfOperands(); + for (int i=numberOfOperands-1; i>=0; i--) { + if (aptg.getParameterClass(i) != Ptg.CLASS_VALUE) { + return false; + } + } + return true; + } + return false; + } - private byte transformClass(byte currentOperandClass, byte desiredOperandClass, - boolean callerForceArrayFlag) { - switch (desiredOperandClass) { - case Ptg.CLASS_VALUE: - if (!callerForceArrayFlag) { - return Ptg.CLASS_VALUE; - } - // else fall through - case Ptg.CLASS_ARRAY: - return Ptg.CLASS_ARRAY; - case Ptg.CLASS_REF: - if (!callerForceArrayFlag) { - return currentOperandClass; - } - return Ptg.CLASS_REF; - } - throw new IllegalStateException("Unexpected operand class (" + desiredOperandClass + ")"); - } + private byte transformClass(byte currentOperandClass, byte desiredOperandClass, + boolean callerForceArrayFlag) { + switch (desiredOperandClass) { + case Ptg.CLASS_VALUE: + if (!callerForceArrayFlag) { + return Ptg.CLASS_VALUE; + } + // else fall through + case Ptg.CLASS_ARRAY: + return Ptg.CLASS_ARRAY; + case Ptg.CLASS_REF: + if (!callerForceArrayFlag) { + return currentOperandClass; + } + return Ptg.CLASS_REF; + } + throw new IllegalStateException("Unexpected operand class (" + desiredOperandClass + ")"); + } - private void transformFunctionNode(AbstractFunctionPtg afp, ParseNode[] children, - byte desiredOperandClass, boolean callerForceArrayFlag) { + private void transformFunctionNode(AbstractFunctionPtg afp, ParseNode[] children, + byte desiredOperandClass, boolean callerForceArrayFlag) { - boolean localForceArrayFlag; - byte defaultReturnOperandClass = afp.getDefaultOperandClass(); + boolean localForceArrayFlag; + byte defaultReturnOperandClass = afp.getDefaultOperandClass(); - if (callerForceArrayFlag) { - switch (defaultReturnOperandClass) { - case Ptg.CLASS_REF: - if (desiredOperandClass == Ptg.CLASS_REF) { - afp.setClass(Ptg.CLASS_REF); - } else { - afp.setClass(Ptg.CLASS_ARRAY); - } - localForceArrayFlag = false; - break; - case Ptg.CLASS_ARRAY: - afp.setClass(Ptg.CLASS_ARRAY); - localForceArrayFlag = false; - break; - case Ptg.CLASS_VALUE: - afp.setClass(Ptg.CLASS_ARRAY); - localForceArrayFlag = true; - break; - default: - throw new IllegalStateException("Unexpected operand class (" - + defaultReturnOperandClass + ")"); - } - } else { - if (defaultReturnOperandClass == desiredOperandClass) { - localForceArrayFlag = false; - // an alternative would have been to for non-base Ptgs to set their operand class - // from their default, but this would require the call in many subclasses because - // the default OC is not known until the end of the constructor - afp.setClass(defaultReturnOperandClass); - } else { - switch (desiredOperandClass) { - case Ptg.CLASS_VALUE: - // always OK to set functions to return 'value' - afp.setClass(Ptg.CLASS_VALUE); - localForceArrayFlag = false; - break; - case Ptg.CLASS_ARRAY: - switch (defaultReturnOperandClass) { - case Ptg.CLASS_REF: - afp.setClass(Ptg.CLASS_REF); -// afp.setClass(Ptg.CLASS_ARRAY); - break; - case Ptg.CLASS_VALUE: - afp.setClass(Ptg.CLASS_ARRAY); - break; - default: - throw new IllegalStateException("Unexpected operand class (" - + defaultReturnOperandClass + ")"); - } - localForceArrayFlag = (defaultReturnOperandClass == Ptg.CLASS_VALUE); - break; - case Ptg.CLASS_REF: - switch (defaultReturnOperandClass) { - case Ptg.CLASS_ARRAY: - afp.setClass(Ptg.CLASS_ARRAY); - break; - case Ptg.CLASS_VALUE: - afp.setClass(Ptg.CLASS_VALUE); - break; - default: - throw new IllegalStateException("Unexpected operand class (" - + defaultReturnOperandClass + ")"); - } - localForceArrayFlag = false; - break; - default: - throw new IllegalStateException("Unexpected operand class (" - + desiredOperandClass + ")"); - } + if (callerForceArrayFlag) { + switch (defaultReturnOperandClass) { + case Ptg.CLASS_REF: + if (desiredOperandClass == Ptg.CLASS_REF) { + afp.setClass(Ptg.CLASS_REF); + } else { + afp.setClass(Ptg.CLASS_ARRAY); + } + localForceArrayFlag = false; + break; + case Ptg.CLASS_ARRAY: + afp.setClass(Ptg.CLASS_ARRAY); + localForceArrayFlag = false; + break; + case Ptg.CLASS_VALUE: + afp.setClass(Ptg.CLASS_ARRAY); + localForceArrayFlag = true; + break; + default: + throw new IllegalStateException("Unexpected operand class (" + + defaultReturnOperandClass + ")"); + } + } else { + if (defaultReturnOperandClass == desiredOperandClass) { + localForceArrayFlag = false; + // an alternative would have been to for non-base Ptgs to set their operand class + // from their default, but this would require the call in many subclasses because + // the default OC is not known until the end of the constructor + afp.setClass(defaultReturnOperandClass); + } else { + switch (desiredOperandClass) { + case Ptg.CLASS_VALUE: + // always OK to set functions to return 'value' + afp.setClass(Ptg.CLASS_VALUE); + localForceArrayFlag = false; + break; + case Ptg.CLASS_ARRAY: + switch (defaultReturnOperandClass) { + case Ptg.CLASS_REF: + afp.setClass(Ptg.CLASS_REF); +// afp.setClass(Ptg.CLASS_ARRAY); + break; + case Ptg.CLASS_VALUE: + afp.setClass(Ptg.CLASS_ARRAY); + break; + default: + throw new IllegalStateException("Unexpected operand class (" + + defaultReturnOperandClass + ")"); + } + localForceArrayFlag = (defaultReturnOperandClass == Ptg.CLASS_VALUE); + break; + case Ptg.CLASS_REF: + switch (defaultReturnOperandClass) { + case Ptg.CLASS_ARRAY: + afp.setClass(Ptg.CLASS_ARRAY); + break; + case Ptg.CLASS_VALUE: + afp.setClass(Ptg.CLASS_VALUE); + break; + default: + throw new IllegalStateException("Unexpected operand class (" + + defaultReturnOperandClass + ")"); + } + localForceArrayFlag = false; + break; + default: + throw new IllegalStateException("Unexpected operand class (" + + desiredOperandClass + ")"); + } - } - } + } + } - for (int i = 0; i < children.length; i++) { - ParseNode child = children[i]; - byte paramOperandClass = afp.getParameterClass(i); - transformNode(child, paramOperandClass, localForceArrayFlag); - } - } + for (int i = 0; i < children.length; i++) { + ParseNode child = children[i]; + byte paramOperandClass = afp.getParameterClass(i); + transformNode(child, paramOperandClass, localForceArrayFlag); + } + } - private void setSimpleValueFuncClass(AbstractFunctionPtg afp, - byte desiredOperandClass, boolean callerForceArrayFlag) { + private void setSimpleValueFuncClass(AbstractFunctionPtg afp, + byte desiredOperandClass, boolean callerForceArrayFlag) { - if (callerForceArrayFlag || desiredOperandClass == Ptg.CLASS_ARRAY) { - afp.setClass(Ptg.CLASS_ARRAY); - } else { - afp.setClass(Ptg.CLASS_VALUE); - } - } + if (callerForceArrayFlag || desiredOperandClass == Ptg.CLASS_ARRAY) { + afp.setClass(Ptg.CLASS_ARRAY); + } else { + afp.setClass(Ptg.CLASS_VALUE); + } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/OperationEvaluatorFactory.java b/poi/src/main/java/org/apache/poi/ss/formula/OperationEvaluatorFactory.java index 542e026ad9..4dfcb78e12 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/OperationEvaluatorFactory.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/OperationEvaluatorFactory.java @@ -62,84 +62,84 @@ import org.apache.poi.ss.util.CellRangeAddress; */ final class OperationEvaluatorFactory { - private static final Map _instancesByPtgClass = initialiseInstancesMap(); + private static final Map _instancesByPtgClass = initialiseInstancesMap(); - private OperationEvaluatorFactory() { - // no instances of this class - } + private OperationEvaluatorFactory() { + // no instances of this class + } - private static Map initialiseInstancesMap() { - Map m = new HashMap<>(32); + private static Map initialiseInstancesMap() { + Map m = new HashMap<>(32); - m.put(AddPtg.instance.getSid(), TwoOperandNumericOperation.AddEval); // 0x03 - m.put(SubtractPtg.instance.getSid(), TwoOperandNumericOperation.SubtractEval); // 0x04 - m.put(MultiplyPtg.instance.getSid(), TwoOperandNumericOperation.MultiplyEval); // 0x05 - m.put(DividePtg.instance.getSid(), TwoOperandNumericOperation.DivideEval); // 0x06 - m.put(PowerPtg.instance.getSid(), TwoOperandNumericOperation.PowerEval); // 0x07 - m.put(ConcatPtg.instance.getSid(), ConcatEval.instance); // 0x08 - m.put(LessThanPtg.instance.getSid(), RelationalOperationEval.LessThanEval); // 0x09 - m.put(LessEqualPtg.instance.getSid(), RelationalOperationEval.LessEqualEval); // 0x0a - m.put(EqualPtg.instance.getSid(), RelationalOperationEval.EqualEval); // 0x0b - m.put(GreaterEqualPtg.instance.getSid(), RelationalOperationEval.GreaterEqualEval); // 0x0c - m.put(GreaterThanPtg.instance.getSid(), RelationalOperationEval.GreaterThanEval); // 0x0D - m.put(NotEqualPtg.instance.getSid(), RelationalOperationEval.NotEqualEval); // 0x0e - m.put(IntersectionPtg.instance.getSid(), IntersectionEval.instance); // 0x0f - m.put(RangePtg.instance.getSid(), RangeEval.instance); // 0x11 - m.put(UnaryPlusPtg.instance.getSid(), UnaryPlusEval.instance); // 0x12 - m.put(UnaryMinusPtg.instance.getSid(), UnaryMinusEval.instance); // 0x13 - m.put(PercentPtg.instance.getSid(), PercentEval.instance); // 0x14 + m.put(AddPtg.instance.getSid(), TwoOperandNumericOperation.AddEval); // 0x03 + m.put(SubtractPtg.instance.getSid(), TwoOperandNumericOperation.SubtractEval); // 0x04 + m.put(MultiplyPtg.instance.getSid(), TwoOperandNumericOperation.MultiplyEval); // 0x05 + m.put(DividePtg.instance.getSid(), TwoOperandNumericOperation.DivideEval); // 0x06 + m.put(PowerPtg.instance.getSid(), TwoOperandNumericOperation.PowerEval); // 0x07 + m.put(ConcatPtg.instance.getSid(), ConcatEval.instance); // 0x08 + m.put(LessThanPtg.instance.getSid(), RelationalOperationEval.LessThanEval); // 0x09 + m.put(LessEqualPtg.instance.getSid(), RelationalOperationEval.LessEqualEval); // 0x0a + m.put(EqualPtg.instance.getSid(), RelationalOperationEval.EqualEval); // 0x0b + m.put(GreaterEqualPtg.instance.getSid(), RelationalOperationEval.GreaterEqualEval); // 0x0c + m.put(GreaterThanPtg.instance.getSid(), RelationalOperationEval.GreaterThanEval); // 0x0D + m.put(NotEqualPtg.instance.getSid(), RelationalOperationEval.NotEqualEval); // 0x0e + m.put(IntersectionPtg.instance.getSid(), IntersectionEval.instance); // 0x0f + m.put(RangePtg.instance.getSid(), RangeEval.instance); // 0x11 + m.put(UnaryPlusPtg.instance.getSid(), UnaryPlusEval.instance); // 0x12 + m.put(UnaryMinusPtg.instance.getSid(), UnaryMinusEval.instance); // 0x13 + m.put(PercentPtg.instance.getSid(), PercentEval.instance); // 0x14 - return m; - } + return m; + } - /** - * returns the OperationEval concrete impl instance corresponding - * to the supplied operationPtg - */ - public static ValueEval evaluate(OperationPtg ptg, ValueEval[] args, - OperationEvaluationContext ec) { - if(ptg == null) { - throw new IllegalArgumentException("ptg must not be null"); - } - Function result = _instancesByPtgClass.get(ptg.getSid()); - FreeRefFunction udfFunc = null; - if (result == null) { - if (ptg instanceof AbstractFunctionPtg) { - AbstractFunctionPtg fptg = (AbstractFunctionPtg)ptg; - int functionIndex = fptg.getFunctionIndex(); - switch (functionIndex) { - case FunctionMetadataRegistry.FUNCTION_INDEX_INDIRECT: - udfFunc = Indirect.instance; - break; - case FunctionMetadataRegistry.FUNCTION_INDEX_EXTERNAL: - udfFunc = UserDefinedFunction.instance; - break; - default: - result = FunctionEval.getBasicFunction(functionIndex); - break; - } - } - } - if (result != null) { - EvaluationSheet evalSheet = ec.getWorkbook().getSheet(ec.getSheetIndex()); - EvaluationCell evalCell = evalSheet.getCell(ec.getRowIndex(), ec.getColumnIndex()); + /** + * returns the OperationEval concrete impl instance corresponding + * to the supplied operationPtg + */ + public static ValueEval evaluate(OperationPtg ptg, ValueEval[] args, + OperationEvaluationContext ec) { + if(ptg == null) { + throw new IllegalArgumentException("ptg must not be null"); + } + Function result = _instancesByPtgClass.get(ptg.getSid()); + FreeRefFunction udfFunc = null; + if (result == null) { + if (ptg instanceof AbstractFunctionPtg) { + AbstractFunctionPtg fptg = (AbstractFunctionPtg)ptg; + int functionIndex = fptg.getFunctionIndex(); + switch (functionIndex) { + case FunctionMetadataRegistry.FUNCTION_INDEX_INDIRECT: + udfFunc = Indirect.instance; + break; + case FunctionMetadataRegistry.FUNCTION_INDEX_EXTERNAL: + udfFunc = UserDefinedFunction.instance; + break; + default: + result = FunctionEval.getBasicFunction(functionIndex); + break; + } + } + } + if (result != null) { + EvaluationSheet evalSheet = ec.getWorkbook().getSheet(ec.getSheetIndex()); + EvaluationCell evalCell = evalSheet.getCell(ec.getRowIndex(), ec.getColumnIndex()); - if (evalCell != null && result instanceof ArrayFunction) { - ArrayFunction func = (ArrayFunction) result; - if(evalCell.isPartOfArrayFormulaGroup()){ - // array arguments must be evaluated relative to the function defining range - CellRangeAddress ca = evalCell.getArrayFormulaRange(); - return func.evaluateArray(args, ca.getFirstRow(), ca.getFirstColumn()); - } else if (ec.isArraymode()){ - return func.evaluateArray(args, ec.getRowIndex(), ec.getColumnIndex()); - } - } + if (evalCell != null && result instanceof ArrayFunction) { + ArrayFunction func = (ArrayFunction) result; + if(evalCell.isPartOfArrayFormulaGroup()){ + // array arguments must be evaluated relative to the function defining range + CellRangeAddress ca = evalCell.getArrayFormulaRange(); + return func.evaluateArray(args, ca.getFirstRow(), ca.getFirstColumn()); + } else if (ec.isArraymode()){ + return func.evaluateArray(args, ec.getRowIndex(), ec.getColumnIndex()); + } + } - return result.evaluate(args, ec.getRowIndex(), ec.getColumnIndex()); - } else if (udfFunc != null){ - return udfFunc.evaluate(args, ec); - } + return result.evaluate(args, ec.getRowIndex(), ec.getColumnIndex()); + } else if (udfFunc != null){ + return udfFunc.evaluate(args, ec); + } - throw new RuntimeException("Unexpected operation ptg class (" + ptg.getClass().getName() + ")"); - } + throw new RuntimeException("Unexpected operation ptg class (" + ptg.getClass().getName() + ")"); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/ParseNode.java b/poi/src/main/java/org/apache/poi/ss/formula/ParseNode.java index d9f01cec1c..17cb41086e 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/ParseNode.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/ParseNode.java @@ -31,177 +31,177 @@ import org.apache.poi.ss.formula.function.FunctionMetadataRegistry; */ final class ParseNode { - public static final ParseNode[] EMPTY_ARRAY = { }; - private final Ptg _token; - private final ParseNode[] _children; - private final boolean _isIf; - private final int _tokenCount; + public static final ParseNode[] EMPTY_ARRAY = { }; + private final Ptg _token; + private final ParseNode[] _children; + private final boolean _isIf; + private final int _tokenCount; - public ParseNode(Ptg token, ParseNode[] children) { - if (token == null) { - throw new IllegalArgumentException("token must not be null"); - } - _token = token; - _children = children.clone(); - _isIf = isIf(token); - int tokenCount = 1; - for (ParseNode child : children) { - tokenCount += child.getTokenCount(); - } - if (_isIf) { - // there will be 2 or 3 extra tAttr tokens according to whether the false param is present - tokenCount += children.length; - } - _tokenCount = tokenCount; - } - public ParseNode(Ptg token) { - this(token, EMPTY_ARRAY); - } - public ParseNode(Ptg token, ParseNode child0) { - this(token, new ParseNode[] { child0, }); - } - public ParseNode(Ptg token, ParseNode child0, ParseNode child1) { - this(token, new ParseNode[] { child0, child1, }); - } - private int getTokenCount() { - return _tokenCount; - } - public int getEncodedSize() { - int result = _token instanceof ArrayPtg ? ArrayPtg.PLAIN_TOKEN_SIZE : _token.getSize(); - for (ParseNode child : _children) { - result += child.getEncodedSize(); - } - return result; - } + public ParseNode(Ptg token, ParseNode[] children) { + if (token == null) { + throw new IllegalArgumentException("token must not be null"); + } + _token = token; + _children = children.clone(); + _isIf = isIf(token); + int tokenCount = 1; + for (ParseNode child : children) { + tokenCount += child.getTokenCount(); + } + if (_isIf) { + // there will be 2 or 3 extra tAttr tokens according to whether the false param is present + tokenCount += children.length; + } + _tokenCount = tokenCount; + } + public ParseNode(Ptg token) { + this(token, EMPTY_ARRAY); + } + public ParseNode(Ptg token, ParseNode child0) { + this(token, new ParseNode[] { child0, }); + } + public ParseNode(Ptg token, ParseNode child0, ParseNode child1) { + this(token, new ParseNode[] { child0, child1, }); + } + private int getTokenCount() { + return _tokenCount; + } + public int getEncodedSize() { + int result = _token instanceof ArrayPtg ? ArrayPtg.PLAIN_TOKEN_SIZE : _token.getSize(); + for (ParseNode child : _children) { + result += child.getEncodedSize(); + } + return result; + } - /** - * Collects the array of {@code Ptg} tokens for the specified tree. - */ - public static Ptg[] toTokenArray(ParseNode rootNode) { - TokenCollector temp = new TokenCollector(rootNode.getTokenCount()); - rootNode.collectPtgs(temp); - return temp.getResult(); - } - private void collectPtgs(TokenCollector temp) { - if (isIf(_token)) { - collectIfPtgs(temp); - return; - } - boolean isPreFixOperator = _token instanceof MemFuncPtg || _token instanceof MemAreaPtg; - if (isPreFixOperator) { - temp.add(_token); - } - for (int i=0; i< getChildren().length; i++) { - getChildren()[i].collectPtgs(temp); - } - if (!isPreFixOperator) { - temp.add(_token); - } - } - /** - * The IF() function gets marked up with two or three tAttr tokens. - * Similar logic will be required for CHOOSE() when it is supported - * - * See excelfileformat.pdf sec 3.10.5 "tAttr (19H) - */ - private void collectIfPtgs(TokenCollector temp) { + /** + * Collects the array of {@code Ptg} tokens for the specified tree. + */ + public static Ptg[] toTokenArray(ParseNode rootNode) { + TokenCollector temp = new TokenCollector(rootNode.getTokenCount()); + rootNode.collectPtgs(temp); + return temp.getResult(); + } + private void collectPtgs(TokenCollector temp) { + if (isIf(_token)) { + collectIfPtgs(temp); + return; + } + boolean isPreFixOperator = _token instanceof MemFuncPtg || _token instanceof MemAreaPtg; + if (isPreFixOperator) { + temp.add(_token); + } + for (int i=0; i< getChildren().length; i++) { + getChildren()[i].collectPtgs(temp); + } + if (!isPreFixOperator) { + temp.add(_token); + } + } + /** + * The IF() function gets marked up with two or three tAttr tokens. + * Similar logic will be required for CHOOSE() when it is supported + * + * See excelfileformat.pdf sec 3.10.5 "tAttr (19H) + */ + private void collectIfPtgs(TokenCollector temp) { - // condition goes first - getChildren()[0].collectPtgs(temp); + // condition goes first + getChildren()[0].collectPtgs(temp); - // placeholder for tAttrIf - int ifAttrIndex = temp.createPlaceholder(); + // placeholder for tAttrIf + int ifAttrIndex = temp.createPlaceholder(); - // true parameter - getChildren()[1].collectPtgs(temp); + // true parameter + getChildren()[1].collectPtgs(temp); - // placeholder for first skip attr - int skipAfterTrueParamIndex = temp.createPlaceholder(); - int trueParamSize = temp.sumTokenSizes(ifAttrIndex+1, skipAfterTrueParamIndex); + // placeholder for first skip attr + int skipAfterTrueParamIndex = temp.createPlaceholder(); + int trueParamSize = temp.sumTokenSizes(ifAttrIndex+1, skipAfterTrueParamIndex); - AttrPtg attrIf = AttrPtg.createIf(trueParamSize + 4); // distance to start of false parameter/tFuncVar. +4 for tAttrSkip after true + AttrPtg attrIf = AttrPtg.createIf(trueParamSize + 4); // distance to start of false parameter/tFuncVar. +4 for tAttrSkip after true - if (getChildren().length > 2) { - // false param present + if (getChildren().length > 2) { + // false param present - // false parameter - getChildren()[2].collectPtgs(temp); + // false parameter + getChildren()[2].collectPtgs(temp); - int skipAfterFalseParamIndex = temp.createPlaceholder(); + int skipAfterFalseParamIndex = temp.createPlaceholder(); - int falseParamSize = temp.sumTokenSizes(skipAfterTrueParamIndex+1, skipAfterFalseParamIndex); + int falseParamSize = temp.sumTokenSizes(skipAfterTrueParamIndex+1, skipAfterFalseParamIndex); - AttrPtg attrSkipAfterTrue = AttrPtg.createSkip(falseParamSize + 4 + 4 - 1); // 1 less than distance to end of if FuncVar(size=4). +4 for attr skip before - AttrPtg attrSkipAfterFalse = AttrPtg.createSkip(4 - 1); // 1 less than distance to end of if FuncVar(size=4). + AttrPtg attrSkipAfterTrue = AttrPtg.createSkip(falseParamSize + 4 + 4 - 1); // 1 less than distance to end of if FuncVar(size=4). +4 for attr skip before + AttrPtg attrSkipAfterFalse = AttrPtg.createSkip(4 - 1); // 1 less than distance to end of if FuncVar(size=4). - temp.setPlaceholder(ifAttrIndex, attrIf); - temp.setPlaceholder(skipAfterTrueParamIndex, attrSkipAfterTrue); - temp.setPlaceholder(skipAfterFalseParamIndex, attrSkipAfterFalse); - } else { - // false parameter not present - AttrPtg attrSkipAfterTrue = AttrPtg.createSkip(4 - 1); // 1 less than distance to end of if FuncVar(size=4). + temp.setPlaceholder(ifAttrIndex, attrIf); + temp.setPlaceholder(skipAfterTrueParamIndex, attrSkipAfterTrue); + temp.setPlaceholder(skipAfterFalseParamIndex, attrSkipAfterFalse); + } else { + // false parameter not present + AttrPtg attrSkipAfterTrue = AttrPtg.createSkip(4 - 1); // 1 less than distance to end of if FuncVar(size=4). - temp.setPlaceholder(ifAttrIndex, attrIf); - temp.setPlaceholder(skipAfterTrueParamIndex, attrSkipAfterTrue); - } - temp.add(_token); - } + temp.setPlaceholder(ifAttrIndex, attrIf); + temp.setPlaceholder(skipAfterTrueParamIndex, attrSkipAfterTrue); + } + temp.add(_token); + } - private static boolean isIf(Ptg token) { - if (token instanceof FuncVarPtg) { - FuncVarPtg func = (FuncVarPtg) token; - return FunctionMetadataRegistry.FUNCTION_NAME_IF.equals(func.getName()); - } - return false; - } + private static boolean isIf(Ptg token) { + if (token instanceof FuncVarPtg) { + FuncVarPtg func = (FuncVarPtg) token; + return FunctionMetadataRegistry.FUNCTION_NAME_IF.equals(func.getName()); + } + return false; + } - public Ptg getToken() { - return _token; - } + public Ptg getToken() { + return _token; + } - public ParseNode[] getChildren() { - return _children; - } + public ParseNode[] getChildren() { + return _children; + } - private static final class TokenCollector { + private static final class TokenCollector { - private final Ptg[] _ptgs; - private int _offset; + private final Ptg[] _ptgs; + private int _offset; - public TokenCollector(int tokenCount) { - _ptgs = new Ptg[tokenCount]; - _offset = 0; - } + public TokenCollector(int tokenCount) { + _ptgs = new Ptg[tokenCount]; + _offset = 0; + } - public int sumTokenSizes(int fromIx, int toIx) { - int result = 0; - for (int i=fromIx; i>> 32)) + 17 * _rowIndex; - } + return (int)(_bookSheetColumn ^ (_bookSheetColumn >>> 32)) + 17 * _rowIndex; + } - @Override + @Override public boolean equals(Object obj) { - if (!(obj instanceof Loc)) { - return false; - } - Loc other = (Loc) obj; - return _bookSheetColumn == other._bookSheetColumn && _rowIndex == other._rowIndex; - } + if (!(obj instanceof Loc)) { + return false; + } + Loc other = (Loc) obj; + return _bookSheetColumn == other._bookSheetColumn && _rowIndex == other._rowIndex; + } - public int getRowIndex() { - return _rowIndex; - } + public int getRowIndex() { + return _rowIndex; + } - public int getColumnIndex() { + public int getColumnIndex() { return (int)(_bookSheetColumn & 0x000FFFF); - } + } public int getSheetIndex() { return (int)((_bookSheetColumn >> 32) & 0xFFFF); @@ -73,27 +73,27 @@ final class PlainCellCache { public int getBookIndex() { return (int)((_bookSheetColumn >> 48) & 0xFFFF); } - } + } - private Map _plainValueEntriesByLoc; + private Map _plainValueEntriesByLoc; - public PlainCellCache() { - _plainValueEntriesByLoc = new HashMap<>(); - } + public PlainCellCache() { + _plainValueEntriesByLoc = new HashMap<>(); + } - public void put(Loc key, PlainValueCellCacheEntry cce) { - _plainValueEntriesByLoc.put(key, cce); - } + public void put(Loc key, PlainValueCellCacheEntry cce) { + _plainValueEntriesByLoc.put(key, cce); + } - public void clear() { - _plainValueEntriesByLoc.clear(); - } + public void clear() { + _plainValueEntriesByLoc.clear(); + } - public PlainValueCellCacheEntry get(Loc key) { - return _plainValueEntriesByLoc.get(key); - } + public PlainValueCellCacheEntry get(Loc key) { + return _plainValueEntriesByLoc.get(key); + } - public void remove(Loc key) { - _plainValueEntriesByLoc.remove(key); - } + public void remove(Loc key) { + _plainValueEntriesByLoc.remove(key); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/PlainValueCellCacheEntry.java b/poi/src/main/java/org/apache/poi/ss/formula/PlainValueCellCacheEntry.java index 4b62110669..b39517ff4c 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/PlainValueCellCacheEntry.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/PlainValueCellCacheEntry.java @@ -23,7 +23,7 @@ import org.apache.poi.ss.formula.eval.ValueEval; * Used for non-formula cells, primarily to keep track of the referencing (formula) cells. */ final class PlainValueCellCacheEntry extends CellCacheEntry { - public PlainValueCellCacheEntry(ValueEval value) { - updateValue(value); - } + public PlainValueCellCacheEntry(ValueEval value) { + updateValue(value); + } } \ No newline at end of file diff --git a/poi/src/main/java/org/apache/poi/ss/formula/SheetNameFormatter.java b/poi/src/main/java/org/apache/poi/ss/formula/SheetNameFormatter.java index 9e847ebdc1..11f3e0802b 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/SheetNameFormatter.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/SheetNameFormatter.java @@ -29,27 +29,27 @@ import org.apache.poi.ss.SpreadsheetVersion; */ public final class SheetNameFormatter { - private static final char DELIMITER = '\''; + private static final char DELIMITER = '\''; - /** - * Matches a single cell ref with no absolute ('$') markers - */ - private static final Pattern CELL_REF_PATTERN = Pattern.compile("([A-Za-z]+)([0-9]+)"); + /** + * Matches a single cell ref with no absolute ('$') markers + */ + private static final Pattern CELL_REF_PATTERN = Pattern.compile("([A-Za-z]+)([0-9]+)"); - private SheetNameFormatter() { - // no instances of this class - } - /** - * Used to format sheet names as they would appear in cell formula expressions. - * @return the sheet name unchanged if there is no need for delimiting. Otherwise the sheet - * name is enclosed in single quotes ('). Any single quotes which were already present in the - * sheet name will be converted to double single quotes (''). - */ - public static String format(String rawSheetName) { + private SheetNameFormatter() { + // no instances of this class + } + /** + * Used to format sheet names as they would appear in cell formula expressions. + * @return the sheet name unchanged if there is no need for delimiting. Otherwise the sheet + * name is enclosed in single quotes ('). Any single quotes which were already present in the + * sheet name will be converted to double single quotes (''). + */ + public static String format(String rawSheetName) { StringBuilder sb = new StringBuilder((rawSheetName == null ? 0 : rawSheetName.length()) + 2); - appendFormat(sb, rawSheetName); - return sb.toString(); - } + appendFormat(sb, rawSheetName); + return sb.toString(); + } /** * Convenience method for ({@link #format(String)}) when a StringBuffer is already available. @@ -57,211 +57,211 @@ public final class SheetNameFormatter { * @param out - sheet name will be appended here possibly with delimiting quotes * @param rawSheetName - sheet name */ - public static void appendFormat(Appendable out, String rawSheetName) { - try { - boolean needsQuotes = needsDelimiting(rawSheetName); - if(needsQuotes) { - out.append(DELIMITER); - appendAndEscape(out, rawSheetName); - out.append(DELIMITER); - } else { - appendAndEscape(out, rawSheetName); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** - * Convenience method for ({@link #format(String)}) when a StringBuffer is already available. - * - * @param out - sheet name will be appended here possibly with delimiting quotes - * @param workbookName - workbook name - * @param rawSheetName - sheet name - */ - public static void appendFormat(Appendable out, String workbookName, String rawSheetName) { - try { - boolean needsQuotes = needsDelimiting(workbookName) || needsDelimiting(rawSheetName); - if(needsQuotes) { - out.append(DELIMITER); - out.append('['); - appendAndEscape(out, workbookName.replace('[', '(').replace(']', ')')); - out.append(']'); - appendAndEscape(out, rawSheetName); - out.append(DELIMITER); - } else { - out.append('['); - appendOrREF(out, workbookName); - out.append(']'); - appendOrREF(out, rawSheetName); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static void appendOrREF(Appendable out, String name) throws IOException { - if(name == null) { - out.append("#REF"); - } else { - out.append(name); - } - } - - static void appendAndEscape(Appendable sb, String rawSheetName) { - try { - if (rawSheetName == null) { - sb.append("#REF"); - return; - } - - int len = rawSheetName.length(); - for (int i = 0; i < len; i++) { - char ch = rawSheetName.charAt(i); - if (ch == DELIMITER) { - // single quotes (') are encoded as ('') - sb.append(DELIMITER); - } - sb.append(ch); - } - } catch (Exception e) { - throw new RuntimeException(e); - } + public static void appendFormat(Appendable out, String rawSheetName) { + try { + boolean needsQuotes = needsDelimiting(rawSheetName); + if(needsQuotes) { + out.append(DELIMITER); + appendAndEscape(out, rawSheetName); + out.append(DELIMITER); + } else { + appendAndEscape(out, rawSheetName); + } + } catch (Exception e) { + throw new RuntimeException(e); + } } - /** - * Tell if the given raw sheet name needs screening/delimiting. - * @param rawSheetName the sheet name. - * @return true if the given raw sheet name needs screening/delimiting, false otherwise or - * if the sheet name is null. - */ - static boolean needsDelimiting(String rawSheetName) { - if(rawSheetName == null) { - return false; - } + /** + * Convenience method for ({@link #format(String)}) when a StringBuffer is already available. + * + * @param out - sheet name will be appended here possibly with delimiting quotes + * @param workbookName - workbook name + * @param rawSheetName - sheet name + */ + public static void appendFormat(Appendable out, String workbookName, String rawSheetName) { + try { + boolean needsQuotes = needsDelimiting(workbookName) || needsDelimiting(rawSheetName); + if(needsQuotes) { + out.append(DELIMITER); + out.append('['); + appendAndEscape(out, workbookName.replace('[', '(').replace(']', ')')); + out.append(']'); + appendAndEscape(out, rawSheetName); + out.append(DELIMITER); + } else { + out.append('['); + appendOrREF(out, workbookName); + out.append(']'); + appendOrREF(out, rawSheetName); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } - int len = rawSheetName.length(); - if(len < 1) { - return false; // some cases we get missing external references, resulting in empty sheet names - } - if(Character.isDigit(rawSheetName.charAt(0))) { - // sheet name with digit in the first position always requires delimiting - return true; - } - for(int i=0; i - * This code is currently being used for translating formulas represented with {@code Ptg} - * tokens into human readable text form. In formula expressions, a sheet name always has a - * trailing '!' so there is little chance for ambiguity. It doesn't matter too much what this - * method returns but it is worth noting the likely consumers of these formula text strings: - *
    - *
  1. POI's own formula parser
  2. - *
  3. Visual reading by human
  4. - *
  5. VBA automation entry into Excel cell contents e.g. ActiveCell.Formula = "=c64!A1"
  6. - *
  7. Manual entry into Excel cell contents
  8. - *
  9. Some third party formula parser
  10. - *
- * - * At the time of writing, POI's formula parser tolerates cell-like sheet names in formulas - * with or without delimiters. The same goes for Excel(2007), both manual and automated entry. - *

- * For better or worse this implementation attempts to replicate Excel's formula renderer. - * Excel uses range checking on the apparent 'row' and 'column' components. Note however that - * the maximum sheet size varies across versions. - * @see org.apache.poi.ss.util.CellReference - */ - /* package */ static boolean cellReferenceIsWithinRange(String lettersPrefix, String numbersSuffix) { - return CellReference.cellReferenceIsWithinRange(lettersPrefix, numbersSuffix, SpreadsheetVersion.EXCEL97); - } + /** + * Used to decide whether sheet names like 'AB123' need delimiting due to the fact that they + * look like cell references. + *

+ * This code is currently being used for translating formulas represented with {@code Ptg} + * tokens into human readable text form. In formula expressions, a sheet name always has a + * trailing '!' so there is little chance for ambiguity. It doesn't matter too much what this + * method returns but it is worth noting the likely consumers of these formula text strings: + *

    + *
  1. POI's own formula parser
  2. + *
  3. Visual reading by human
  4. + *
  5. VBA automation entry into Excel cell contents e.g. ActiveCell.Formula = "=c64!A1"
  6. + *
  7. Manual entry into Excel cell contents
  8. + *
  9. Some third party formula parser
  10. + *
+ * + * At the time of writing, POI's formula parser tolerates cell-like sheet names in formulas + * with or without delimiters. The same goes for Excel(2007), both manual and automated entry. + *

+ * For better or worse this implementation attempts to replicate Excel's formula renderer. + * Excel uses range checking on the apparent 'row' and 'column' components. Note however that + * the maximum sheet size varies across versions. + * @see org.apache.poi.ss.util.CellReference + */ + /* package */ static boolean cellReferenceIsWithinRange(String lettersPrefix, String numbersSuffix) { + return CellReference.cellReferenceIsWithinRange(lettersPrefix, numbersSuffix, SpreadsheetVersion.EXCEL97); + } - /** - * Note - this method assumes the specified rawSheetName has only letters and digits. It - * cannot be used to match absolute or range references (using the dollar or colon char). - *

- * Some notable cases: - * - * - * - * - * - * - * - * - * - * - * - * - *
Notable cases
Input Result Comments
"A1"  true 
"a111"  true 
"AA"  false 
"aa1"  true 
"A1A"  false 
"A1A1"  false 
"A$1:$C$20"  falseNot a plain cell reference
"SALES20080101"  trueStill needs delimiting even though well out of range
- * - * @return {@code true} if there is any possible ambiguity that the specified rawSheetName - * could be interpreted as a valid cell name. - */ - /* package */ static boolean nameLooksLikePlainCellReference(String rawSheetName) { - Matcher matcher = CELL_REF_PATTERN.matcher(rawSheetName); - if(!matcher.matches()) { - return false; - } + /** + * Note - this method assumes the specified rawSheetName has only letters and digits. It + * cannot be used to match absolute or range references (using the dollar or colon char). + *

+ * Some notable cases: + * + * + * + * + * + * + * + * + * + * + * + * + *
Notable cases
Input Result Comments
"A1"  true 
"a111"  true 
"AA"  false 
"aa1"  true 
"A1A"  false 
"A1A1"  false 
"A$1:$C$20"  falseNot a plain cell reference
"SALES20080101"  trueStill needs delimiting even though well out of range
+ * + * @return {@code true} if there is any possible ambiguity that the specified rawSheetName + * could be interpreted as a valid cell name. + */ + /* package */ static boolean nameLooksLikePlainCellReference(String rawSheetName) { + Matcher matcher = CELL_REF_PATTERN.matcher(rawSheetName); + if(!matcher.matches()) { + return false; + } - // rawSheetName == "Sheet1" gets this far. - String lettersPrefix = matcher.group(1); - String numbersSuffix = matcher.group(2); - return cellReferenceIsWithinRange(lettersPrefix, numbersSuffix); - } + // rawSheetName == "Sheet1" gets this far. + String lettersPrefix = matcher.group(1); + String numbersSuffix = matcher.group(2); + return cellReferenceIsWithinRange(lettersPrefix, numbersSuffix); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/SheetRangeEvaluator.java b/poi/src/main/java/org/apache/poi/ss/formula/SheetRangeEvaluator.java index 68dbb9be3f..806dc08f35 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/SheetRangeEvaluator.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/SheetRangeEvaluator.java @@ -23,54 +23,54 @@ import org.apache.poi.ss.formula.eval.ValueEval; * Evaluator for returning cells or sheets for a range of sheets */ final class SheetRangeEvaluator implements SheetRange { - private final int _firstSheetIndex; + private final int _firstSheetIndex; private final int _lastSheetIndex; - private SheetRefEvaluator[] _sheetEvaluators; + private SheetRefEvaluator[] _sheetEvaluators; - public SheetRangeEvaluator(int firstSheetIndex, int lastSheetIndex, SheetRefEvaluator[] sheetEvaluators) { - if (firstSheetIndex < 0) { - throw new IllegalArgumentException("Invalid firstSheetIndex: " + firstSheetIndex + "."); - } + public SheetRangeEvaluator(int firstSheetIndex, int lastSheetIndex, SheetRefEvaluator[] sheetEvaluators) { + if (firstSheetIndex < 0) { + throw new IllegalArgumentException("Invalid firstSheetIndex: " + firstSheetIndex + "."); + } if (lastSheetIndex < firstSheetIndex) { throw new IllegalArgumentException("Invalid lastSheetIndex: " + lastSheetIndex + " for firstSheetIndex: " + firstSheetIndex + "."); } _firstSheetIndex = firstSheetIndex; _lastSheetIndex = lastSheetIndex; _sheetEvaluators = sheetEvaluators.clone(); - } + } public SheetRangeEvaluator(int onlySheetIndex, SheetRefEvaluator sheetEvaluator) { this(onlySheetIndex, onlySheetIndex, new SheetRefEvaluator[] {sheetEvaluator}); } - - public SheetRefEvaluator getSheetEvaluator(int sheetIndex) { - if (sheetIndex < _firstSheetIndex || sheetIndex > _lastSheetIndex) { + + public SheetRefEvaluator getSheetEvaluator(int sheetIndex) { + if (sheetIndex < _firstSheetIndex || sheetIndex > _lastSheetIndex) { throw new IllegalArgumentException("Invalid SheetIndex: " + sheetIndex + " - Outside range " + _firstSheetIndex + " : " + _lastSheetIndex); - } - return _sheetEvaluators[sheetIndex-_firstSheetIndex]; - } - - public int getFirstSheetIndex() { - return _firstSheetIndex; - } + } + return _sheetEvaluators[sheetIndex-_firstSheetIndex]; + } + + public int getFirstSheetIndex() { + return _firstSheetIndex; + } public int getLastSheetIndex() { return _lastSheetIndex; } - public String getSheetName(int sheetIndex) { - return getSheetEvaluator(sheetIndex).getSheetName(); - } - public String getSheetNameRange() { - StringBuilder sb = new StringBuilder(); - sb.append(getSheetName(_firstSheetIndex)); - if (_firstSheetIndex != _lastSheetIndex) { - sb.append(':'); - sb.append(getSheetName(_lastSheetIndex)); - } - return sb.toString(); - } + public String getSheetName(int sheetIndex) { + return getSheetEvaluator(sheetIndex).getSheetName(); + } + public String getSheetNameRange() { + StringBuilder sb = new StringBuilder(); + sb.append(getSheetName(_firstSheetIndex)); + if (_firstSheetIndex != _lastSheetIndex) { + sb.append(':'); + sb.append(getSheetName(_lastSheetIndex)); + } + return sb.toString(); + } - public ValueEval getEvalForCell(int sheetIndex, int rowIndex, int columnIndex) { + public ValueEval getEvalForCell(int sheetIndex, int rowIndex, int columnIndex) { return getSheetEvaluator(sheetIndex).getEvalForCell(rowIndex, columnIndex); - } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/SheetRefEvaluator.java b/poi/src/main/java/org/apache/poi/ss/formula/SheetRefEvaluator.java index 2324eda75b..eb411bd664 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/SheetRefEvaluator.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/SheetRefEvaluator.java @@ -26,34 +26,34 @@ import org.apache.poi.ss.usermodel.CellType; * Evaluator for cells within a specific Sheet */ final class SheetRefEvaluator { - private final WorkbookEvaluator _bookEvaluator; - private final EvaluationTracker _tracker; - private final int _sheetIndex; - private EvaluationSheet _sheet; + private final WorkbookEvaluator _bookEvaluator; + private final EvaluationTracker _tracker; + private final int _sheetIndex; + private EvaluationSheet _sheet; - public SheetRefEvaluator(WorkbookEvaluator bookEvaluator, EvaluationTracker tracker, int sheetIndex) { - if (sheetIndex < 0) { - throw new IllegalArgumentException("Invalid sheetIndex: " + sheetIndex + "."); - } - _bookEvaluator = bookEvaluator; - _tracker = tracker; - _sheetIndex = sheetIndex; - } + public SheetRefEvaluator(WorkbookEvaluator bookEvaluator, EvaluationTracker tracker, int sheetIndex) { + if (sheetIndex < 0) { + throw new IllegalArgumentException("Invalid sheetIndex: " + sheetIndex + "."); + } + _bookEvaluator = bookEvaluator; + _tracker = tracker; + _sheetIndex = sheetIndex; + } - public String getSheetName() { - return _bookEvaluator.getSheetName(_sheetIndex); - } + public String getSheetName() { + return _bookEvaluator.getSheetName(_sheetIndex); + } - public ValueEval getEvalForCell(int rowIndex, int columnIndex) { - return _bookEvaluator.evaluateReference(getSheet(), _sheetIndex, rowIndex, columnIndex, _tracker); - } + public ValueEval getEvalForCell(int rowIndex, int columnIndex) { + return _bookEvaluator.evaluateReference(getSheet(), _sheetIndex, rowIndex, columnIndex, _tracker); + } - private EvaluationSheet getSheet() { - if (_sheet == null) { - _sheet = _bookEvaluator.getSheet(_sheetIndex); - } - return _sheet; - } + private EvaluationSheet getSheet() { + if (_sheet == null) { + _sheet = _bookEvaluator.getSheet(_sheetIndex); + } + return _sheet; + } /** * @param rowIndex diff --git a/poi/src/main/java/org/apache/poi/ss/formula/ThreeDEval.java b/poi/src/main/java/org/apache/poi/ss/formula/ThreeDEval.java index 0bda63749c..d0ef3af881 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/ThreeDEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/ThreeDEval.java @@ -26,11 +26,11 @@ import org.apache.poi.ss.formula.eval.ValueEval; * which allows for looking up 3D (sheet+row+column) evaluations */ public interface ThreeDEval extends TwoDEval, SheetRange { - /** - * @param sheetIndex sheet index (zero based) - * @param rowIndex relative row index (zero based) - * @param columnIndex relative column index (zero based) - * @return element at the specified row and column position - */ - ValueEval getValue(int sheetIndex, int rowIndex, int columnIndex); + /** + * @param sheetIndex sheet index (zero based) + * @param rowIndex relative row index (zero based) + * @param columnIndex relative column index (zero based) + * @return element at the specified row and column position + */ + ValueEval getValue(int sheetIndex, int rowIndex, int columnIndex); } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/TwoDEval.java b/poi/src/main/java/org/apache/poi/ss/formula/TwoDEval.java index 8f347ff10e..2324fd31a2 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/TwoDEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/TwoDEval.java @@ -27,40 +27,40 @@ import org.apache.poi.ss.formula.functions.Subtotal; */ public interface TwoDEval extends ValueEval { - /** - * @param rowIndex relative row index (zero based) - * @param columnIndex relative column index (zero based) - * @return element at the specified row and column position - */ - ValueEval getValue(int rowIndex, int columnIndex); + /** + * @param rowIndex relative row index (zero based) + * @param columnIndex relative column index (zero based) + * @return element at the specified row and column position + */ + ValueEval getValue(int rowIndex, int columnIndex); - int getWidth(); - int getHeight(); + int getWidth(); + int getHeight(); - /** - * @return {@code true} if the area has just a single row, this also includes - * the trivial case when the area has just a single cell. - */ - default boolean isRow() { - return false; - } + /** + * @return {@code true} if the area has just a single row, this also includes + * the trivial case when the area has just a single cell. + */ + default boolean isRow() { + return false; + } - /** - * @return {@code true} if the area has just a single column, this also includes - * the trivial case when the area has just a single cell. - */ - boolean isColumn(); + /** + * @return {@code true} if the area has just a single column, this also includes + * the trivial case when the area has just a single cell. + */ + boolean isColumn(); - /** - * @param rowIndex relative row index (zero based) - * @return a single row TwoDEval - */ - TwoDEval getRow(int rowIndex); - /** - * @param columnIndex relative column index (zero based) - * @return a single column TwoDEval - */ - TwoDEval getColumn(int columnIndex); + /** + * @param rowIndex relative row index (zero based) + * @return a single row TwoDEval + */ + TwoDEval getRow(int rowIndex); + /** + * @param columnIndex relative column index (zero based) + * @return a single column TwoDEval + */ + TwoDEval getColumn(int columnIndex); /** diff --git a/poi/src/main/java/org/apache/poi/ss/formula/UserDefinedFunction.java b/poi/src/main/java/org/apache/poi/ss/formula/UserDefinedFunction.java index 70546b2d19..cccb3fab29 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/UserDefinedFunction.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/UserDefinedFunction.java @@ -28,34 +28,34 @@ import org.apache.poi.ss.formula.functions.FreeRefFunction; */ final class UserDefinedFunction implements FreeRefFunction { - public static final FreeRefFunction instance = new UserDefinedFunction(); + public static final FreeRefFunction instance = new UserDefinedFunction(); - private UserDefinedFunction() { - // enforce singleton - } + private UserDefinedFunction() { + // enforce singleton + } - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - int nIncomingArgs = args.length; - if(nIncomingArgs < 1) { - throw new RuntimeException("function name argument missing"); - } + @Override + public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { + int nIncomingArgs = args.length; + if(nIncomingArgs < 1) { + throw new RuntimeException("function name argument missing"); + } - ValueEval nameArg = args[0]; - String functionName; - if (nameArg instanceof FunctionNameEval) { - functionName = ((FunctionNameEval) nameArg).getFunctionName(); - } else { - throw new RuntimeException("First argument should be a NameEval, but got (" - + nameArg.getClass().getName() + ")"); - } - FreeRefFunction targetFunc = ec.findUserDefinedFunction(functionName); - if (targetFunc == null) { - throw new NotImplementedFunctionException(functionName); - } - int nOutGoingArgs = nIncomingArgs -1; - ValueEval[] outGoingArgs = new ValueEval[nOutGoingArgs]; - System.arraycopy(args, 1, outGoingArgs, 0, nOutGoingArgs); - return targetFunc.evaluate(outGoingArgs, ec); - } + ValueEval nameArg = args[0]; + String functionName; + if (nameArg instanceof FunctionNameEval) { + functionName = ((FunctionNameEval) nameArg).getFunctionName(); + } else { + throw new RuntimeException("First argument should be a NameEval, but got (" + + nameArg.getClass().getName() + ")"); + } + FreeRefFunction targetFunc = ec.findUserDefinedFunction(functionName); + if (targetFunc == null) { + throw new NotImplementedFunctionException(functionName); + } + int nOutGoingArgs = nIncomingArgs -1; + ValueEval[] outGoingArgs = new ValueEval[nOutGoingArgs]; + System.arraycopy(args, 1, outGoingArgs, 0, nOutGoingArgs); + return targetFunc.evaluate(outGoingArgs, ec); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/WorkbookDependentFormula.java b/poi/src/main/java/org/apache/poi/ss/formula/WorkbookDependentFormula.java index acecc26bd9..8fe26fa526 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/WorkbookDependentFormula.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/WorkbookDependentFormula.java @@ -24,5 +24,5 @@ import org.apache.poi.util.Internal; */ @Internal public interface WorkbookDependentFormula { - String toFormulaString(FormulaRenderingWorkbook book); + String toFormulaString(FormulaRenderingWorkbook book); } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/atp/IfError.java b/poi/src/main/java/org/apache/poi/ss/formula/atp/IfError.java index d500d81807..bcc59808c6 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/atp/IfError.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/atp/IfError.java @@ -33,33 +33,33 @@ import org.apache.poi.ss.formula.functions.FreeRefFunction; */ final class IfError implements FreeRefFunction { - public static final FreeRefFunction instance = new IfError(); + public static final FreeRefFunction instance = new IfError(); - private IfError() { - // enforce singleton - } + private IfError() { + // enforce singleton + } - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 2) { - return ErrorEval.VALUE_INVALID; - } + public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { + if (args.length != 2) { + return ErrorEval.VALUE_INVALID; + } - ValueEval val; - try { - val = evaluateInternal(args[0], args[1], ec.getRowIndex(), ec.getColumnIndex()); - } catch (EvaluationException e) { - return e.getErrorEval(); - } + ValueEval val; + try { + val = evaluateInternal(args[0], args[1], ec.getRowIndex(), ec.getColumnIndex()); + } catch (EvaluationException e) { + return e.getErrorEval(); + } - return val; - } + return val; + } - private static ValueEval evaluateInternal(ValueEval arg, ValueEval iferror, int srcCellRow, int srcCellCol) throws EvaluationException { - arg = WorkbookEvaluator.dereferenceResult(arg, srcCellRow, srcCellCol); - if(arg instanceof ErrorEval) { - return iferror; - } else { - return arg; - } - } + private static ValueEval evaluateInternal(ValueEval arg, ValueEval iferror, int srcCellRow, int srcCellCol) throws EvaluationException { + arg = WorkbookEvaluator.dereferenceResult(arg, srcCellRow, srcCellCol); + if(arg instanceof ErrorEval) { + return iferror; + } else { + return arg; + } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/atp/MRound.java b/poi/src/main/java/org/apache/poi/ss/formula/atp/MRound.java index f1e6227a9b..1068f974b7 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/atp/MRound.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/atp/MRound.java @@ -32,13 +32,13 @@ import org.apache.poi.ss.formula.functions.NumericFunction; */ final class MRound implements FreeRefFunction { - public static final FreeRefFunction instance = new MRound(); + public static final FreeRefFunction instance = new MRound(); - private MRound() { - // enforce singleton - } + private MRound() { + // enforce singleton + } - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { + public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { double number, multiple, result; if (args.length != 2) { @@ -63,5 +63,5 @@ final class MRound implements FreeRefFunction { } catch (EvaluationException e) { return e.getErrorEval(); } - } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/atp/ParityFunction.java b/poi/src/main/java/org/apache/poi/ss/formula/atp/ParityFunction.java index e01b07eb46..6128379864 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/atp/ParityFunction.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/atp/ParityFunction.java @@ -29,37 +29,37 @@ import org.apache.poi.ss.formula.OperationEvaluationContext; */ final class ParityFunction implements FreeRefFunction { - public static final FreeRefFunction IS_EVEN = new ParityFunction(0); - public static final FreeRefFunction IS_ODD = new ParityFunction(1); - private final int _desiredParity; + public static final FreeRefFunction IS_EVEN = new ParityFunction(0); + public static final FreeRefFunction IS_ODD = new ParityFunction(1); + private final int _desiredParity; - private ParityFunction(int desiredParity) { - _desiredParity = desiredParity; - } + private ParityFunction(int desiredParity) { + _desiredParity = desiredParity; + } - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - if (args.length != 1) { - return ErrorEval.VALUE_INVALID; - } + public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { + if (args.length != 1) { + return ErrorEval.VALUE_INVALID; + } - int val; - try { - val = evaluateArgParity(args[0], ec.getRowIndex(), ec.getColumnIndex()); - } catch (EvaluationException e) { - return e.getErrorEval(); - } + int val; + try { + val = evaluateArgParity(args[0], ec.getRowIndex(), ec.getColumnIndex()); + } catch (EvaluationException e) { + return e.getErrorEval(); + } - return BoolEval.valueOf(val == _desiredParity); - } + return BoolEval.valueOf(val == _desiredParity); + } - private static int evaluateArgParity(ValueEval arg, int srcCellRow, int srcCellCol) throws EvaluationException { - ValueEval ve = OperandResolver.getSingleValue(arg, srcCellRow, (short)srcCellCol); + private static int evaluateArgParity(ValueEval arg, int srcCellRow, int srcCellCol) throws EvaluationException { + ValueEval ve = OperandResolver.getSingleValue(arg, srcCellRow, (short)srcCellCol); - double d = OperandResolver.coerceValueToDouble(ve); - if (d < 0) { - d = -d; - } - long v = (long) Math.floor(d); - return Math.toIntExact(v & 0x0001); - } + double d = OperandResolver.coerceValueToDouble(ve); + if (d < 0) { + d = -d; + } + long v = (long) Math.floor(d); + return Math.toIntExact(v & 0x0001); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/atp/RandBetween.java b/poi/src/main/java/org/apache/poi/ss/formula/atp/RandBetween.java index 4e96f9ad57..ead3a119d6 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/atp/RandBetween.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/atp/RandBetween.java @@ -37,46 +37,46 @@ import org.apache.poi.ss.formula.OperationEvaluationContext; */ final class RandBetween implements FreeRefFunction{ - public static final FreeRefFunction instance = new RandBetween(); + public static final FreeRefFunction instance = new RandBetween(); - private RandBetween() { - //enforces singleton - } + private RandBetween() { + //enforces singleton + } - /** - * Evaluate for RANDBETWEEN(). Must be given two arguments. Bottom must be greater than top. - * Bottom is rounded up and top value is rounded down. After rounding top has to be set greater - * than top. - * - * @see org.apache.poi.ss.formula.functions.FreeRefFunction#evaluate(org.apache.poi.ss.formula.eval.ValueEval[], org.apache.poi.ss.formula.OperationEvaluationContext) - */ - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { + /** + * Evaluate for RANDBETWEEN(). Must be given two arguments. Bottom must be greater than top. + * Bottom is rounded up and top value is rounded down. After rounding top has to be set greater + * than top. + * + * @see org.apache.poi.ss.formula.functions.FreeRefFunction#evaluate(org.apache.poi.ss.formula.eval.ValueEval[], org.apache.poi.ss.formula.OperationEvaluationContext) + */ + public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - double bottom, top; + double bottom, top; - if (args.length != 2) { - return ErrorEval.VALUE_INVALID; - } + if (args.length != 2) { + return ErrorEval.VALUE_INVALID; + } - try { - bottom = OperandResolver.coerceValueToDouble(OperandResolver.getSingleValue(args[0], ec.getRowIndex(), ec.getColumnIndex())); - top = OperandResolver.coerceValueToDouble(OperandResolver.getSingleValue(args[1], ec.getRowIndex(), ec.getColumnIndex())); - if(bottom > top) { - return ErrorEval.NUM_ERROR; - } - } catch (EvaluationException e) { - return ErrorEval.VALUE_INVALID; - } + try { + bottom = OperandResolver.coerceValueToDouble(OperandResolver.getSingleValue(args[0], ec.getRowIndex(), ec.getColumnIndex())); + top = OperandResolver.coerceValueToDouble(OperandResolver.getSingleValue(args[1], ec.getRowIndex(), ec.getColumnIndex())); + if(bottom > top) { + return ErrorEval.NUM_ERROR; + } + } catch (EvaluationException e) { + return ErrorEval.VALUE_INVALID; + } - bottom = Math.ceil(bottom); - top = Math.floor(top); + bottom = Math.ceil(bottom); + top = Math.floor(top); - if(bottom > top) { - top = bottom; - } + if(bottom > top) { + top = bottom; + } - return new NumberEval((bottom + (long)(Math.random() * ((top - bottom) + 1)))); + return new NumberEval((bottom + (long)(Math.random() * ((top - bottom) + 1)))); - } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/atp/WorkdayCalculator.java b/poi/src/main/java/org/apache/poi/ss/formula/atp/WorkdayCalculator.java index 666501d540..1abcb549a0 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/atp/WorkdayCalculator.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/atp/WorkdayCalculator.java @@ -60,23 +60,23 @@ public class WorkdayCalculator { * @param holidays an array of holidays. * @return date past x workdays. */ - public Date calculateWorkdays(double start, int workdays, double[] holidays) { - Date startDate = DateUtil.getJavaDate(start); - int direction = workdays < 0 ? -1 : 1; - Calendar endDate = LocaleUtil.getLocaleCalendar(); - endDate.setTime(startDate); - double excelEndDate = DateUtil.getExcelDate(endDate.getTime()); - while (workdays != 0) { - endDate.add(Calendar.DAY_OF_YEAR, direction); - excelEndDate += direction; - if (endDate.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY - && endDate.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY - && !isHoliday(excelEndDate, holidays)) { - workdays -= direction; - } - } - return endDate.getTime(); - } + public Date calculateWorkdays(double start, int workdays, double[] holidays) { + Date startDate = DateUtil.getJavaDate(start); + int direction = workdays < 0 ? -1 : 1; + Calendar endDate = LocaleUtil.getLocaleCalendar(); + endDate.setTime(startDate); + double excelEndDate = DateUtil.getExcelDate(endDate.getTime()); + while (workdays != 0) { + endDate.add(Calendar.DAY_OF_YEAR, direction); + excelEndDate += direction; + if (endDate.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY + && endDate.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY + && !isHoliday(excelEndDate, holidays)) { + workdays -= direction; + } + } + return endDate.getTime(); + } /** * Calculates how many days of week past between a start and an end date. diff --git a/poi/src/main/java/org/apache/poi/ss/formula/atp/YearFrac.java b/poi/src/main/java/org/apache/poi/ss/formula/atp/YearFrac.java index 9922654659..4fc9818680 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/atp/YearFrac.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/atp/YearFrac.java @@ -53,55 +53,55 @@ import org.apache.poi.ss.util.DateParser; */ final class YearFrac implements FreeRefFunction { - public static final FreeRefFunction instance = new YearFrac(); + public static final FreeRefFunction instance = new YearFrac(); - private YearFrac() { - // enforce singleton - } + private YearFrac() { + // enforce singleton + } - @Override - public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { - int srcCellRow = ec.getRowIndex(); - int srcCellCol = ec.getColumnIndex(); - double result; - try { - int basis = 0; // default - switch(args.length) { - case 3: - basis = evaluateIntArg(args[2], srcCellRow, srcCellCol); - // fall through - case 2: - break; - default: - return ErrorEval.VALUE_INVALID; - } - double startDateVal = evaluateDateArg(args[0], srcCellRow, srcCellCol); - double endDateVal = evaluateDateArg(args[1], srcCellRow, srcCellCol); - result = YearFracCalculator.calculate(startDateVal, endDateVal, basis); - } catch (EvaluationException e) { - return e.getErrorEval(); - } + @Override + public ValueEval evaluate(ValueEval[] args, OperationEvaluationContext ec) { + int srcCellRow = ec.getRowIndex(); + int srcCellCol = ec.getColumnIndex(); + double result; + try { + int basis = 0; // default + switch(args.length) { + case 3: + basis = evaluateIntArg(args[2], srcCellRow, srcCellCol); + // fall through + case 2: + break; + default: + return ErrorEval.VALUE_INVALID; + } + double startDateVal = evaluateDateArg(args[0], srcCellRow, srcCellCol); + double endDateVal = evaluateDateArg(args[1], srcCellRow, srcCellCol); + result = YearFracCalculator.calculate(startDateVal, endDateVal, basis); + } catch (EvaluationException e) { + return e.getErrorEval(); + } - return new NumberEval(result); - } + return new NumberEval(result); + } - private static double evaluateDateArg(ValueEval arg, int srcCellRow, int srcCellCol) throws EvaluationException { - ValueEval ve = OperandResolver.getSingleValue(arg, srcCellRow, (short) srcCellCol); + private static double evaluateDateArg(ValueEval arg, int srcCellRow, int srcCellCol) throws EvaluationException { + ValueEval ve = OperandResolver.getSingleValue(arg, srcCellRow, (short) srcCellCol); - if (ve instanceof StringEval) { - String strVal = ((StringEval) ve).getStringValue(); - Double dVal = OperandResolver.parseDouble(strVal); - if (dVal != null) { - return dVal; - } - LocalDate date = DateParser.parseLocalDate(strVal); - return DateUtil.getExcelDate(date, false); - } - return OperandResolver.coerceValueToDouble(ve); - } + if (ve instanceof StringEval) { + String strVal = ((StringEval) ve).getStringValue(); + Double dVal = OperandResolver.parseDouble(strVal); + if (dVal != null) { + return dVal; + } + LocalDate date = DateParser.parseLocalDate(strVal); + return DateUtil.getExcelDate(date, false); + } + return OperandResolver.coerceValueToDouble(ve); + } - private static int evaluateIntArg(ValueEval arg, int srcCellRow, int srcCellCol) throws EvaluationException { - ValueEval ve = OperandResolver.getSingleValue(arg, srcCellRow, (short) srcCellCol); - return OperandResolver.coerceValueToInt(ve); - } + private static int evaluateIntArg(ValueEval arg, int srcCellRow, int srcCellCol) throws EvaluationException { + ValueEval ve = OperandResolver.getSingleValue(arg, srcCellRow, (short) srcCellCol); + return OperandResolver.coerceValueToInt(ve); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/atp/YearFracCalculator.java b/poi/src/main/java/org/apache/poi/ss/formula/atp/YearFracCalculator.java index aba00e7f6b..60546cf051 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/atp/YearFracCalculator.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/atp/YearFracCalculator.java @@ -33,304 +33,304 @@ import org.apache.poi.util.LocaleUtil; */ @Internal final class YearFracCalculator { - private static final int MS_PER_HOUR = 60 * 60 * 1000; - private static final int MS_PER_DAY = 24 * MS_PER_HOUR; - private static final int DAYS_PER_NORMAL_YEAR = 365; - private static final int DAYS_PER_LEAP_YEAR = DAYS_PER_NORMAL_YEAR + 1; + private static final int MS_PER_HOUR = 60 * 60 * 1000; + private static final int MS_PER_DAY = 24 * MS_PER_HOUR; + private static final int DAYS_PER_NORMAL_YEAR = 365; + private static final int DAYS_PER_LEAP_YEAR = DAYS_PER_NORMAL_YEAR + 1; - /** the length of normal long months i.e. 31 */ - private static final int LONG_MONTH_LEN = 31; - /** the length of normal short months i.e. 30 */ - private static final int SHORT_MONTH_LEN = 30; - private static final int SHORT_FEB_LEN = 28; - private static final int LONG_FEB_LEN = SHORT_FEB_LEN + 1; + /** the length of normal long months i.e. 31 */ + private static final int LONG_MONTH_LEN = 31; + /** the length of normal short months i.e. 30 */ + private static final int SHORT_MONTH_LEN = 30; + private static final int SHORT_FEB_LEN = 28; + private static final int LONG_FEB_LEN = SHORT_FEB_LEN + 1; - private YearFracCalculator() { - // no instances of this class - } + private YearFracCalculator() { + // no instances of this class + } - public static double calculate(double pStartDateVal, double pEndDateVal, int basis) throws EvaluationException { + public static double calculate(double pStartDateVal, double pEndDateVal, int basis) throws EvaluationException { - if (basis < 0 || basis >= 5) { - // if basis is invalid the result is #NUM! - throw new EvaluationException(ErrorEval.NUM_ERROR); - } + if (basis < 0 || basis >= 5) { + // if basis is invalid the result is #NUM! + throw new EvaluationException(ErrorEval.NUM_ERROR); + } - // common logic for all bases + // common logic for all bases - // truncate day values - int startDateVal = (int) Math.floor(pStartDateVal); - int endDateVal = (int) Math.floor(pEndDateVal); - if (startDateVal == endDateVal) { - // when dates are equal, result is zero - return 0; - } - // swap start and end if out of order - if (startDateVal > endDateVal) { - int temp = startDateVal; - startDateVal = endDateVal; - endDateVal = temp; - } + // truncate day values + int startDateVal = (int) Math.floor(pStartDateVal); + int endDateVal = (int) Math.floor(pEndDateVal); + if (startDateVal == endDateVal) { + // when dates are equal, result is zero + return 0; + } + // swap start and end if out of order + if (startDateVal > endDateVal) { + int temp = startDateVal; + startDateVal = endDateVal; + endDateVal = temp; + } - switch (basis) { - case 0: return basis0(startDateVal, endDateVal); - case 1: return basis1(startDateVal, endDateVal); - case 2: return basis2(startDateVal, endDateVal); - case 3: return basis3(startDateVal, endDateVal); - case 4: return basis4(startDateVal, endDateVal); - } - throw new IllegalStateException("cannot happen"); - } + switch (basis) { + case 0: return basis0(startDateVal, endDateVal); + case 1: return basis1(startDateVal, endDateVal); + case 2: return basis2(startDateVal, endDateVal); + case 3: return basis3(startDateVal, endDateVal); + case 4: return basis4(startDateVal, endDateVal); + } + throw new IllegalStateException("cannot happen"); + } - /** - * @param startDateVal assumed to be less than or equal to endDateVal - * @param endDateVal assumed to be greater than or equal to startDateVal - */ - private static double basis0(int startDateVal, int endDateVal) { - SimpleDate startDate = createDate(startDateVal); - SimpleDate endDate = createDate(endDateVal); - int date1day = startDate.day; - int date2day = endDate.day; + /** + * @param startDateVal assumed to be less than or equal to endDateVal + * @param endDateVal assumed to be greater than or equal to startDateVal + */ + private static double basis0(int startDateVal, int endDateVal) { + SimpleDate startDate = createDate(startDateVal); + SimpleDate endDate = createDate(endDateVal); + int date1day = startDate.day; + int date2day = endDate.day; - // basis zero has funny adjustments to the day-of-month fields when at end-of-month - if (date1day == LONG_MONTH_LEN && date2day == LONG_MONTH_LEN) { - date1day = SHORT_MONTH_LEN; - date2day = SHORT_MONTH_LEN; - } else if (date1day == LONG_MONTH_LEN) { - date1day = SHORT_MONTH_LEN; - } else if (date1day == SHORT_MONTH_LEN && date2day == LONG_MONTH_LEN) { - date2day = SHORT_MONTH_LEN; - // Note: If date2day==31, it STAYS 31 if date1day < 30. - // Special fixes for February: - } else if (startDate.month == 2 && isLastDayOfMonth(startDate)) { - // Note - these assignments deliberately set Feb 30 date. - date1day = SHORT_MONTH_LEN; - if (endDate.month == 2 && isLastDayOfMonth(endDate)) { - // only adjusted when first date is last day in Feb - date2day = SHORT_MONTH_LEN; - } - } - return calculateAdjusted(startDate, endDate, date1day, date2day); - } - /** - * @param startDateVal assumed to be less than or equal to endDateVal - * @param endDateVal assumed to be greater than or equal to startDateVal - */ - private static double basis1(int startDateVal, int endDateVal) { - assert(startDateVal <= endDateVal); - SimpleDate startDate = createDate(startDateVal); - SimpleDate endDate = createDate(endDateVal); - double yearLength; - if (isGreaterThanOneYear(startDate, endDate)) { - yearLength = averageYearLength(startDate.year, endDate.year); - assert(yearLength > 0); - } else if (shouldCountFeb29(startDate, endDate)) { - yearLength = DAYS_PER_LEAP_YEAR; - } else { - yearLength = DAYS_PER_NORMAL_YEAR; - } - return dateDiff(startDate.tsMilliseconds, endDate.tsMilliseconds) / yearLength; - } + // basis zero has funny adjustments to the day-of-month fields when at end-of-month + if (date1day == LONG_MONTH_LEN && date2day == LONG_MONTH_LEN) { + date1day = SHORT_MONTH_LEN; + date2day = SHORT_MONTH_LEN; + } else if (date1day == LONG_MONTH_LEN) { + date1day = SHORT_MONTH_LEN; + } else if (date1day == SHORT_MONTH_LEN && date2day == LONG_MONTH_LEN) { + date2day = SHORT_MONTH_LEN; + // Note: If date2day==31, it STAYS 31 if date1day < 30. + // Special fixes for February: + } else if (startDate.month == 2 && isLastDayOfMonth(startDate)) { + // Note - these assignments deliberately set Feb 30 date. + date1day = SHORT_MONTH_LEN; + if (endDate.month == 2 && isLastDayOfMonth(endDate)) { + // only adjusted when first date is last day in Feb + date2day = SHORT_MONTH_LEN; + } + } + return calculateAdjusted(startDate, endDate, date1day, date2day); + } + /** + * @param startDateVal assumed to be less than or equal to endDateVal + * @param endDateVal assumed to be greater than or equal to startDateVal + */ + private static double basis1(int startDateVal, int endDateVal) { + assert(startDateVal <= endDateVal); + SimpleDate startDate = createDate(startDateVal); + SimpleDate endDate = createDate(endDateVal); + double yearLength; + if (isGreaterThanOneYear(startDate, endDate)) { + yearLength = averageYearLength(startDate.year, endDate.year); + assert(yearLength > 0); + } else if (shouldCountFeb29(startDate, endDate)) { + yearLength = DAYS_PER_LEAP_YEAR; + } else { + yearLength = DAYS_PER_NORMAL_YEAR; + } + return dateDiff(startDate.tsMilliseconds, endDate.tsMilliseconds) / yearLength; + } - /** - * @param startDateVal assumed to be less than or equal to endDateVal - * @param endDateVal assumed to be greater than or equal to startDateVal - */ - private static double basis2(int startDateVal, int endDateVal) { - return (endDateVal - startDateVal) / 360.0; - } - /** - * @param startDateVal assumed to be less than or equal to endDateVal - * @param endDateVal assumed to be greater than or equal to startDateVal - */ - private static double basis3(double startDateVal, double endDateVal) { - return (endDateVal - startDateVal) / 365.0; - } - /** - * @param startDateVal assumed to be less than or equal to endDateVal - * @param endDateVal assumed to be greater than or equal to startDateVal - */ - private static double basis4(int startDateVal, int endDateVal) { - SimpleDate startDate = createDate(startDateVal); - SimpleDate endDate = createDate(endDateVal); - int date1day = startDate.day; - int date2day = endDate.day; + /** + * @param startDateVal assumed to be less than or equal to endDateVal + * @param endDateVal assumed to be greater than or equal to startDateVal + */ + private static double basis2(int startDateVal, int endDateVal) { + return (endDateVal - startDateVal) / 360.0; + } + /** + * @param startDateVal assumed to be less than or equal to endDateVal + * @param endDateVal assumed to be greater than or equal to startDateVal + */ + private static double basis3(double startDateVal, double endDateVal) { + return (endDateVal - startDateVal) / 365.0; + } + /** + * @param startDateVal assumed to be less than or equal to endDateVal + * @param endDateVal assumed to be greater than or equal to startDateVal + */ + private static double basis4(int startDateVal, int endDateVal) { + SimpleDate startDate = createDate(startDateVal); + SimpleDate endDate = createDate(endDateVal); + int date1day = startDate.day; + int date2day = endDate.day; - // basis four has funny adjustments to the day-of-month fields when at end-of-month - if (date1day == LONG_MONTH_LEN) { - date1day = SHORT_MONTH_LEN; - } - if (date2day == LONG_MONTH_LEN) { - date2day = SHORT_MONTH_LEN; - } - // Note - no adjustments for end of Feb - return calculateAdjusted(startDate, endDate, date1day, date2day); - } + // basis four has funny adjustments to the day-of-month fields when at end-of-month + if (date1day == LONG_MONTH_LEN) { + date1day = SHORT_MONTH_LEN; + } + if (date2day == LONG_MONTH_LEN) { + date2day = SHORT_MONTH_LEN; + } + // Note - no adjustments for end of Feb + return calculateAdjusted(startDate, endDate, date1day, date2day); + } - private static double calculateAdjusted(SimpleDate startDate, SimpleDate endDate, int date1day, - int date2day) { - double dayCount - = (endDate.year - startDate.year) * 360.0 - + (endDate.month - startDate.month) * (double)SHORT_MONTH_LEN - + (date2day - date1day) * 1.0; - return dayCount / 360; - } + private static double calculateAdjusted(SimpleDate startDate, SimpleDate endDate, int date1day, + int date2day) { + double dayCount + = (endDate.year - startDate.year) * 360.0 + + (endDate.month - startDate.month) * (double)SHORT_MONTH_LEN + + (date2day - date1day) * 1.0; + return dayCount / 360; + } - private static boolean isLastDayOfMonth(SimpleDate date) { - if (date.day < SHORT_FEB_LEN) { - return false; - } - return date.day == getLastDayOfMonth(date); - } + private static boolean isLastDayOfMonth(SimpleDate date) { + if (date.day < SHORT_FEB_LEN) { + return false; + } + return date.day == getLastDayOfMonth(date); + } - private static int getLastDayOfMonth(SimpleDate date) { - switch (date.month) { - case 1: - case 3: - case 5: - case 7: - case 8: - case 10: - case 12: - return LONG_MONTH_LEN; - case 4: - case 6: - case 9: - case 11: - return SHORT_MONTH_LEN; - } - if (isLeapYear(date.year)) { - return LONG_FEB_LEN; - } - return SHORT_FEB_LEN; - } + private static int getLastDayOfMonth(SimpleDate date) { + switch (date.month) { + case 1: + case 3: + case 5: + case 7: + case 8: + case 10: + case 12: + return LONG_MONTH_LEN; + case 4: + case 6: + case 9: + case 11: + return SHORT_MONTH_LEN; + } + if (isLeapYear(date.year)) { + return LONG_FEB_LEN; + } + return SHORT_FEB_LEN; + } - /** - * Assumes dates are no more than 1 year apart. - * @return true if dates both within a leap year, or span a period including Feb 29 - */ - private static boolean shouldCountFeb29(SimpleDate start, SimpleDate end) { - if (isLeapYear(start.year)) { - if (start.year == end.year) { - // note - dates may not actually span Feb-29, but it gets counted anyway in this case - return true; - } + /** + * Assumes dates are no more than 1 year apart. + * @return true if dates both within a leap year, or span a period including Feb 29 + */ + private static boolean shouldCountFeb29(SimpleDate start, SimpleDate end) { + if (isLeapYear(start.year)) { + if (start.year == end.year) { + // note - dates may not actually span Feb-29, but it gets counted anyway in this case + return true; + } - switch (start.month) { - case SimpleDate.JANUARY: - case SimpleDate.FEBRUARY: - return true; - } - return false; - } + switch (start.month) { + case SimpleDate.JANUARY: + case SimpleDate.FEBRUARY: + return true; + } + return false; + } - if (isLeapYear(end.year)) { - switch (end.month) { - case SimpleDate.JANUARY: - return false; - case SimpleDate.FEBRUARY: - break; - default: - return true; - } - return end.day == LONG_FEB_LEN; - } - return false; - } + if (isLeapYear(end.year)) { + switch (end.month) { + case SimpleDate.JANUARY: + return false; + case SimpleDate.FEBRUARY: + break; + default: + return true; + } + return end.day == LONG_FEB_LEN; + } + return false; + } - /** - * @return the whole number of days between the two time-stamps. Both time-stamps are - * assumed to represent 12:00 midnight on the respective day. - */ - private static int dateDiff(long startDateMS, long endDateMS) { - long msDiff = endDateMS - startDateMS; + /** + * @return the whole number of days between the two time-stamps. Both time-stamps are + * assumed to represent 12:00 midnight on the respective day. + */ + private static int dateDiff(long startDateMS, long endDateMS) { + long msDiff = endDateMS - startDateMS; - // some extra checks to make sure we don't hide some other bug with the rounding - int remainderHours = (int) ((msDiff % MS_PER_DAY) / MS_PER_HOUR); - switch (remainderHours) { - case 0: // normal case - break; - case 1: // transition from normal time to daylight savings adjusted - case 23: // transition from daylight savings adjusted to normal time - // Unexpected since we are using UTC_TIME_ZONE - default: - throw new RuntimeException("Unexpected date diff between " + startDateMS + " and " + endDateMS); + // some extra checks to make sure we don't hide some other bug with the rounding + int remainderHours = (int) ((msDiff % MS_PER_DAY) / MS_PER_HOUR); + switch (remainderHours) { + case 0: // normal case + break; + case 1: // transition from normal time to daylight savings adjusted + case 23: // transition from daylight savings adjusted to normal time + // Unexpected since we are using UTC_TIME_ZONE + default: + throw new RuntimeException("Unexpected date diff between " + startDateMS + " and " + endDateMS); - } - return (int) (0.5 + ((double)msDiff / MS_PER_DAY)); - } + } + return (int) (0.5 + ((double)msDiff / MS_PER_DAY)); + } - private static double averageYearLength(int startYear, int endYear) { - assert(startYear <= endYear); - int dayCount = 0; - for (int i=startYear; i<=endYear; i++) { - dayCount += isLeapYear(i) ? DAYS_PER_LEAP_YEAR : DAYS_PER_NORMAL_YEAR; - } - double numberOfYears = endYear-startYear+1.; - return dayCount / numberOfYears; - } + private static double averageYearLength(int startYear, int endYear) { + assert(startYear <= endYear); + int dayCount = 0; + for (int i=startYear; i<=endYear; i++) { + dayCount += isLeapYear(i) ? DAYS_PER_LEAP_YEAR : DAYS_PER_NORMAL_YEAR; + } + double numberOfYears = endYear-startYear+1.; + return dayCount / numberOfYears; + } - private static boolean isLeapYear(int i) { - // leap years are always divisible by 4 - if (i % 4 != 0) { - return false; - } - // each 4th century is a leap year - if (i % 400 == 0) { - return true; - } - // all other centuries are *not* leap years - return i % 100 != 0; - } + private static boolean isLeapYear(int i) { + // leap years are always divisible by 4 + if (i % 4 != 0) { + return false; + } + // each 4th century is a leap year + if (i % 400 == 0) { + return true; + } + // all other centuries are *not* leap years + return i % 100 != 0; + } - private static boolean isGreaterThanOneYear(SimpleDate start, SimpleDate end) { - assert(start.year <= end.year); - if (start.year == end.year) { - return false; - } - if (start.year + 1 != end.year) { - return true; - } + private static boolean isGreaterThanOneYear(SimpleDate start, SimpleDate end) { + assert(start.year <= end.year); + if (start.year == end.year) { + return false; + } + if (start.year + 1 != end.year) { + return true; + } - if (start.month > end.month) { - return false; - } - if (start.month < end.month) { - return true; - } + if (start.month > end.month) { + return false; + } + if (start.month < end.month) { + return true; + } - return start.day < end.day; - } + return start.day < end.day; + } - private static SimpleDate createDate(int dayCount) { - /* use UTC time-zone to avoid daylight savings issues */ - Calendar cal = LocaleUtil.getLocaleCalendar(LocaleUtil.TIMEZONE_UTC); - DateUtil.setCalendar(cal, dayCount, 0, false, false); - return new SimpleDate(cal); - } + private static SimpleDate createDate(int dayCount) { + /* use UTC time-zone to avoid daylight savings issues */ + Calendar cal = LocaleUtil.getLocaleCalendar(LocaleUtil.TIMEZONE_UTC); + DateUtil.setCalendar(cal, dayCount, 0, false, false); + return new SimpleDate(cal); + } - private static final class SimpleDate { + private static final class SimpleDate { - public static final int JANUARY = 1; - public static final int FEBRUARY = 2; + public static final int JANUARY = 1; + public static final int FEBRUARY = 2; - public final int year; - /** 1-based month */ - public final int month; - /** day of month */ - public final int day; - /** milliseconds since 1970 */ - public final long tsMilliseconds; + public final int year; + /** 1-based month */ + public final int month; + /** day of month */ + public final int day; + /** milliseconds since 1970 */ + public final long tsMilliseconds; - public SimpleDate(Calendar cal) { - year = cal.get(Calendar.YEAR); - month = cal.get(Calendar.MONTH) + 1; - day = cal.get(Calendar.DAY_OF_MONTH); - tsMilliseconds = cal.getTimeInMillis(); - } - } + public SimpleDate(Calendar cal) { + year = cal.get(Calendar.YEAR); + month = cal.get(Calendar.MONTH) + 1; + day = cal.get(Calendar.DAY_OF_MONTH); + tsMilliseconds = cal.getTimeInMillis(); + } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/constant/ConstantValueParser.java b/poi/src/main/java/org/apache/poi/ss/formula/constant/ConstantValueParser.java index b68e957ea0..e0e923b02e 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/constant/ConstantValueParser.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/constant/ConstantValueParser.java @@ -27,129 +27,129 @@ import org.apache.poi.util.StringUtil; * EXTERNALNAME (5.39) records and Array tokens. */ public final class ConstantValueParser { - // note - these (non-combinable) enum values are sparse. - private static final int TYPE_EMPTY = 0; - private static final int TYPE_NUMBER = 1; - private static final int TYPE_STRING = 2; - private static final int TYPE_BOOLEAN = 4; - private static final int TYPE_ERROR_CODE = 16; // TODO - update OOO document to include this value + // note - these (non-combinable) enum values are sparse. + private static final int TYPE_EMPTY = 0; + private static final int TYPE_NUMBER = 1; + private static final int TYPE_STRING = 2; + private static final int TYPE_BOOLEAN = 4; + private static final int TYPE_ERROR_CODE = 16; // TODO - update OOO document to include this value - private static final int TRUE_ENCODING = 1; - private static final int FALSE_ENCODING = 0; + private static final int TRUE_ENCODING = 1; + private static final int FALSE_ENCODING = 0; - // TODO - is this the best way to represent 'EMPTY'? - private static final Object EMPTY_REPRESENTATION = null; + // TODO - is this the best way to represent 'EMPTY'? + private static final Object EMPTY_REPRESENTATION = null; - private ConstantValueParser() { - // no instances of this class - } + private ConstantValueParser() { + // no instances of this class + } - public static Object[] parse(LittleEndianInput in, int nValues) { - Object[] result = new Object[nValues]; - for (int i = 0; i < result.length; i++) { - result[i] = readAConstantValue(in); - } - return result; - } + public static Object[] parse(LittleEndianInput in, int nValues) { + Object[] result = new Object[nValues]; + for (int i = 0; i < result.length; i++) { + result[i] = readAConstantValue(in); + } + return result; + } - private static Object readAConstantValue(LittleEndianInput in) { - byte grbit = in.readByte(); - switch(grbit) { - case TYPE_EMPTY: - in.readLong(); // 8 byte 'not used' field - return EMPTY_REPRESENTATION; - case TYPE_NUMBER: - return in.readDouble(); - case TYPE_STRING: - return StringUtil.readUnicodeString(in); - case TYPE_BOOLEAN: - return readBoolean(in); - case TYPE_ERROR_CODE: - int errCode = in.readUShort(); - // next 6 bytes are unused - in.readUShort(); - in.readInt(); - return ErrorConstant.valueOf(errCode); - } - throw new RuntimeException("Unknown grbit value (" + grbit + ")"); - } + private static Object readAConstantValue(LittleEndianInput in) { + byte grbit = in.readByte(); + switch(grbit) { + case TYPE_EMPTY: + in.readLong(); // 8 byte 'not used' field + return EMPTY_REPRESENTATION; + case TYPE_NUMBER: + return in.readDouble(); + case TYPE_STRING: + return StringUtil.readUnicodeString(in); + case TYPE_BOOLEAN: + return readBoolean(in); + case TYPE_ERROR_CODE: + int errCode = in.readUShort(); + // next 6 bytes are unused + in.readUShort(); + in.readInt(); + return ErrorConstant.valueOf(errCode); + } + throw new RuntimeException("Unknown grbit value (" + grbit + ")"); + } - private static Object readBoolean(LittleEndianInput in) { - byte val = (byte)in.readLong(); // 7 bytes 'not used' - switch(val) { - case FALSE_ENCODING: - return Boolean.FALSE; - case TRUE_ENCODING: - return Boolean.TRUE; - } - // Don't tolerate unusual boolean encoded values (unless it becomes evident that they occur) - throw new RuntimeException("unexpected boolean encoding (" + val + ")"); - } + private static Object readBoolean(LittleEndianInput in) { + byte val = (byte)in.readLong(); // 7 bytes 'not used' + switch(val) { + case FALSE_ENCODING: + return Boolean.FALSE; + case TRUE_ENCODING: + return Boolean.TRUE; + } + // Don't tolerate unusual boolean encoded values (unless it becomes evident that they occur) + throw new RuntimeException("unexpected boolean encoding (" + val + ")"); + } - public static int getEncodedSize(Object[] values) { - // start with one byte 'type' code for each value - int result = values.length; - for (Object value : values) { - result += getEncodedSize(value); - } - return result; - } + public static int getEncodedSize(Object[] values) { + // start with one byte 'type' code for each value + int result = values.length; + for (Object value : values) { + result += getEncodedSize(value); + } + return result; + } - /** - * @return encoded size without the 'type' code byte - */ - private static int getEncodedSize(Object object) { - if(object == EMPTY_REPRESENTATION) { - return 8; - } - Class cls = object.getClass(); + /** + * @return encoded size without the 'type' code byte + */ + private static int getEncodedSize(Object object) { + if(object == EMPTY_REPRESENTATION) { + return 8; + } + Class cls = object.getClass(); - if(cls == Boolean.class || cls == Double.class || cls == ErrorConstant.class) { - return 8; - } - String strVal = (String)object; - return StringUtil.getEncodedSize(strVal); - } + if(cls == Boolean.class || cls == Double.class || cls == ErrorConstant.class) { + return 8; + } + String strVal = (String)object; + return StringUtil.getEncodedSize(strVal); + } - public static void encode(LittleEndianOutput out, Object[] values) { - for (Object value : values) { - encodeSingleValue(out, value); - } - } + public static void encode(LittleEndianOutput out, Object[] values) { + for (Object value : values) { + encodeSingleValue(out, value); + } + } - private static void encodeSingleValue(LittleEndianOutput out, Object value) { - if (value == EMPTY_REPRESENTATION) { - out.writeByte(TYPE_EMPTY); - out.writeLong(0L); - return; - } - if (value instanceof Boolean) { - Boolean bVal = ((Boolean)value); - out.writeByte(TYPE_BOOLEAN); - long longVal = bVal ? 1L : 0L; - out.writeLong(longVal); - return; - } - if (value instanceof Double) { - Double dVal = (Double) value; - out.writeByte(TYPE_NUMBER); - out.writeDouble(dVal); - return; - } - if (value instanceof String) { - String val = (String) value; - out.writeByte(TYPE_STRING); - StringUtil.writeUnicodeString(out, val); - return; - } - if (value instanceof ErrorConstant) { - ErrorConstant ecVal = (ErrorConstant) value; - out.writeByte(TYPE_ERROR_CODE); - long longVal = ecVal.getErrorCode(); - out.writeLong(longVal); - return; - } + private static void encodeSingleValue(LittleEndianOutput out, Object value) { + if (value == EMPTY_REPRESENTATION) { + out.writeByte(TYPE_EMPTY); + out.writeLong(0L); + return; + } + if (value instanceof Boolean) { + Boolean bVal = ((Boolean)value); + out.writeByte(TYPE_BOOLEAN); + long longVal = bVal ? 1L : 0L; + out.writeLong(longVal); + return; + } + if (value instanceof Double) { + Double dVal = (Double) value; + out.writeByte(TYPE_NUMBER); + out.writeDouble(dVal); + return; + } + if (value instanceof String) { + String val = (String) value; + out.writeByte(TYPE_STRING); + StringUtil.writeUnicodeString(out, val); + return; + } + if (value instanceof ErrorConstant) { + ErrorConstant ecVal = (ErrorConstant) value; + out.writeByte(TYPE_ERROR_CODE); + long longVal = ecVal.getErrorCode(); + out.writeLong(longVal); + return; + } - throw new IllegalStateException("Unexpected value type (" + value.getClass().getName() + "'"); - } + throw new IllegalStateException("Unexpected value type (" + value.getClass().getName() + "'"); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/constant/ErrorConstant.java b/poi/src/main/java/org/apache/poi/ss/formula/constant/ErrorConstant.java index 5082acff75..d0817fb22e 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/constant/ErrorConstant.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/constant/ErrorConstant.java @@ -30,8 +30,8 @@ import static org.apache.logging.log4j.util.Unbox.box; * {@code ErrorEval}. */ public final class ErrorConstant { - private static final Logger LOG = LogManager.getLogger(ErrorConstant.class); - private static final ErrorConstant NULL = new ErrorConstant(FormulaError.NULL.getCode()); + private static final Logger LOG = LogManager.getLogger(ErrorConstant.class); + private static final ErrorConstant NULL = new ErrorConstant(FormulaError.NULL.getCode()); private static final ErrorConstant DIV_0 = new ErrorConstant(FormulaError.DIV0.getCode()); private static final ErrorConstant VALUE = new ErrorConstant(FormulaError.VALUE.getCode()); private static final ErrorConstant REF = new ErrorConstant(FormulaError.REF.getCode()); @@ -39,41 +39,41 @@ public final class ErrorConstant { private static final ErrorConstant NUM = new ErrorConstant(FormulaError.NUM.getCode()); private static final ErrorConstant NA = new ErrorConstant(FormulaError.NA.getCode()); - private final int _errorCode; + private final int _errorCode; - private ErrorConstant(int errorCode) { - _errorCode = errorCode; - } + private ErrorConstant(int errorCode) { + _errorCode = errorCode; + } - public int getErrorCode() { - return _errorCode; - } + public int getErrorCode() { + return _errorCode; + } - public String getText() { - if(FormulaError.isValidCode(_errorCode)) { - return FormulaError.forInt(_errorCode).getString(); - } - return "unknown error code (" + _errorCode + ")"; - } + public String getText() { + if(FormulaError.isValidCode(_errorCode)) { + return FormulaError.forInt(_errorCode).getString(); + } + return "unknown error code (" + _errorCode + ")"; + } - public static ErrorConstant valueOf(int errorCode) { - if (FormulaError.isValidCode(errorCode)) { - switch (FormulaError.forInt(errorCode)) { - case NULL: return NULL; - case DIV0: return DIV_0; - case VALUE: return VALUE; - case REF: return REF; - case NAME: return NAME; - case NUM: return NUM; - case NA: return NA; - default: break; - } - } - LOG.atWarn().log("Warning - unexpected error code ({})", box(errorCode)); - return new ErrorConstant(errorCode); - } + public static ErrorConstant valueOf(int errorCode) { + if (FormulaError.isValidCode(errorCode)) { + switch (FormulaError.forInt(errorCode)) { + case NULL: return NULL; + case DIV0: return DIV_0; + case VALUE: return VALUE; + case REF: return REF; + case NAME: return NAME; + case NUM: return NUM; + case NA: return NA; + default: break; + } + } + LOG.atWarn().log("Warning - unexpected error code ({})", box(errorCode)); + return new ErrorConstant(errorCode); + } - public String toString() { - return getClass().getName() + " [" + getText() + "]"; - } + public String toString() { + return getClass().getName() + " [" + getText() + "]"; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/AreaEvalBase.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/AreaEvalBase.java index 624fa42eb9..cf83f2b5a8 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/AreaEvalBase.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/AreaEvalBase.java @@ -23,141 +23,141 @@ import org.apache.poi.ss.formula.ptg.AreaI; public abstract class AreaEvalBase implements AreaEval { private final int _firstSheet; - private final int _firstColumn; - private final int _firstRow; + private final int _firstColumn; + private final int _firstRow; private final int _lastSheet; - private final int _lastColumn; - private final int _lastRow; - private final int _nColumns; - private final int _nRows; + private final int _lastColumn; + private final int _lastRow; + private final int _nColumns; + private final int _nRows; - protected AreaEvalBase(SheetRange sheets, int firstRow, int firstColumn, int lastRow, int lastColumn) { - _firstColumn = firstColumn; - _firstRow = firstRow; - _lastColumn = lastColumn; - _lastRow = lastRow; + protected AreaEvalBase(SheetRange sheets, int firstRow, int firstColumn, int lastRow, int lastColumn) { + _firstColumn = firstColumn; + _firstRow = firstRow; + _lastColumn = lastColumn; + _lastRow = lastRow; - _nColumns = _lastColumn - _firstColumn + 1; - _nRows = _lastRow - _firstRow + 1; + _nColumns = _lastColumn - _firstColumn + 1; + _nRows = _lastRow - _firstRow + 1; - if (sheets != null) { - _firstSheet = sheets.getFirstSheetIndex(); - _lastSheet = sheets.getLastSheetIndex(); - } else { - _firstSheet = -1; - _lastSheet = -1; - } - } + if (sheets != null) { + _firstSheet = sheets.getFirstSheetIndex(); + _lastSheet = sheets.getLastSheetIndex(); + } else { + _firstSheet = -1; + _lastSheet = -1; + } + } protected AreaEvalBase(int firstRow, int firstColumn, int lastRow, int lastColumn) { this(null, firstRow, firstColumn, lastRow, lastColumn); } - protected AreaEvalBase(AreaI ptg) { - this(ptg, null); - } + protected AreaEvalBase(AreaI ptg) { + this(ptg, null); + } protected AreaEvalBase(AreaI ptg, SheetRange sheets) { - this(sheets, ptg.getFirstRow(), ptg.getFirstColumn(), ptg.getLastRow(), ptg.getLastColumn()); - } + this(sheets, ptg.getFirstRow(), ptg.getFirstColumn(), ptg.getLastRow(), ptg.getLastColumn()); + } - @Override - public final int getFirstColumn() { - return _firstColumn; - } + @Override + public final int getFirstColumn() { + return _firstColumn; + } - @Override - public final int getFirstRow() { - return _firstRow; - } + @Override + public final int getFirstRow() { + return _firstRow; + } - @Override - public final int getLastColumn() { - return _lastColumn; - } + @Override + public final int getLastColumn() { + return _lastColumn; + } - @Override - public final int getLastRow() { - return _lastRow; - } + @Override + public final int getLastRow() { + return _lastRow; + } - @Override - public int getFirstSheetIndex() { - return _firstSheet; + @Override + public int getFirstSheetIndex() { + return _firstSheet; } @Override - public int getLastSheetIndex() { + public int getLastSheetIndex() { return _lastSheet; } @Override - public final ValueEval getAbsoluteValue(int row, int col) { - int rowOffsetIx = row - _firstRow; - int colOffsetIx = col - _firstColumn; + public final ValueEval getAbsoluteValue(int row, int col) { + int rowOffsetIx = row - _firstRow; + int colOffsetIx = col - _firstColumn; - if(rowOffsetIx < 0 || rowOffsetIx >= _nRows) { - throw new IllegalArgumentException("Specified row index (" + row - + ") is outside the allowed range (" + _firstRow + ".." + _lastRow + ")"); - } - if(colOffsetIx < 0 || colOffsetIx >= _nColumns) { - throw new IllegalArgumentException("Specified column index (" + col - + ") is outside the allowed range (" + _firstColumn + ".." + col + ")"); - } - return getRelativeValue(rowOffsetIx, colOffsetIx); - } + if(rowOffsetIx < 0 || rowOffsetIx >= _nRows) { + throw new IllegalArgumentException("Specified row index (" + row + + ") is outside the allowed range (" + _firstRow + ".." + _lastRow + ")"); + } + if(colOffsetIx < 0 || colOffsetIx >= _nColumns) { + throw new IllegalArgumentException("Specified column index (" + col + + ") is outside the allowed range (" + _firstColumn + ".." + col + ")"); + } + return getRelativeValue(rowOffsetIx, colOffsetIx); + } - @Override - public final boolean contains(int row, int col) { - return _firstRow <= row && _lastRow >= row - && _firstColumn <= col && _lastColumn >= col; - } - - @Override - public final boolean containsRow(int row) { - return _firstRow <= row && _lastRow >= row; - } - - @Override - public final boolean containsColumn(int col) { - return _firstColumn <= col && _lastColumn >= col; - } - - @Override - public final boolean isColumn() { - return _firstColumn == _lastColumn; - } - - @Override - public final boolean isRow() { - return _firstRow == _lastRow; - } - @Override - public int getHeight() { - return _lastRow-_firstRow+1; - } - - @Override - public final ValueEval getValue(int row, int col) { - return getRelativeValue(row, col); - } @Override - public final ValueEval getValue(int sheetIndex, int row, int col) { + public final boolean contains(int row, int col) { + return _firstRow <= row && _lastRow >= row + && _firstColumn <= col && _lastColumn >= col; + } + + @Override + public final boolean containsRow(int row) { + return _firstRow <= row && _lastRow >= row; + } + + @Override + public final boolean containsColumn(int col) { + return _firstColumn <= col && _lastColumn >= col; + } + + @Override + public final boolean isColumn() { + return _firstColumn == _lastColumn; + } + + @Override + public final boolean isRow() { + return _firstRow == _lastRow; + } + @Override + public int getHeight() { + return _lastRow-_firstRow+1; + } + + @Override + public final ValueEval getValue(int row, int col) { + return getRelativeValue(row, col); + } + @Override + public final ValueEval getValue(int sheetIndex, int row, int col) { return getRelativeValue(sheetIndex, row, col); } - @Override - public abstract ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex); + @Override + public abstract ValueEval getRelativeValue(int relativeRowIndex, int relativeColumnIndex); public abstract ValueEval getRelativeValue(int sheetIndex, int relativeRowIndex, int relativeColumnIndex); - @Override - public int getWidth() { - return _lastColumn-_firstColumn+1; - } + @Override + public int getWidth() { + return _lastColumn-_firstColumn+1; + } /** * @return whether cell at rowIndex and columnIndex is a subtotal. * By default return false which means 'don't care about subtotals' */ @Override - public boolean isSubTotal(int rowIndex, int columnIndex) { + public boolean isSubTotal(int rowIndex, int columnIndex) { return false; } @@ -166,7 +166,7 @@ public abstract class AreaEvalBase implements AreaEval { * @see org.apache.poi.ss.formula.TwoDEval#isRowHidden(int) */ @Override - public boolean isRowHidden(int rowIndex) { + public boolean isRowHidden(int rowIndex) { return false; } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/BlankEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/BlankEval.java index 894f58b402..0972bd4180 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/BlankEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/BlankEval.java @@ -22,9 +22,9 @@ package org.apache.poi.ss.formula.eval; */ public final class BlankEval implements ValueEval { - public static final BlankEval instance = new BlankEval(); + public static final BlankEval instance = new BlankEval(); - private BlankEval() { - // enforce singleton - } + private BlankEval() { + // enforce singleton + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/BoolEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/BoolEval.java index 9e35d4c904..2fa301c9ff 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/BoolEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/BoolEval.java @@ -19,43 +19,43 @@ package org.apache.poi.ss.formula.eval; public final class BoolEval implements NumericValueEval, StringValueEval { - private final boolean _value; + private final boolean _value; - public static final BoolEval FALSE = new BoolEval(false); + public static final BoolEval FALSE = new BoolEval(false); - public static final BoolEval TRUE = new BoolEval(true); + public static final BoolEval TRUE = new BoolEval(true); - /** - * Convenience method for the following:
- * {@code (b ? BoolEval.TRUE : BoolEval.FALSE)} - * - * @return the {@code BoolEval} instance representing {@code b}. - */ - public static BoolEval valueOf(boolean b) { - return b ? TRUE : FALSE; - } + /** + * Convenience method for the following:
+ * {@code (b ? BoolEval.TRUE : BoolEval.FALSE)} + * + * @return the {@code BoolEval} instance representing {@code b}. + */ + public static BoolEval valueOf(boolean b) { + return b ? TRUE : FALSE; + } - private BoolEval(boolean value) { - _value = value; - } + private BoolEval(boolean value) { + _value = value; + } - public boolean getBooleanValue() { - return _value; - } + public boolean getBooleanValue() { + return _value; + } - @Override - public double getNumberValue() { - return _value ? 1 : 0; - } + @Override + public double getNumberValue() { + return _value ? 1 : 0; + } - @Override - public String getStringValue() { - return _value ? "TRUE" : "FALSE"; - } + @Override + public String getStringValue() { + return _value ? "TRUE" : "FALSE"; + } - public String toString() { - return getClass().getName() + " [" + - getStringValue() + - "]"; - } + public String toString() { + return getClass().getName() + " [" + + getStringValue() + + "]"; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/ConcatEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/ConcatEval.java index cec4b987e8..02b5a85962 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/ConcatEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/ConcatEval.java @@ -22,36 +22,36 @@ import org.apache.poi.ss.formula.functions.Function; public final class ConcatEval extends Fixed2ArgFunction { - public static final Function instance = new ConcatEval(); + public static final Function instance = new ConcatEval(); - private ConcatEval() { - // enforce singleton - } + private ConcatEval() { + // enforce singleton + } - public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { - ValueEval ve0; - ValueEval ve1; - try { - ve0 = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); - ve1 = OperandResolver.getSingleValue(arg1, srcRowIndex, srcColumnIndex); - } catch (EvaluationException e) { - return e.getErrorEval(); - } - StringBuilder sb = new StringBuilder(); - sb.append(getText(ve0)); - sb.append(getText(ve1)); - return new StringEval(sb.toString()); - } + public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { + ValueEval ve0; + ValueEval ve1; + try { + ve0 = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); + ve1 = OperandResolver.getSingleValue(arg1, srcRowIndex, srcColumnIndex); + } catch (EvaluationException e) { + return e.getErrorEval(); + } + StringBuilder sb = new StringBuilder(); + sb.append(getText(ve0)); + sb.append(getText(ve1)); + return new StringEval(sb.toString()); + } - private Object getText(ValueEval ve) { - if (ve instanceof StringValueEval) { - StringValueEval sve = (StringValueEval) ve; - return sve.getStringValue(); - } - if (ve == BlankEval.instance) { - return ""; - } - throw new IllegalAccessError("Unexpected value type (" - + ve.getClass().getName() + ")"); - } + private Object getText(ValueEval ve) { + if (ve instanceof StringValueEval) { + StringValueEval sve = (StringValueEval) ve; + return sve.getStringValue(); + } + if (ve == BlankEval.instance) { + return ""; + } + throw new IllegalAccessError("Unexpected value type (" + + ve.getClass().getName() + ")"); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/EvaluationException.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/EvaluationException.java index 21a368e2e5..73fb14d89e 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/EvaluationException.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/EvaluationException.java @@ -25,28 +25,28 @@ package org.apache.poi.ss.formula.eval; * Here is an example coded without {@code EvaluationException}, to show how it can help: *

{@code
  * public Eval evaluate(Eval[] args, int srcRow, short srcCol) {
- *	// ...
- *	Eval arg0 = args[0];
- *	if(arg0 instanceof ErrorEval) {
- *		return arg0;
- *	}
- *	if(!(arg0 instanceof AreaEval)) {
- *		return ErrorEval.VALUE_INVALID;
- *	}
- *	double temp = 0;
- *	AreaEval area = (AreaEval)arg0;
- *	ValueEval[] values = area.getValues();
- *	for (int i = 0; i < values.length; i++) {
- *		ValueEval ve = values[i];
- *		if(ve instanceof ErrorEval) {
- *			return ve;
- *		}
- *		if(!(ve instanceof NumericValueEval)) {
- *			return ErrorEval.VALUE_INVALID;
- *		}
- *		temp += ((NumericValueEval)ve).getNumberValue();
- *	}
- *	// ...
+ *  // ...
+ *  Eval arg0 = args[0];
+ *  if(arg0 instanceof ErrorEval) {
+ *      return arg0;
+ *  }
+ *  if(!(arg0 instanceof AreaEval)) {
+ *      return ErrorEval.VALUE_INVALID;
+ *  }
+ *  double temp = 0;
+ *  AreaEval area = (AreaEval)arg0;
+ *  ValueEval[] values = area.getValues();
+ *  for (int i = 0; i < values.length; i++) {
+ *      ValueEval ve = values[i];
+ *      if(ve instanceof ErrorEval) {
+ *          return ve;
+ *      }
+ *      if(!(ve instanceof NumericValueEval)) {
+ *          return ErrorEval.VALUE_INVALID;
+ *      }
+ *      temp += ((NumericValueEval)ve).getNumberValue();
+ *  }
+ *  // ...
  * }
  * }
* In this example, if any error is encountered while processing the arguments, an error is @@ -57,39 +57,39 @@ package org.apache.poi.ss.formula.eval; * *
{@code
  * public Eval evaluate(Eval[] args, int srcRow, short srcCol) {
- *	try {
- *		// ...
- *		AreaEval area = getAreaArg(args[0]);
- *		double temp = sumValues(area.getValues());
- *		// ...
- *	} catch (EvaluationException e) {
- *		return e.getErrorEval();
- *	}
+ *  try {
+ *      // ...
+ *      AreaEval area = getAreaArg(args[0]);
+ *      double temp = sumValues(area.getValues());
+ *      // ...
+ *  } catch (EvaluationException e) {
+ *      return e.getErrorEval();
+ *  }
  *}
  *
  *private static AreaEval getAreaArg(Eval arg0) throws EvaluationException {
- *	if (arg0 instanceof ErrorEval) {
- *		throw new EvaluationException((ErrorEval) arg0);
- *	}
- *	if (arg0 instanceof AreaEval) {
- *		return (AreaEval) arg0;
- *	}
- *	throw EvaluationException.invalidValue();
+ *  if (arg0 instanceof ErrorEval) {
+ *      throw new EvaluationException((ErrorEval) arg0);
+ *  }
+ *  if (arg0 instanceof AreaEval) {
+ *      return (AreaEval) arg0;
+ *  }
+ *  throw EvaluationException.invalidValue();
  *}
  *
  *private double sumValues(ValueEval[] values) throws EvaluationException {
- *	double temp = 0;
- *	for (int i = 0; i < values.length; i++) {
- *		ValueEval ve = values[i];
- *		if (ve instanceof ErrorEval) {
- *			throw new EvaluationException((ErrorEval) ve);
- *		}
- *		if (!(ve instanceof NumericValueEval)) {
- *			throw EvaluationException.invalidValue();
- *		}
- *		temp += ((NumericValueEval) ve).getNumberValue();
- *	}
- *	return temp;
+ *  double temp = 0;
+ *  for (int i = 0; i < values.length; i++) {
+ *      ValueEval ve = values[i];
+ *      if (ve instanceof ErrorEval) {
+ *          throw new EvaluationException((ErrorEval) ve);
+ *      }
+ *      if (!(ve instanceof NumericValueEval)) {
+ *          throw EvaluationException.invalidValue();
+ *      }
+ *      temp += ((NumericValueEval) ve).getNumberValue();
+ *  }
+ *  return temp;
  *}
  * }
* It is not mandatory to use EvaluationException, doing so might give the following advantages:
@@ -107,27 +107,27 @@ package org.apache.poi.ss.formula.eval; * be taken to not translate any POI internal error into an Excel evaluation error code. */ public final class EvaluationException extends Exception { - private final ErrorEval _errorEval; + private final ErrorEval _errorEval; - public EvaluationException(ErrorEval errorEval) { - _errorEval = errorEval; - } - // some convenience factory methods + public EvaluationException(ErrorEval errorEval) { + _errorEval = errorEval; + } + // some convenience factory methods /** #VALUE! - Wrong type of operand */ - public static EvaluationException invalidValue() { - return new EvaluationException(ErrorEval.VALUE_INVALID); - } + public static EvaluationException invalidValue() { + return new EvaluationException(ErrorEval.VALUE_INVALID); + } /** #REF! - Illegal or deleted cell reference */ - public static EvaluationException invalidRef() { - return new EvaluationException(ErrorEval.REF_INVALID); - } + public static EvaluationException invalidRef() { + return new EvaluationException(ErrorEval.REF_INVALID); + } /** #NUM! - Value range overflow */ - public static EvaluationException numberError() { - return new EvaluationException(ErrorEval.NUM_ERROR); - } + public static EvaluationException numberError() { + return new EvaluationException(ErrorEval.NUM_ERROR); + } - public ErrorEval getErrorEval() { - return _errorEval; - } + public ErrorEval getErrorEval() { + return _errorEval; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/ExternalNameEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/ExternalNameEval.java index cd813fb96f..6724c707b7 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/ExternalNameEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/ExternalNameEval.java @@ -23,19 +23,19 @@ import org.apache.poi.ss.formula.EvaluationName; * Evaluation of a Name defined in a Sheet or Workbook scope */ public final class ExternalNameEval implements ValueEval { - private final EvaluationName _name; + private final EvaluationName _name; - public ExternalNameEval(EvaluationName name) { - _name = name; - } + public ExternalNameEval(EvaluationName name) { + _name = name; + } - public EvaluationName getName() { - return _name; - } + public EvaluationName getName() { + return _name; + } - public String toString() { - return getClass().getName() + " [" + - _name.getNameText() + - "]"; - } + public String toString() { + return getClass().getName() + " [" + + _name.getNameText() + + "]"; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/FunctionNameEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/FunctionNameEval.java index b98c8a80f9..1447a65e6a 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/FunctionNameEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/FunctionNameEval.java @@ -19,23 +19,23 @@ package org.apache.poi.ss.formula.eval; public final class FunctionNameEval implements ValueEval { - private final String _functionName; + private final String _functionName; - /** - * Creates a NameEval representing a function name - */ - public FunctionNameEval(String functionName) { - _functionName = functionName; - } + /** + * Creates a NameEval representing a function name + */ + public FunctionNameEval(String functionName) { + _functionName = functionName; + } - public String getFunctionName() { - return _functionName; - } + public String getFunctionName() { + return _functionName; + } - public String toString() { - return getClass().getName() + " [" + - _functionName + - "]"; - } + public String toString() { + return getClass().getName() + " [" + + _functionName + + "]"; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/IntersectionEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/IntersectionEval.java index 36cd234c68..cb6fe4aae4 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/IntersectionEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/IntersectionEval.java @@ -22,73 +22,73 @@ import org.apache.poi.ss.formula.functions.Function; public final class IntersectionEval extends Fixed2ArgFunction { - public static final Function instance = new IntersectionEval(); + public static final Function instance = new IntersectionEval(); - private IntersectionEval() { - // enforces singleton - } + private IntersectionEval() { + // enforces singleton + } - @Override - public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { + @Override + public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { - try { - AreaEval reA = evaluateRef(arg0); - AreaEval reB = evaluateRef(arg1); - AreaEval result = resolveRange(reA, reB); - if (result == null) { - return ErrorEval.NULL_INTERSECTION; - } - return result; - } catch (EvaluationException e) { - return e.getErrorEval(); - } - } + try { + AreaEval reA = evaluateRef(arg0); + AreaEval reB = evaluateRef(arg1); + AreaEval result = resolveRange(reA, reB); + if (result == null) { + return ErrorEval.NULL_INTERSECTION; + } + return result; + } catch (EvaluationException e) { + return e.getErrorEval(); + } + } - /** - * @return simple rectangular {@link AreaEval} which represents the intersection of areas - * {@code aeA} and {@code aeB}. If the two areas do not intersect, the result is {@code null}. - */ - private static AreaEval resolveRange(AreaEval aeA, AreaEval aeB) { + /** + * @return simple rectangular {@link AreaEval} which represents the intersection of areas + * {@code aeA} and {@code aeB}. If the two areas do not intersect, the result is {@code null}. + */ + private static AreaEval resolveRange(AreaEval aeA, AreaEval aeB) { - int aeAfr = aeA.getFirstRow(); - int aeAfc = aeA.getFirstColumn(); - int aeBlc = aeB.getLastColumn(); - if (aeAfc > aeBlc) { - return null; - } - int aeBfc = aeB.getFirstColumn(); - if (aeBfc > aeA.getLastColumn()) { - return null; - } - int aeBlr = aeB.getLastRow(); - if (aeAfr > aeBlr) { - return null; - } - int aeBfr = aeB.getFirstRow(); - int aeAlr = aeA.getLastRow(); - if (aeBfr > aeAlr) { - return null; - } + int aeAfr = aeA.getFirstRow(); + int aeAfc = aeA.getFirstColumn(); + int aeBlc = aeB.getLastColumn(); + if (aeAfc > aeBlc) { + return null; + } + int aeBfc = aeB.getFirstColumn(); + if (aeBfc > aeA.getLastColumn()) { + return null; + } + int aeBlr = aeB.getLastRow(); + if (aeAfr > aeBlr) { + return null; + } + int aeBfr = aeB.getFirstRow(); + int aeAlr = aeA.getLastRow(); + if (aeBfr > aeAlr) { + return null; + } - int top = Math.max(aeAfr, aeBfr); - int bottom = Math.min(aeAlr, aeBlr); - int left = Math.max(aeAfc, aeBfc); - int right = Math.min(aeA.getLastColumn(), aeBlc); + int top = Math.max(aeAfr, aeBfr); + int bottom = Math.min(aeAlr, aeBlr); + int left = Math.max(aeAfc, aeBfc); + int right = Math.min(aeA.getLastColumn(), aeBlc); - return aeA.offset(top-aeAfr, bottom-aeAfr, left-aeAfc, right-aeAfc); - } + return aeA.offset(top-aeAfr, bottom-aeAfr, left-aeAfc, right-aeAfc); + } - private static AreaEval evaluateRef(ValueEval arg) throws EvaluationException { - if (arg instanceof AreaEval) { - return (AreaEval) arg; - } - if (arg instanceof RefEval) { - return ((RefEval) arg).offset(0, 0, 0, 0); - } - if (arg instanceof ErrorEval) { - throw new EvaluationException((ErrorEval)arg); - } - throw new IllegalArgumentException("Unexpected ref arg class (" + arg.getClass().getName() + ")"); - } + private static AreaEval evaluateRef(ValueEval arg) throws EvaluationException { + if (arg instanceof AreaEval) { + return (AreaEval) arg; + } + if (arg instanceof RefEval) { + return ((RefEval) arg).offset(0, 0, 0, 0); + } + if (arg instanceof ErrorEval) { + throw new EvaluationException((ErrorEval)arg); + } + throw new IllegalArgumentException("Unexpected ref arg class (" + arg.getClass().getName() + ")"); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/MissingArgEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/MissingArgEval.java index 185509e57e..f65e7a50fc 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/MissingArgEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/MissingArgEval.java @@ -26,9 +26,9 @@ package org.apache.poi.ss.formula.eval; */ public final class MissingArgEval implements ValueEval { - public static final MissingArgEval instance = new MissingArgEval(); + public static final MissingArgEval instance = new MissingArgEval(); - private MissingArgEval() { - // enforce singleton - } + private MissingArgEval() { + // enforce singleton + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/NotImplementedException.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/NotImplementedException.java index 9d81f8ce36..bb9373fbcc 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/NotImplementedException.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/NotImplementedException.java @@ -32,9 +32,9 @@ public class NotImplementedException extends RuntimeException { private static final long serialVersionUID = -5840703336495141301L; public NotImplementedException(String message) { - super(message); - } - public NotImplementedException(String message, NotImplementedException cause) { - super(message, cause); - } + super(message); + } + public NotImplementedException(String message, NotImplementedException cause) { + super(message, cause); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/NotImplementedFunctionException.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/NotImplementedFunctionException.java index 182e53b153..6dea6732d6 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/NotImplementedFunctionException.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/NotImplementedFunctionException.java @@ -29,16 +29,16 @@ public final class NotImplementedFunctionException extends NotImplementedExcepti private String functionName; - public NotImplementedFunctionException(String functionName) { - super(functionName); - this.functionName = functionName; - } - public NotImplementedFunctionException(String functionName, NotImplementedException cause) { - super(functionName, cause); + public NotImplementedFunctionException(String functionName) { + super(functionName); this.functionName = functionName; - } - - public String getFunctionName() { - return functionName; - } + } + public NotImplementedFunctionException(String functionName, NotImplementedException cause) { + super(functionName, cause); + this.functionName = functionName; + } + + public String getFunctionName() { + return functionName; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/PercentEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/PercentEval.java index f78dfabc01..6d335074b0 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/PercentEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/PercentEval.java @@ -26,24 +26,24 @@ import org.apache.poi.ss.formula.functions.Function; */ public final class PercentEval extends Fixed1ArgFunction { - public static final Function instance = new PercentEval(); + public static final Function instance = new PercentEval(); - private PercentEval() { - // enforce singleton - } + private PercentEval() { + // enforce singleton + } - @Override - public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) { - double d; - try { - ValueEval ve = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); - d = OperandResolver.coerceValueToDouble(ve); - } catch (EvaluationException e) { - return e.getErrorEval(); - } - if (d == 0.0) { // this '==' matches +0.0 and -0.0 - return NumberEval.ZERO; - } - return new NumberEval(d / 100); - } + @Override + public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) { + double d; + try { + ValueEval ve = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); + d = OperandResolver.coerceValueToDouble(ve); + } catch (EvaluationException e) { + return e.getErrorEval(); + } + if (d == 0.0) { // this '==' matches +0.0 and -0.0 + return NumberEval.ZERO; + } + return new NumberEval(d / 100); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/RangeEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/RangeEval.java index f11fb72245..0913a96016 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/RangeEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/RangeEval.java @@ -23,50 +23,50 @@ import org.apache.poi.ss.formula.functions.Function; public final class RangeEval extends Fixed2ArgFunction { - public static final Function instance = new RangeEval(); + public static final Function instance = new RangeEval(); - private RangeEval() { - // enforces singleton - } + private RangeEval() { + // enforces singleton + } - @Override - public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { + @Override + public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { - try { - AreaEval reA = evaluateRef(arg0); - AreaEval reB = evaluateRef(arg1); - return resolveRange(reA, reB); - } catch (EvaluationException e) { - return e.getErrorEval(); - } - } + try { + AreaEval reA = evaluateRef(arg0); + AreaEval reB = evaluateRef(arg1); + return resolveRange(reA, reB); + } catch (EvaluationException e) { + return e.getErrorEval(); + } + } - /** - * @return simple rectangular {@link AreaEval} which fully encloses both areas - * {@code aeA} and {@code aeB} - */ - private static AreaEval resolveRange(AreaEval aeA, AreaEval aeB) { - int aeAfr = aeA.getFirstRow(); - int aeAfc = aeA.getFirstColumn(); + /** + * @return simple rectangular {@link AreaEval} which fully encloses both areas + * {@code aeA} and {@code aeB} + */ + private static AreaEval resolveRange(AreaEval aeA, AreaEval aeB) { + int aeAfr = aeA.getFirstRow(); + int aeAfc = aeA.getFirstColumn(); - int top = Math.min(aeAfr, aeB.getFirstRow()); - int bottom = Math.max(aeA.getLastRow(), aeB.getLastRow()); - int left = Math.min(aeAfc, aeB.getFirstColumn()); - int right = Math.max(aeA.getLastColumn(), aeB.getLastColumn()); + int top = Math.min(aeAfr, aeB.getFirstRow()); + int bottom = Math.max(aeA.getLastRow(), aeB.getLastRow()); + int left = Math.min(aeAfc, aeB.getFirstColumn()); + int right = Math.max(aeA.getLastColumn(), aeB.getLastColumn()); - return aeA.offset(top-aeAfr, bottom-aeAfr, left-aeAfc, right-aeAfc); - } + return aeA.offset(top-aeAfr, bottom-aeAfr, left-aeAfc, right-aeAfc); + } - private static AreaEval evaluateRef(ValueEval arg) throws EvaluationException { - if (arg instanceof AreaEval) { - return (AreaEval) arg; - } - if (arg instanceof RefEval) { - return ((RefEval) arg).offset(0, 0, 0, 0); - } - if (arg instanceof ErrorEval) { - throw new EvaluationException((ErrorEval)arg); - } - throw new IllegalArgumentException("Unexpected ref arg class (" + arg.getClass().getName() + ")"); - } + private static AreaEval evaluateRef(ValueEval arg) throws EvaluationException { + if (arg instanceof AreaEval) { + return (AreaEval) arg; + } + if (arg instanceof RefEval) { + return ((RefEval) arg).offset(0, 0, 0, 0); + } + if (arg instanceof ErrorEval) { + throw new EvaluationException((ErrorEval)arg); + } + throw new IllegalArgumentException("Unexpected ref arg class (" + arg.getClass().getName() + ")"); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/RefEvalBase.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/RefEvalBase.java index bd96c4eb81..7ae776fee2 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/RefEvalBase.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/RefEvalBase.java @@ -25,8 +25,8 @@ import org.apache.poi.ss.formula.SheetRange; public abstract class RefEvalBase implements RefEval { private final int _firstSheetIndex; private final int _lastSheetIndex; - private final int _rowIndex; - private final int _columnIndex; + private final int _rowIndex; + private final int _columnIndex; protected RefEvalBase(SheetRange sheetRange, int rowIndex, int columnIndex) { if (sheetRange == null) { @@ -37,18 +37,18 @@ public abstract class RefEvalBase implements RefEval { _rowIndex = rowIndex; _columnIndex = columnIndex; } - protected RefEvalBase(int firstSheetIndex, int lastSheetIndex, int rowIndex, int columnIndex) { - _firstSheetIndex = firstSheetIndex; - _lastSheetIndex = lastSheetIndex; - _rowIndex = rowIndex; - _columnIndex = columnIndex; - } + protected RefEvalBase(int firstSheetIndex, int lastSheetIndex, int rowIndex, int columnIndex) { + _firstSheetIndex = firstSheetIndex; + _lastSheetIndex = lastSheetIndex; + _rowIndex = rowIndex; + _columnIndex = columnIndex; + } protected RefEvalBase(int onlySheetIndex, int rowIndex, int columnIndex) { this(onlySheetIndex, onlySheetIndex, rowIndex, columnIndex); } - public int getNumberOfSheets() { - return _lastSheetIndex-_firstSheetIndex+1; + public int getNumberOfSheets() { + return _lastSheetIndex-_firstSheetIndex+1; } public int getFirstSheetIndex() { return _firstSheetIndex; @@ -57,9 +57,9 @@ public abstract class RefEvalBase implements RefEval { return _lastSheetIndex; } public final int getRow() { - return _rowIndex; - } - public final int getColumn() { - return _columnIndex; - } + return _rowIndex; + } + public final int getColumn() { + return _columnIndex; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/RelationalOperationEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/RelationalOperationEval.java index 0c808ea843..dafc5e0ed0 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/RelationalOperationEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/RelationalOperationEval.java @@ -27,154 +27,154 @@ import org.apache.poi.ss.util.NumberComparer; */ public abstract class RelationalOperationEval extends Fixed2ArgFunction implements ArrayFunction { - /** - * Converts a standard compare result (-1, 0, 1) to true or false - * according to subclass' comparison type. - */ - protected abstract boolean convertComparisonResult(int cmpResult); + /** + * Converts a standard compare result (-1, 0, 1) to true or false + * according to subclass' comparison type. + */ + protected abstract boolean convertComparisonResult(int cmpResult); - /** - * This is a description of how the relational operators apply in MS Excel. - * Use this as a guideline when testing/implementing the evaluate methods - * for the relational operators Evals. - * - *
-	 * Bool.TRUE > any number.
-	 * Bool > any string. ALWAYS
-	 * Bool.TRUE > Bool.FALSE
-	 * Bool.FALSE == Blank
-	 *
-	 * Strings are never converted to numbers or booleans
-	 * String > any number. ALWAYS
-	 * Non-empty String > Blank
-	 * Empty String == Blank
-	 * String are sorted dictionary wise
-	 *
-	 * Blank > Negative numbers
-	 * Blank == 0
-	 * Blank < Positive numbers
-	 * 
- */ + /** + * This is a description of how the relational operators apply in MS Excel. + * Use this as a guideline when testing/implementing the evaluate methods + * for the relational operators Evals. + * + *
+     * Bool.TRUE > any number.
+     * Bool > any string. ALWAYS
+     * Bool.TRUE > Bool.FALSE
+     * Bool.FALSE == Blank
+     *
+     * Strings are never converted to numbers or booleans
+     * String > any number. ALWAYS
+     * Non-empty String > Blank
+     * Empty String == Blank
+     * String are sorted dictionary wise
+     *
+     * Blank > Negative numbers
+     * Blank == 0
+     * Blank < Positive numbers
+     * 
+ */ - public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { + public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { - ValueEval vA; - ValueEval vB; - try { - vA = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); - vB = OperandResolver.getSingleValue(arg1, srcRowIndex, srcColumnIndex); - } catch (EvaluationException e) { - return e.getErrorEval(); - } - int cmpResult = doCompare(vA, vB); - boolean result = convertComparisonResult(cmpResult); - return BoolEval.valueOf(result); - } + ValueEval vA; + ValueEval vB; + try { + vA = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); + vB = OperandResolver.getSingleValue(arg1, srcRowIndex, srcColumnIndex); + } catch (EvaluationException e) { + return e.getErrorEval(); + } + int cmpResult = doCompare(vA, vB); + boolean result = convertComparisonResult(cmpResult); + return BoolEval.valueOf(result); + } - @Override - public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { - ValueEval arg0 = args[0]; - ValueEval arg1 = args[1]; - return evaluateTwoArrayArgs(arg0, arg1, srcRowIndex, srcColumnIndex, (vA, vB) -> { - int cmpResult = doCompare(vA, vB); - boolean result = convertComparisonResult(cmpResult); - return BoolEval.valueOf(result); - }); + @Override + public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { + ValueEval arg0 = args[0]; + ValueEval arg1 = args[1]; + return evaluateTwoArrayArgs(arg0, arg1, srcRowIndex, srcColumnIndex, (vA, vB) -> { + int cmpResult = doCompare(vA, vB); + boolean result = convertComparisonResult(cmpResult); + return BoolEval.valueOf(result); + }); - } + } - private static int doCompare(ValueEval va, ValueEval vb) { - // special cases when one operand is blank or missing - if (va == BlankEval.instance || va instanceof MissingArgEval) { - return compareBlank(vb); - } - if (vb == BlankEval.instance || vb instanceof MissingArgEval) { - return -compareBlank(va); - } + private static int doCompare(ValueEval va, ValueEval vb) { + // special cases when one operand is blank or missing + if (va == BlankEval.instance || va instanceof MissingArgEval) { + return compareBlank(vb); + } + if (vb == BlankEval.instance || vb instanceof MissingArgEval) { + return -compareBlank(va); + } - if (va instanceof BoolEval) { - if (vb instanceof BoolEval) { - BoolEval bA = (BoolEval) va; - BoolEval bB = (BoolEval) vb; - if (bA.getBooleanValue() == bB.getBooleanValue()) { - return 0; - } - return bA.getBooleanValue() ? 1 : -1; - } - return 1; - } - if (vb instanceof BoolEval) { - return -1; - } - if (va instanceof StringEval) { - if (vb instanceof StringEval) { - StringEval sA = (StringEval) va; - StringEval sB = (StringEval) vb; - return sA.getStringValue().compareToIgnoreCase(sB.getStringValue()); - } - return 1; - } - if (vb instanceof StringEval) { - return -1; - } - if (va instanceof NumberEval) { - if (vb instanceof NumberEval) { - NumberEval nA = (NumberEval) va; - NumberEval nB = (NumberEval) vb; - return NumberComparer.compare(nA.getNumberValue(), nB.getNumberValue()); - } - } - throw new IllegalArgumentException("Bad operand types (" + va.getClass().getName() + "), (" - + vb.getClass().getName() + ")"); - } + if (va instanceof BoolEval) { + if (vb instanceof BoolEval) { + BoolEval bA = (BoolEval) va; + BoolEval bB = (BoolEval) vb; + if (bA.getBooleanValue() == bB.getBooleanValue()) { + return 0; + } + return bA.getBooleanValue() ? 1 : -1; + } + return 1; + } + if (vb instanceof BoolEval) { + return -1; + } + if (va instanceof StringEval) { + if (vb instanceof StringEval) { + StringEval sA = (StringEval) va; + StringEval sB = (StringEval) vb; + return sA.getStringValue().compareToIgnoreCase(sB.getStringValue()); + } + return 1; + } + if (vb instanceof StringEval) { + return -1; + } + if (va instanceof NumberEval) { + if (vb instanceof NumberEval) { + NumberEval nA = (NumberEval) va; + NumberEval nB = (NumberEval) vb; + return NumberComparer.compare(nA.getNumberValue(), nB.getNumberValue()); + } + } + throw new IllegalArgumentException("Bad operand types (" + va.getClass().getName() + "), (" + + vb.getClass().getName() + ")"); + } - private static int compareBlank(ValueEval v) { - if (v == BlankEval.instance || v instanceof MissingArgEval) { - return 0; - } - if (v instanceof BoolEval) { - BoolEval boolEval = (BoolEval) v; - return boolEval.getBooleanValue() ? -1 : 0; - } - if (v instanceof NumberEval) { - NumberEval ne = (NumberEval) v; - return NumberComparer.compare(0.0, ne.getNumberValue()); - } - if (v instanceof StringEval) { - StringEval se = (StringEval) v; - return se.getStringValue().length() < 1 ? 0 : -1; - } - throw new IllegalArgumentException("bad value class (" + v.getClass().getName() + ")"); - } + private static int compareBlank(ValueEval v) { + if (v == BlankEval.instance || v instanceof MissingArgEval) { + return 0; + } + if (v instanceof BoolEval) { + BoolEval boolEval = (BoolEval) v; + return boolEval.getBooleanValue() ? -1 : 0; + } + if (v instanceof NumberEval) { + NumberEval ne = (NumberEval) v; + return NumberComparer.compare(0.0, ne.getNumberValue()); + } + if (v instanceof StringEval) { + StringEval se = (StringEval) v; + return se.getStringValue().length() < 1 ? 0 : -1; + } + throw new IllegalArgumentException("bad value class (" + v.getClass().getName() + ")"); + } - public static final Function EqualEval = new RelationalOperationEval() { - protected boolean convertComparisonResult(int cmpResult) { - return cmpResult == 0; - } - }; - public static final Function GreaterEqualEval = new RelationalOperationEval() { - protected boolean convertComparisonResult(int cmpResult) { - return cmpResult >= 0; - } - }; - public static final Function GreaterThanEval = new RelationalOperationEval() { - protected boolean convertComparisonResult(int cmpResult) { - return cmpResult > 0; - } - }; - public static final Function LessEqualEval = new RelationalOperationEval() { - protected boolean convertComparisonResult(int cmpResult) { - return cmpResult <= 0; - } - }; - public static final Function LessThanEval = new RelationalOperationEval() { - protected boolean convertComparisonResult(int cmpResult) { - return cmpResult < 0; - } - }; - public static final Function NotEqualEval = new RelationalOperationEval() { - protected boolean convertComparisonResult(int cmpResult) { - return cmpResult != 0; - } - }; + public static final Function EqualEval = new RelationalOperationEval() { + protected boolean convertComparisonResult(int cmpResult) { + return cmpResult == 0; + } + }; + public static final Function GreaterEqualEval = new RelationalOperationEval() { + protected boolean convertComparisonResult(int cmpResult) { + return cmpResult >= 0; + } + }; + public static final Function GreaterThanEval = new RelationalOperationEval() { + protected boolean convertComparisonResult(int cmpResult) { + return cmpResult > 0; + } + }; + public static final Function LessEqualEval = new RelationalOperationEval() { + protected boolean convertComparisonResult(int cmpResult) { + return cmpResult <= 0; + } + }; + public static final Function LessThanEval = new RelationalOperationEval() { + protected boolean convertComparisonResult(int cmpResult) { + return cmpResult < 0; + } + }; + public static final Function NotEqualEval = new RelationalOperationEval() { + protected boolean convertComparisonResult(int cmpResult) { + return cmpResult != 0; + } + }; } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/StringEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/StringEval.java index cad32e0050..a475c0a24f 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/StringEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/StringEval.java @@ -24,29 +24,29 @@ import org.apache.poi.ss.formula.ptg.StringPtg; public final class StringEval implements StringValueEval { - public static final StringEval EMPTY_INSTANCE = new StringEval(""); + public static final StringEval EMPTY_INSTANCE = new StringEval(""); - //@NotNull - private final String _value; + //@NotNull + private final String _value; - public StringEval(Ptg ptg) { - this(((StringPtg) ptg).getValue()); - } + public StringEval(Ptg ptg) { + this(((StringPtg) ptg).getValue()); + } - public StringEval(String value) { - if (value == null) { - throw new IllegalArgumentException("value must not be null"); - } - _value = value; - } + public StringEval(String value) { + if (value == null) { + throw new IllegalArgumentException("value must not be null"); + } + _value = value; + } - public String getStringValue() { - return _value; - } + public String getStringValue() { + return _value; + } - public String toString() { - return getClass().getName() + " [" + - _value + - "]"; - } + public String toString() { + return getClass().getName() + " [" + + _value + + "]"; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/TwoOperandNumericOperation.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/TwoOperandNumericOperation.java index 03f22788ff..9e3f3610d5 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/TwoOperandNumericOperation.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/TwoOperandNumericOperation.java @@ -23,94 +23,94 @@ import org.apache.poi.ss.formula.functions.Function; public abstract class TwoOperandNumericOperation extends Fixed2ArgFunction implements ArrayFunction { - protected final double singleOperandEvaluate(ValueEval arg, int srcCellRow, int srcCellCol) throws EvaluationException { - ValueEval ve = OperandResolver.getSingleValue(arg, srcCellRow, srcCellCol); - return OperandResolver.coerceValueToDouble(ve); - } + protected final double singleOperandEvaluate(ValueEval arg, int srcCellRow, int srcCellCol) throws EvaluationException { + ValueEval ve = OperandResolver.getSingleValue(arg, srcCellRow, srcCellCol); + return OperandResolver.coerceValueToDouble(ve); + } - @Override + @Override public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { - if (args.length != 2) { - return ErrorEval.VALUE_INVALID; - } - //return new ArrayEval().evaluate(srcRowIndex, srcColumnIndex, args[0], args[1]); + if (args.length != 2) { + return ErrorEval.VALUE_INVALID; + } + //return new ArrayEval().evaluate(srcRowIndex, srcColumnIndex, args[0], args[1]); - return evaluateTwoArrayArgs(args[0], args[1], srcRowIndex, srcColumnIndex, - (vA, vB) -> { - try { - double d0 = OperandResolver.coerceValueToDouble(vA); - double d1 = OperandResolver.coerceValueToDouble(vB); - double result = evaluate(d0, d1); - return new NumberEval(result); - } catch (EvaluationException e){ - return e.getErrorEval(); - } - }); + return evaluateTwoArrayArgs(args[0], args[1], srcRowIndex, srcColumnIndex, + (vA, vB) -> { + try { + double d0 = OperandResolver.coerceValueToDouble(vA); + double d1 = OperandResolver.coerceValueToDouble(vB); + double result = evaluate(d0, d1); + return new NumberEval(result); + } catch (EvaluationException e){ + return e.getErrorEval(); + } + }); - } + } - @Override - public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { - double result; - try { - double d0 = singleOperandEvaluate(arg0, srcRowIndex, srcColumnIndex); - double d1 = singleOperandEvaluate(arg1, srcRowIndex, srcColumnIndex); - result = evaluate(d0, d1); - if (result == 0.0) { // this '==' matches +0.0 and -0.0 - // Excel converts -0.0 to +0.0 for '*', '/', '%', '+' and '^' - if (!(this instanceof SubtractEvalClass)) { - return NumberEval.ZERO; - } - } - if (Double.isNaN(result) || Double.isInfinite(result)) { - return ErrorEval.NUM_ERROR; - } - } catch (EvaluationException e) { - return e.getErrorEval(); - } - return new NumberEval(result); - } + @Override + public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { + double result; + try { + double d0 = singleOperandEvaluate(arg0, srcRowIndex, srcColumnIndex); + double d1 = singleOperandEvaluate(arg1, srcRowIndex, srcColumnIndex); + result = evaluate(d0, d1); + if (result == 0.0) { // this '==' matches +0.0 and -0.0 + // Excel converts -0.0 to +0.0 for '*', '/', '%', '+' and '^' + if (!(this instanceof SubtractEvalClass)) { + return NumberEval.ZERO; + } + } + if (Double.isNaN(result) || Double.isInfinite(result)) { + return ErrorEval.NUM_ERROR; + } + } catch (EvaluationException e) { + return e.getErrorEval(); + } + return new NumberEval(result); + } - protected abstract double evaluate(double d0, double d1) throws EvaluationException; + protected abstract double evaluate(double d0, double d1) throws EvaluationException; - public static final Function AddEval = new TwoOperandNumericOperation() { - @Override - protected double evaluate(double d0, double d1) { - return d0+d1; - } - }; - public static final Function DivideEval = new TwoOperandNumericOperation() { - @Override - protected double evaluate(double d0, double d1) throws EvaluationException { - if (d1 == 0.0) { - throw new EvaluationException(ErrorEval.DIV_ZERO); - } - return d0/d1; - } - }; - public static final Function MultiplyEval = new TwoOperandNumericOperation() { - @Override - protected double evaluate(double d0, double d1) { - return d0*d1; - } - }; - public static final Function PowerEval = new TwoOperandNumericOperation() { - @Override - protected double evaluate(double d0, double d1) { - if(d0 < 0 && Math.abs(d1) > 0.0 && Math.abs(d1) < 1.0) { - return -1 * Math.pow(d0 * -1, d1); - } - return Math.pow(d0, d1); - } - }; - private static final class SubtractEvalClass extends TwoOperandNumericOperation { - public SubtractEvalClass() { - // - } - @Override - protected double evaluate(double d0, double d1) { - return d0-d1; - } - } - public static final Function SubtractEval = new SubtractEvalClass(); + public static final Function AddEval = new TwoOperandNumericOperation() { + @Override + protected double evaluate(double d0, double d1) { + return d0+d1; + } + }; + public static final Function DivideEval = new TwoOperandNumericOperation() { + @Override + protected double evaluate(double d0, double d1) throws EvaluationException { + if (d1 == 0.0) { + throw new EvaluationException(ErrorEval.DIV_ZERO); + } + return d0/d1; + } + }; + public static final Function MultiplyEval = new TwoOperandNumericOperation() { + @Override + protected double evaluate(double d0, double d1) { + return d0*d1; + } + }; + public static final Function PowerEval = new TwoOperandNumericOperation() { + @Override + protected double evaluate(double d0, double d1) { + if(d0 < 0 && Math.abs(d1) > 0.0 && Math.abs(d1) < 1.0) { + return -1 * Math.pow(d0 * -1, d1); + } + return Math.pow(d0, d1); + } + }; + private static final class SubtractEvalClass extends TwoOperandNumericOperation { + public SubtractEvalClass() { + // + } + @Override + protected double evaluate(double d0, double d1) { + return d0-d1; + } + } + public static final Function SubtractEval = new SubtractEvalClass(); } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/UnaryMinusEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/UnaryMinusEval.java index 922c5cc90a..61d8bfddf5 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/UnaryMinusEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/UnaryMinusEval.java @@ -23,34 +23,34 @@ import org.apache.poi.ss.formula.functions.Function; public final class UnaryMinusEval extends Fixed1ArgFunction implements ArrayFunction { - public static final Function instance = new UnaryMinusEval(); + public static final Function instance = new UnaryMinusEval(); - private UnaryMinusEval() { - // enforce singleton - } + private UnaryMinusEval() { + // enforce singleton + } - public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) { - double d; - try { - ValueEval ve = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); - d = OperandResolver.coerceValueToDouble(ve); - } catch (EvaluationException e) { - return e.getErrorEval(); - } - if (d == 0.0) { // this '==' matches +0.0 and -0.0 - return NumberEval.ZERO; - } - return new NumberEval(-d); - } + public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) { + double d; + try { + ValueEval ve = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); + d = OperandResolver.coerceValueToDouble(ve); + } catch (EvaluationException e) { + return e.getErrorEval(); + } + if (d == 0.0) { // this '==' matches +0.0 and -0.0 + return NumberEval.ZERO; + } + return new NumberEval(-d); + } - @Override - public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex){ - if (args.length != 1) { - return ErrorEval.VALUE_INVALID; - } - return evaluateOneArrayArg(args[0], srcRowIndex, srcColumnIndex, (valA) -> - evaluate(srcRowIndex, srcColumnIndex, valA) - ); - } + @Override + public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex){ + if (args.length != 1) { + return ErrorEval.VALUE_INVALID; + } + return evaluateOneArrayArg(args[0], srcRowIndex, srcColumnIndex, (valA) -> + evaluate(srcRowIndex, srcColumnIndex, valA) + ); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/UnaryPlusEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/UnaryPlusEval.java index f8d73dfd15..f5fc420ea5 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/UnaryPlusEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/UnaryPlusEval.java @@ -24,37 +24,37 @@ import org.apache.poi.ss.formula.functions.Function; public final class UnaryPlusEval extends Fixed1ArgFunction implements ArrayFunction { - public static final Function instance = new UnaryPlusEval(); + public static final Function instance = new UnaryPlusEval(); - private UnaryPlusEval() { - // enforce singleton - } + private UnaryPlusEval() { + // enforce singleton + } - public ValueEval evaluate(int srcCellRow, int srcCellCol, ValueEval arg0) { - double d; - try { - ValueEval ve = OperandResolver.getSingleValue(arg0, srcCellRow, srcCellCol); - if(ve instanceof StringEval) { - // Note - asymmetric with UnaryMinus - // -"hello" evaluates to #VALUE! - // but +"hello" evaluates to "hello" - return ve; - } - d = OperandResolver.coerceValueToDouble(ve); - } catch (EvaluationException e) { - return e.getErrorEval(); - } - return new NumberEval(+d); - } + public ValueEval evaluate(int srcCellRow, int srcCellCol, ValueEval arg0) { + double d; + try { + ValueEval ve = OperandResolver.getSingleValue(arg0, srcCellRow, srcCellCol); + if(ve instanceof StringEval) { + // Note - asymmetric with UnaryMinus + // -"hello" evaluates to #VALUE! + // but +"hello" evaluates to "hello" + return ve; + } + d = OperandResolver.coerceValueToDouble(ve); + } catch (EvaluationException e) { + return e.getErrorEval(); + } + return new NumberEval(+d); + } - @Override - public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex){ - if (args.length != 1) { - return ErrorEval.VALUE_INVALID; - } - return evaluateOneArrayArg(args[0], srcRowIndex, srcColumnIndex, (valA) -> - evaluate(srcRowIndex, srcColumnIndex, valA) - ); - } + @Override + public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex){ + if (args.length != 1) { + return ErrorEval.VALUE_INVALID; + } + return evaluateOneArrayArg(args[0], srcRowIndex, srcColumnIndex, (valA) -> + evaluate(srcRowIndex, srcColumnIndex, valA) + ); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/ValueEval.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/ValueEval.java index a9db4cac58..2252c57061 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/ValueEval.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/ValueEval.java @@ -18,5 +18,5 @@ package org.apache.poi.ss.formula.eval; public interface ValueEval { - // no methods + // no methods } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationCell.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationCell.java index 7f7f137c98..e864294ab8 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationCell.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluationCell.java @@ -35,124 +35,124 @@ import org.apache.poi.ss.util.CellRangeAddress; */ final class ForkedEvaluationCell implements EvaluationCell { - private final EvaluationSheet _sheet; - /** corresponding cell from master workbook */ - private final EvaluationCell _masterCell; - private boolean _booleanValue; - private CellType _cellType; - private int _errorValue; - private double _numberValue; - private String _stringValue; + private final EvaluationSheet _sheet; + /** corresponding cell from master workbook */ + private final EvaluationCell _masterCell; + private boolean _booleanValue; + private CellType _cellType; + private int _errorValue; + private double _numberValue; + private String _stringValue; - public ForkedEvaluationCell(ForkedEvaluationSheet sheet, EvaluationCell masterCell) { - _sheet = sheet; - _masterCell = masterCell; - // start with value blank, but expect construction to be immediately - setValue(BlankEval.instance); // followed by a proper call to setValue() - } + public ForkedEvaluationCell(ForkedEvaluationSheet sheet, EvaluationCell masterCell) { + _sheet = sheet; + _masterCell = masterCell; + // start with value blank, but expect construction to be immediately + setValue(BlankEval.instance); // followed by a proper call to setValue() + } - @Override - public Object getIdentityKey() { - return _masterCell.getIdentityKey(); - } + @Override + public Object getIdentityKey() { + return _masterCell.getIdentityKey(); + } - public void setValue(ValueEval value) { - Class cls = value.getClass(); + public void setValue(ValueEval value) { + Class cls = value.getClass(); - if (cls == NumberEval.class) { - _cellType = CellType.NUMERIC; - _numberValue = ((NumberEval)value).getNumberValue(); - return; - } - if (cls == StringEval.class) { - _cellType = CellType.STRING; - _stringValue = ((StringEval)value).getStringValue(); - return; - } - if (cls == BoolEval.class) { - _cellType = CellType.BOOLEAN; - _booleanValue = ((BoolEval)value).getBooleanValue(); - return; - } - if (cls == ErrorEval.class) { - _cellType = CellType.ERROR; - _errorValue = ((ErrorEval)value).getErrorCode(); - return; - } - if (cls == BlankEval.class) { - _cellType = CellType.BLANK; - return; - } - throw new IllegalArgumentException("Unexpected value class (" + cls.getName() + ")"); - } - public void copyValue(Cell destCell) { - switch (_cellType) { - case BLANK: destCell.setBlank(); return; - case NUMERIC: destCell.setCellValue(_numberValue); return; - case BOOLEAN: destCell.setCellValue(_booleanValue); return; - case STRING: destCell.setCellValue(_stringValue); return; - case ERROR: destCell.setCellErrorValue((byte)_errorValue); return; - default: throw new IllegalStateException("Unexpected data type (" + _cellType + ")"); - } - } + if (cls == NumberEval.class) { + _cellType = CellType.NUMERIC; + _numberValue = ((NumberEval)value).getNumberValue(); + return; + } + if (cls == StringEval.class) { + _cellType = CellType.STRING; + _stringValue = ((StringEval)value).getStringValue(); + return; + } + if (cls == BoolEval.class) { + _cellType = CellType.BOOLEAN; + _booleanValue = ((BoolEval)value).getBooleanValue(); + return; + } + if (cls == ErrorEval.class) { + _cellType = CellType.ERROR; + _errorValue = ((ErrorEval)value).getErrorCode(); + return; + } + if (cls == BlankEval.class) { + _cellType = CellType.BLANK; + return; + } + throw new IllegalArgumentException("Unexpected value class (" + cls.getName() + ")"); + } + public void copyValue(Cell destCell) { + switch (_cellType) { + case BLANK: destCell.setBlank(); return; + case NUMERIC: destCell.setCellValue(_numberValue); return; + case BOOLEAN: destCell.setCellValue(_booleanValue); return; + case STRING: destCell.setCellValue(_stringValue); return; + case ERROR: destCell.setCellErrorValue((byte)_errorValue); return; + default: throw new IllegalStateException("Unexpected data type (" + _cellType + ")"); + } + } - private void checkCellType(CellType expectedCellType) { - if (_cellType != expectedCellType) { - throw new RuntimeException("Wrong data type (" + _cellType + ")"); - } - } + private void checkCellType(CellType expectedCellType) { + if (_cellType != expectedCellType) { + throw new RuntimeException("Wrong data type (" + _cellType + ")"); + } + } - @Override - public CellType getCellType() { - return _cellType; - } - @Override - public boolean getBooleanCellValue() { - checkCellType(CellType.BOOLEAN); - return _booleanValue; - } - @Override - public int getErrorCellValue() { - checkCellType(CellType.ERROR); - return _errorValue; - } - @Override - public double getNumericCellValue() { - checkCellType(CellType.NUMERIC); - return _numberValue; - } - @Override - public String getStringCellValue() { - checkCellType(CellType.STRING); - return _stringValue; - } - @Override - public EvaluationSheet getSheet() { - return _sheet; - } - @Override - public int getRowIndex() { - return _masterCell.getRowIndex(); - } - @Override - public int getColumnIndex() { - return _masterCell.getColumnIndex(); - } + @Override + public CellType getCellType() { + return _cellType; + } + @Override + public boolean getBooleanCellValue() { + checkCellType(CellType.BOOLEAN); + return _booleanValue; + } + @Override + public int getErrorCellValue() { + checkCellType(CellType.ERROR); + return _errorValue; + } + @Override + public double getNumericCellValue() { + checkCellType(CellType.NUMERIC); + return _numberValue; + } + @Override + public String getStringCellValue() { + checkCellType(CellType.STRING); + return _stringValue; + } + @Override + public EvaluationSheet getSheet() { + return _sheet; + } + @Override + public int getRowIndex() { + return _masterCell.getRowIndex(); + } + @Override + public int getColumnIndex() { + return _masterCell.getColumnIndex(); + } - @Override - public CellRangeAddress getArrayFormulaRange() { - return _masterCell.getArrayFormulaRange(); - } + @Override + public CellRangeAddress getArrayFormulaRange() { + return _masterCell.getArrayFormulaRange(); + } - @Override - public boolean isPartOfArrayFormulaGroup() { - return _masterCell.isPartOfArrayFormulaGroup(); - } - /** - * @return cell type of cached formula result - */ - @Override - public CellType getCachedFormulaResultType() { - return _masterCell.getCachedFormulaResultType(); - } + @Override + public boolean isPartOfArrayFormulaGroup() { + return _masterCell.isPartOfArrayFormulaGroup(); + } + /** + * @return cell type of cached formula result + */ + @Override + public CellType getCachedFormulaResultType() { + return _masterCell.getCachedFormulaResultType(); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluator.java b/poi/src/main/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluator.java index 8231653cea..0b6e2b17bc 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluator.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/eval/forked/ForkedEvaluator.java @@ -43,84 +43,84 @@ import org.apache.poi.ss.usermodel.Workbook; */ public final class ForkedEvaluator { - private final WorkbookEvaluator _evaluator; - private final ForkedEvaluationWorkbook _sewb; + private final WorkbookEvaluator _evaluator; + private final ForkedEvaluationWorkbook _sewb; - private ForkedEvaluator(EvaluationWorkbook masterWorkbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { - _sewb = new ForkedEvaluationWorkbook(masterWorkbook); - _evaluator = new WorkbookEvaluator(_sewb, stabilityClassifier, udfFinder); - } + private ForkedEvaluator(EvaluationWorkbook masterWorkbook, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { + _sewb = new ForkedEvaluationWorkbook(masterWorkbook); + _evaluator = new WorkbookEvaluator(_sewb, stabilityClassifier, udfFinder); + } - /** - * @param udfFinder pass {@code null} for default (AnalysisToolPak only) - */ - public static ForkedEvaluator create(Workbook wb, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { - return new ForkedEvaluator(wb.createEvaluationWorkbook(), stabilityClassifier, udfFinder); - } + /** + * @param udfFinder pass {@code null} for default (AnalysisToolPak only) + */ + public static ForkedEvaluator create(Workbook wb, IStabilityClassifier stabilityClassifier, UDFFinder udfFinder) { + return new ForkedEvaluator(wb.createEvaluationWorkbook(), stabilityClassifier, udfFinder); + } - /** - * Sets the specified cell to the supplied {@code value} - * @param sheetName the name of the sheet containing the cell - * @param rowIndex zero based - * @param columnIndex zero based - */ - public void updateCell(String sheetName, int rowIndex, int columnIndex, ValueEval value) { - - ForkedEvaluationCell cell = _sewb.getOrCreateUpdatableCell(sheetName, rowIndex, columnIndex); - cell.setValue(value); - _evaluator.notifyUpdateCell(cell); - } - /** - * Copies the values of all updated cells (modified by calls to {@link - * #updateCell(String, int, int, ValueEval)}) to the supplied {@code workbook}.
- * Typically, the supplied {@code workbook} is a writable copy of the 'master workbook', - * but at the very least it must contain sheets with the same names. - */ - public void copyUpdatedCells(Workbook workbook) { - _sewb.copyUpdatedCells(workbook); - } - - /** - * If cell contains a formula, the formula is evaluated and returned, - * else the CellValue simply copies the appropriate cell value from - * the cell and also its cell type. This method should be preferred over - * evaluateInCell() when the call should not modify the contents of the - * original cell. - * + /** + * Sets the specified cell to the supplied {@code value} * @param sheetName the name of the sheet containing the cell * @param rowIndex zero based * @param columnIndex zero based - * @return {@code null} if the supplied cell is {@code null} or blank - */ - public ValueEval evaluate(String sheetName, int rowIndex, int columnIndex) { - EvaluationCell cell = _sewb.getEvaluationCell(sheetName, rowIndex, columnIndex); + */ + public void updateCell(String sheetName, int rowIndex, int columnIndex, ValueEval value) { - switch (cell.getCellType()) { - case BOOLEAN: - return BoolEval.valueOf(cell.getBooleanCellValue()); - case ERROR: - return ErrorEval.valueOf(cell.getErrorCellValue()); - case FORMULA: - return _evaluator.evaluate(cell); - case NUMERIC: - return new NumberEval(cell.getNumericCellValue()); - case STRING: - return new StringEval(cell.getStringCellValue()); - case BLANK: - return null; - default: - throw new IllegalStateException("Bad cell type (" + cell.getCellType() + ")"); - } - } - /** - * Coordinates several formula evaluators together so that formulas that involve external - * references can be evaluated. - * @param workbookNames the simple file names used to identify the workbooks in formulas - * with external links (for example "MyData.xls" as used in a formula "[MyData.xls]Sheet1!A1") - * @param evaluators all evaluators for the full set of workbooks required by the formulas. - */ - public static void setupEnvironment(String[] workbookNames, ForkedEvaluator[] evaluators) { - WorkbookEvaluator[] wbEvals = Stream.of(evaluators).map(e -> e._evaluator).toArray(WorkbookEvaluator[]::new); - CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals); - } + ForkedEvaluationCell cell = _sewb.getOrCreateUpdatableCell(sheetName, rowIndex, columnIndex); + cell.setValue(value); + _evaluator.notifyUpdateCell(cell); + } + /** + * Copies the values of all updated cells (modified by calls to {@link + * #updateCell(String, int, int, ValueEval)}) to the supplied {@code workbook}.
+ * Typically, the supplied {@code workbook} is a writable copy of the 'master workbook', + * but at the very least it must contain sheets with the same names. + */ + public void copyUpdatedCells(Workbook workbook) { + _sewb.copyUpdatedCells(workbook); + } + + /** + * If cell contains a formula, the formula is evaluated and returned, + * else the CellValue simply copies the appropriate cell value from + * the cell and also its cell type. This method should be preferred over + * evaluateInCell() when the call should not modify the contents of the + * original cell. + * + * @param sheetName the name of the sheet containing the cell + * @param rowIndex zero based + * @param columnIndex zero based + * @return {@code null} if the supplied cell is {@code null} or blank + */ + public ValueEval evaluate(String sheetName, int rowIndex, int columnIndex) { + EvaluationCell cell = _sewb.getEvaluationCell(sheetName, rowIndex, columnIndex); + + switch (cell.getCellType()) { + case BOOLEAN: + return BoolEval.valueOf(cell.getBooleanCellValue()); + case ERROR: + return ErrorEval.valueOf(cell.getErrorCellValue()); + case FORMULA: + return _evaluator.evaluate(cell); + case NUMERIC: + return new NumberEval(cell.getNumericCellValue()); + case STRING: + return new StringEval(cell.getStringCellValue()); + case BLANK: + return null; + default: + throw new IllegalStateException("Bad cell type (" + cell.getCellType() + ")"); + } + } + /** + * Coordinates several formula evaluators together so that formulas that involve external + * references can be evaluated. + * @param workbookNames the simple file names used to identify the workbooks in formulas + * with external links (for example "MyData.xls" as used in a formula "[MyData.xls]Sheet1!A1") + * @param evaluators all evaluators for the full set of workbooks required by the formulas. + */ + public static void setupEnvironment(String[] workbookNames, ForkedEvaluator[] evaluators) { + WorkbookEvaluator[] wbEvals = Stream.of(evaluators).map(e -> e._evaluator).toArray(WorkbookEvaluator[]::new); + CollaboratingWorkbooksEnvironment.setup(workbookNames, wbEvals); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionDataBuilder.java b/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionDataBuilder.java index fefc4d0987..6baef59ef9 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionDataBuilder.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionDataBuilder.java @@ -27,62 +27,62 @@ import java.util.Set; * {@code FunctionMetadataRegistry}. */ final class FunctionDataBuilder { - private int _maxFunctionIndex; - private final Map _functionDataByName; - private final Map _functionDataByIndex; - /** stores indexes of all functions with footnotes (i.e. whose definitions might change) */ - private final Set _mutatingFunctionIndexes; + private int _maxFunctionIndex; + private final Map _functionDataByName; + private final Map _functionDataByIndex; + /** stores indexes of all functions with footnotes (i.e. whose definitions might change) */ + private final Set _mutatingFunctionIndexes; - public FunctionDataBuilder(int sizeEstimate) { - _maxFunctionIndex = -1; - _functionDataByName = new HashMap<>(sizeEstimate * 3 / 2); - _functionDataByIndex = new HashMap<>(sizeEstimate * 3 / 2); - _mutatingFunctionIndexes = new HashSet<>(); - } + public FunctionDataBuilder(int sizeEstimate) { + _maxFunctionIndex = -1; + _functionDataByName = new HashMap<>(sizeEstimate * 3 / 2); + _functionDataByIndex = new HashMap<>(sizeEstimate * 3 / 2); + _mutatingFunctionIndexes = new HashSet<>(); + } - public void add(int functionIndex, String functionName, int minParams, int maxParams, - byte returnClassCode, byte[] parameterClassCodes, boolean hasFootnote) { - FunctionMetadata fm = new FunctionMetadata(functionIndex, functionName, minParams, maxParams, - returnClassCode, parameterClassCodes); + public void add(int functionIndex, String functionName, int minParams, int maxParams, + byte returnClassCode, byte[] parameterClassCodes, boolean hasFootnote) { + FunctionMetadata fm = new FunctionMetadata(functionIndex, functionName, minParams, maxParams, + returnClassCode, parameterClassCodes); - Integer indexKey = functionIndex; + Integer indexKey = functionIndex; - if(functionIndex > _maxFunctionIndex) { - _maxFunctionIndex = functionIndex; - } - // allow function definitions to change only if both previous and the new items have footnotes - FunctionMetadata prevFM; - prevFM = _functionDataByName.get(functionName); - if(prevFM != null) { - if(!hasFootnote || !_mutatingFunctionIndexes.contains(indexKey)) { - throw new RuntimeException("Multiple entries for function name '" + functionName + "'"); - } - _functionDataByIndex.remove(prevFM.getIndex()); - } - prevFM = _functionDataByIndex.get(indexKey); - if(prevFM != null) { - if(!hasFootnote || !_mutatingFunctionIndexes.contains(indexKey)) { - throw new RuntimeException("Multiple entries for function index (" + functionIndex + ")"); - } - _functionDataByName.remove(prevFM.getName()); - } - if(hasFootnote) { - _mutatingFunctionIndexes.add(indexKey); - } - _functionDataByIndex.put(indexKey, fm); - _functionDataByName.put(functionName, fm); - } + if(functionIndex > _maxFunctionIndex) { + _maxFunctionIndex = functionIndex; + } + // allow function definitions to change only if both previous and the new items have footnotes + FunctionMetadata prevFM; + prevFM = _functionDataByName.get(functionName); + if(prevFM != null) { + if(!hasFootnote || !_mutatingFunctionIndexes.contains(indexKey)) { + throw new RuntimeException("Multiple entries for function name '" + functionName + "'"); + } + _functionDataByIndex.remove(prevFM.getIndex()); + } + prevFM = _functionDataByIndex.get(indexKey); + if(prevFM != null) { + if(!hasFootnote || !_mutatingFunctionIndexes.contains(indexKey)) { + throw new RuntimeException("Multiple entries for function index (" + functionIndex + ")"); + } + _functionDataByName.remove(prevFM.getName()); + } + if(hasFootnote) { + _mutatingFunctionIndexes.add(indexKey); + } + _functionDataByIndex.put(indexKey, fm); + _functionDataByName.put(functionName, fm); + } - public FunctionMetadataRegistry build() { + public FunctionMetadataRegistry build() { - FunctionMetadata[] jumbledArray = new FunctionMetadata[_functionDataByName.size()]; - _functionDataByName.values().toArray(jumbledArray); - FunctionMetadata[] fdIndexArray = new FunctionMetadata[_maxFunctionIndex+1]; - for (FunctionMetadata fd : jumbledArray) { - fdIndexArray[fd.getIndex()] = fd; - } + FunctionMetadata[] jumbledArray = new FunctionMetadata[_functionDataByName.size()]; + _functionDataByName.values().toArray(jumbledArray); + FunctionMetadata[] fdIndexArray = new FunctionMetadata[_maxFunctionIndex+1]; + for (FunctionMetadata fd : jumbledArray) { + fdIndexArray[fd.getIndex()] = fd; + } - return new FunctionMetadataRegistry(fdIndexArray, _functionDataByName); - } + return new FunctionMetadataRegistry(fdIndexArray, _functionDataByName); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadata.java b/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadata.java index 9c80cd4623..deddc9ae10 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadata.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadata.java @@ -6,7 +6,7 @@ (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 + 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, @@ -21,74 +21,74 @@ package org.apache.poi.ss.formula.function; * Holds information about Excel built-in functions. */ public final class FunctionMetadata { - /** - * maxParams=30 in functionMetadata.txt means the maximum number arguments supported - * by the given version of Excel. Validation routines should take the actual limit (Excel 97 or 2007) - * from the SpreadsheetVersion enum. - * Perhaps a value like 'M' should be used instead of '30' in functionMetadata.txt - * to make that file more version neutral. - * @see org.apache.poi.ss.formula.FormulaParser#validateNumArgs(int, FunctionMetadata) - */ - @SuppressWarnings("JavadocReference") - private static final short FUNCTION_MAX_PARAMS = 30; + /** + * maxParams=30 in functionMetadata.txt means the maximum number arguments supported + * by the given version of Excel. Validation routines should take the actual limit (Excel 97 or 2007) + * from the SpreadsheetVersion enum. + * Perhaps a value like 'M' should be used instead of '30' in functionMetadata.txt + * to make that file more version neutral. + * @see org.apache.poi.ss.formula.FormulaParser#validateNumArgs(int, FunctionMetadata) + */ + @SuppressWarnings("JavadocReference") + private static final short FUNCTION_MAX_PARAMS = 30; - private final int _index; - private final String _name; - private final int _minParams; - private final int _maxParams; - private final byte _returnClassCode; - private final byte[] _parameterClassCodes; + private final int _index; + private final String _name; + private final int _minParams; + private final int _maxParams; + private final byte _returnClassCode; + private final byte[] _parameterClassCodes; - /* package */ FunctionMetadata(int index, String name, int minParams, int maxParams, - byte returnClassCode, byte[] parameterClassCodes) { - _index = index; - _name = name; - _minParams = minParams; - _maxParams = maxParams; - _returnClassCode = returnClassCode; - _parameterClassCodes = (parameterClassCodes == null) ? null : parameterClassCodes.clone(); - } + /* package */ FunctionMetadata(int index, String name, int minParams, int maxParams, + byte returnClassCode, byte[] parameterClassCodes) { + _index = index; + _name = name; + _minParams = minParams; + _maxParams = maxParams; + _returnClassCode = returnClassCode; + _parameterClassCodes = (parameterClassCodes == null) ? null : parameterClassCodes.clone(); + } - public int getIndex() { - return _index; - } + public int getIndex() { + return _index; + } - public String getName() { - return _name; - } + public String getName() { + return _name; + } - public int getMinParams() { - return _minParams; - } + public int getMinParams() { + return _minParams; + } - public int getMaxParams() { - return _maxParams; - } + public int getMaxParams() { + return _maxParams; + } - public boolean hasFixedArgsLength() { - return _minParams == _maxParams; - } + public boolean hasFixedArgsLength() { + return _minParams == _maxParams; + } - public byte getReturnClassCode() { - return _returnClassCode; - } + public byte getReturnClassCode() { + return _returnClassCode; + } - public byte[] getParameterClassCodes() { - return _parameterClassCodes.clone(); - } + public byte[] getParameterClassCodes() { + return _parameterClassCodes.clone(); + } - /** - * Some varags functions (like VLOOKUP) have a specific limit to the number of arguments that - * can be passed. Other functions (like SUM) don't have such a limit. For those functions, - * the spreadsheet version determines the maximum number of arguments that can be passed. - * @return true if this function can the maximum number of arguments allowable by - * the {@link org.apache.poi.ss.SpreadsheetVersion} - */ - public boolean hasUnlimitedVarags() { - return FUNCTION_MAX_PARAMS == _maxParams; - } + /** + * Some varags functions (like VLOOKUP) have a specific limit to the number of arguments that + * can be passed. Other functions (like SUM) don't have such a limit. For those functions, + * the spreadsheet version determines the maximum number of arguments that can be passed. + * @return true if this function can the maximum number of arguments allowable by + * the {@link org.apache.poi.ss.SpreadsheetVersion} + */ + public boolean hasUnlimitedVarags() { + return FUNCTION_MAX_PARAMS == _maxParams; + } - public String toString() { - return getClass().getName() + " [" + _index + " " + _name + "]"; - } + public String toString() { + return getClass().getName() + " [" + _index + " " + _name + "]"; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadataReader.java b/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadataReader.java index fce0793765..236546c3b4 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadataReader.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadataReader.java @@ -6,7 +6,7 @@ (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 + 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, @@ -35,162 +35,162 @@ import org.apache.poi.util.IOUtils; */ final class FunctionMetadataReader { - //arbitrarily selected; may need to increase - private static final int MAX_RECORD_LENGTH = 100_000; + //arbitrarily selected; may need to increase + private static final int MAX_RECORD_LENGTH = 100_000; - private static final String METADATA_FILE_NAME = "functionMetadata.txt"; - private static final String METADATA_FILE_NAME_CETAB = "functionMetadataCetab.txt"; + private static final String METADATA_FILE_NAME = "functionMetadata.txt"; + private static final String METADATA_FILE_NAME_CETAB = "functionMetadataCetab.txt"; - /** plain ASCII text metadata file uses three dots for ellipsis */ - private static final String ELLIPSIS = "..."; + /** plain ASCII text metadata file uses three dots for ellipsis */ + private static final String ELLIPSIS = "..."; - private static final Pattern TAB_DELIM_PATTERN = Pattern.compile("\t"); - private static final Pattern SPACE_DELIM_PATTERN = Pattern.compile(" "); - private static final byte[] EMPTY_BYTE_ARRAY = { }; + private static final Pattern TAB_DELIM_PATTERN = Pattern.compile("\t"); + private static final Pattern SPACE_DELIM_PATTERN = Pattern.compile(" "); + private static final byte[] EMPTY_BYTE_ARRAY = { }; - private static final String[] DIGIT_ENDING_FUNCTION_NAMES = { - // Digits at the end of a function might be due to a left-over footnote marker. - // except in these cases - "LOG10", "ATAN2", "DAYS360", "SUMXMY2", "SUMX2MY2", "SUMX2PY2", "A1.R1C1", - }; - private static final Set DIGIT_ENDING_FUNCTION_NAMES_SET = new HashSet<>(Arrays.asList(DIGIT_ENDING_FUNCTION_NAMES)); + private static final String[] DIGIT_ENDING_FUNCTION_NAMES = { + // Digits at the end of a function might be due to a left-over footnote marker. + // except in these cases + "LOG10", "ATAN2", "DAYS360", "SUMXMY2", "SUMX2MY2", "SUMX2PY2", "A1.R1C1", + }; + private static final Set DIGIT_ENDING_FUNCTION_NAMES_SET = new HashSet<>(Arrays.asList(DIGIT_ENDING_FUNCTION_NAMES)); - public static FunctionMetadataRegistry createRegistry() { - FunctionDataBuilder fdb = new FunctionDataBuilder(800); - readResourceFile(fdb, METADATA_FILE_NAME); - return fdb.build(); - } + public static FunctionMetadataRegistry createRegistry() { + FunctionDataBuilder fdb = new FunctionDataBuilder(800); + readResourceFile(fdb, METADATA_FILE_NAME); + return fdb.build(); + } - public static FunctionMetadataRegistry createRegistryCetab() { - FunctionDataBuilder fdb = new FunctionDataBuilder(800); - readResourceFile(fdb, METADATA_FILE_NAME_CETAB); - return fdb.build(); - } + public static FunctionMetadataRegistry createRegistryCetab() { + FunctionDataBuilder fdb = new FunctionDataBuilder(800); + readResourceFile(fdb, METADATA_FILE_NAME_CETAB); + return fdb.build(); + } - private static void readResourceFile(FunctionDataBuilder fdb, String resourceFile) { - try (InputStream is = FunctionMetadataReader.class.getResourceAsStream(resourceFile)) { - if (is == null) { - throw new RuntimeException("resource '" + resourceFile + "' not found"); - } + private static void readResourceFile(FunctionDataBuilder fdb, String resourceFile) { + try (InputStream is = FunctionMetadataReader.class.getResourceAsStream(resourceFile)) { + if (is == null) { + throw new RuntimeException("resource '" + resourceFile + "' not found"); + } - try(BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { + try(BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { - while (true) { - String line = br.readLine(); - if (line == null) { - break; - } - if (line.length() < 1 || line.charAt(0) == '#') { - continue; - } - String trimLine = line.trim(); - if (trimLine.length() < 1) { - continue; - } - processLine(fdb, line); - } - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } + while (true) { + String line = br.readLine(); + if (line == null) { + break; + } + if (line.length() < 1 || line.charAt(0) == '#') { + continue; + } + String trimLine = line.trim(); + if (trimLine.length() < 1) { + continue; + } + processLine(fdb, line); + } + } + } catch (IOException e) { + throw new RuntimeException(e); + } + } - private static void processLine(FunctionDataBuilder fdb, String line) { + private static void processLine(FunctionDataBuilder fdb, String line) { - String[] parts = TAB_DELIM_PATTERN.split(line, -2); - if(parts.length != 8) { - throw new RuntimeException("Bad line format '" + line + "' - expected 8 data fields delimited by tab, " + - "but had " + parts.length + ": " + Arrays.toString(parts)); - } - int functionIndex = parseInt(parts[0]); - String functionName = parts[1]; - int minParams = parseInt(parts[2]); - int maxParams = parseInt(parts[3]); - byte returnClassCode = parseReturnTypeCode(parts[4]); - byte[] parameterClassCodes = parseOperandTypeCodes(parts[5]); - // 6 isVolatile - boolean hasNote = parts[7].length() > 0; + String[] parts = TAB_DELIM_PATTERN.split(line, -2); + if(parts.length != 8) { + throw new RuntimeException("Bad line format '" + line + "' - expected 8 data fields delimited by tab, " + + "but had " + parts.length + ": " + Arrays.toString(parts)); + } + int functionIndex = parseInt(parts[0]); + String functionName = parts[1]; + int minParams = parseInt(parts[2]); + int maxParams = parseInt(parts[3]); + byte returnClassCode = parseReturnTypeCode(parts[4]); + byte[] parameterClassCodes = parseOperandTypeCodes(parts[5]); + // 6 isVolatile + boolean hasNote = parts[7].length() > 0; - validateFunctionName(functionName); - // TODO - make POI use isVolatile - fdb.add(functionIndex, functionName, minParams, maxParams, - returnClassCode, parameterClassCodes, hasNote); - } + validateFunctionName(functionName); + // TODO - make POI use isVolatile + fdb.add(functionIndex, functionName, minParams, maxParams, + returnClassCode, parameterClassCodes, hasNote); + } - private static byte parseReturnTypeCode(String code) { - if(code.length() == 0) { - return Ptg.CLASS_REF; // happens for GETPIVOTDATA - } - return parseOperandTypeCode(code); - } + private static byte parseReturnTypeCode(String code) { + if(code.length() == 0) { + return Ptg.CLASS_REF; // happens for GETPIVOTDATA + } + return parseOperandTypeCode(code); + } - private static byte[] parseOperandTypeCodes(String codes) { - if(codes.length() < 1) { - return EMPTY_BYTE_ARRAY; // happens for GETPIVOTDATA - } - if(isDash(codes)) { - // '-' means empty: - return EMPTY_BYTE_ARRAY; - } - String[] array = SPACE_DELIM_PATTERN.split(codes); - int nItems = array.length; - if(ELLIPSIS.equals(array[nItems-1])) { - // final ellipsis is optional, and ignored - // (all unspecified params are assumed to be the same as the last) - nItems --; - } - byte[] result = IOUtils.safelyAllocate(nItems, MAX_RECORD_LENGTH); - for (int i = 0; i < nItems; i++) { - result[i] = parseOperandTypeCode(array[i]); - } - return result; - } + private static byte[] parseOperandTypeCodes(String codes) { + if(codes.length() < 1) { + return EMPTY_BYTE_ARRAY; // happens for GETPIVOTDATA + } + if(isDash(codes)) { + // '-' means empty: + return EMPTY_BYTE_ARRAY; + } + String[] array = SPACE_DELIM_PATTERN.split(codes); + int nItems = array.length; + if(ELLIPSIS.equals(array[nItems-1])) { + // final ellipsis is optional, and ignored + // (all unspecified params are assumed to be the same as the last) + nItems --; + } + byte[] result = IOUtils.safelyAllocate(nItems, MAX_RECORD_LENGTH); + for (int i = 0; i < nItems; i++) { + result[i] = parseOperandTypeCode(array[i]); + } + return result; + } - private static boolean isDash(String codes) { - return codes.length() == 1 && codes.charAt(0) == '-'; - } + private static boolean isDash(String codes) { + return codes.length() == 1 && codes.charAt(0) == '-'; + } - private static byte parseOperandTypeCode(String code) { - if(code.length() != 1) { - throw new RuntimeException("Bad operand type code format '" + code + "' expected single char"); - } - switch(code.charAt(0)) { - case 'V': return Ptg.CLASS_VALUE; - case 'R': return Ptg.CLASS_REF; - case 'A': return Ptg.CLASS_ARRAY; - } - throw new IllegalArgumentException("Unexpected operand type code '" + code + "' (" + (int)code.charAt(0) + ")"); - } + private static byte parseOperandTypeCode(String code) { + if(code.length() != 1) { + throw new RuntimeException("Bad operand type code format '" + code + "' expected single char"); + } + switch(code.charAt(0)) { + case 'V': return Ptg.CLASS_VALUE; + case 'R': return Ptg.CLASS_REF; + case 'A': return Ptg.CLASS_ARRAY; + } + throw new IllegalArgumentException("Unexpected operand type code '" + code + "' (" + (int)code.charAt(0) + ")"); + } - /** - * Makes sure that footnote digits from the original OOO document have not been accidentally - * left behind - */ - private static void validateFunctionName(String functionName) { - int len = functionName.length(); - int ix = len - 1; - if (!Character.isDigit(functionName.charAt(ix))) { - return; - } - while(ix >= 0) { - if (!Character.isDigit(functionName.charAt(ix))) { - break; - } - ix--; - } - if(DIGIT_ENDING_FUNCTION_NAMES_SET.contains(functionName)) { - return; - } - throw new RuntimeException("Invalid function name '" + functionName - + "' (is footnote number incorrectly appended)"); - } + /** + * Makes sure that footnote digits from the original OOO document have not been accidentally + * left behind + */ + private static void validateFunctionName(String functionName) { + int len = functionName.length(); + int ix = len - 1; + if (!Character.isDigit(functionName.charAt(ix))) { + return; + } + while(ix >= 0) { + if (!Character.isDigit(functionName.charAt(ix))) { + break; + } + ix--; + } + if(DIGIT_ENDING_FUNCTION_NAMES_SET.contains(functionName)) { + return; + } + throw new RuntimeException("Invalid function name '" + functionName + + "' (is footnote number incorrectly appended)"); + } - private static int parseInt(String valStr) { - try { - return Integer.parseInt(valStr); - } catch (NumberFormatException e) { - throw new RuntimeException("Value '" + valStr + "' could not be parsed as an integer"); - } - } + private static int parseInt(String valStr) { + try { + return Integer.parseInt(valStr); + } catch (NumberFormatException e) { + throw new RuntimeException("Value '" + valStr + "' could not be parsed as an integer"); + } + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadataRegistry.java b/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadataRegistry.java index 2430fa2551..b89713bf9f 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadataRegistry.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/function/FunctionMetadataRegistry.java @@ -24,86 +24,86 @@ import java.util.Set; * Allows clients to get {@link FunctionMetadata} instances for any built-in function of Excel. */ public final class FunctionMetadataRegistry { - /** - * The name of the IF function (i.e. "IF"). Extracted as a constant for clarity. - */ - public static final String FUNCTION_NAME_IF = "IF"; + /** + * The name of the IF function (i.e. "IF"). Extracted as a constant for clarity. + */ + public static final String FUNCTION_NAME_IF = "IF"; - public static final int FUNCTION_INDEX_IF = 1; - public static final short FUNCTION_INDEX_SUM = 4; - public static final int FUNCTION_INDEX_CHOOSE = 100; - public static final short FUNCTION_INDEX_INDIRECT = 148; - public static final short FUNCTION_INDEX_EXTERNAL = 255; + public static final int FUNCTION_INDEX_IF = 1; + public static final short FUNCTION_INDEX_SUM = 4; + public static final int FUNCTION_INDEX_CHOOSE = 100; + public static final short FUNCTION_INDEX_INDIRECT = 148; + public static final short FUNCTION_INDEX_EXTERNAL = 255; - private static FunctionMetadataRegistry _instance; - private static FunctionMetadataRegistry _instanceCetab; + private static FunctionMetadataRegistry _instance; + private static FunctionMetadataRegistry _instanceCetab; - private final FunctionMetadata[] _functionDataByIndex; - private final Map _functionDataByName; + private final FunctionMetadata[] _functionDataByIndex; + private final Map _functionDataByName; - private static FunctionMetadataRegistry getInstance() { - if (_instance == null) { - _instance = FunctionMetadataReader.createRegistry(); - } - return _instance; - } + private static FunctionMetadataRegistry getInstance() { + if (_instance == null) { + _instance = FunctionMetadataReader.createRegistry(); + } + return _instance; + } - private static FunctionMetadataRegistry getInstanceCetab() { - if (_instanceCetab == null) { - _instanceCetab = FunctionMetadataReader.createRegistryCetab(); - } - return _instanceCetab; - } + private static FunctionMetadataRegistry getInstanceCetab() { + if (_instanceCetab == null) { + _instanceCetab = FunctionMetadataReader.createRegistryCetab(); + } + return _instanceCetab; + } - /* package */ FunctionMetadataRegistry(FunctionMetadata[] functionDataByIndex, Map functionDataByName) { - _functionDataByIndex = (functionDataByIndex == null) ? null : functionDataByIndex.clone(); - _functionDataByName = functionDataByName; - } + /* package */ FunctionMetadataRegistry(FunctionMetadata[] functionDataByIndex, Map functionDataByName) { + _functionDataByIndex = (functionDataByIndex == null) ? null : functionDataByIndex.clone(); + _functionDataByName = functionDataByName; + } - /* package */ Set getAllFunctionNames() { - return _functionDataByName.keySet(); - } + /* package */ Set getAllFunctionNames() { + return _functionDataByName.keySet(); + } - public static FunctionMetadata getFunctionByIndex(int index) { - return getInstance().getFunctionByIndexInternal(index); - } + public static FunctionMetadata getFunctionByIndex(int index) { + return getInstance().getFunctionByIndexInternal(index); + } - public static FunctionMetadata getCetabFunctionByIndex(int index) { - return getInstanceCetab().getFunctionByIndexInternal(index); - } + public static FunctionMetadata getCetabFunctionByIndex(int index) { + return getInstanceCetab().getFunctionByIndexInternal(index); + } - private FunctionMetadata getFunctionByIndexInternal(int index) { - return _functionDataByIndex[index]; - } - /** - * Resolves a built-in function index. - * @param name uppercase function name - * @return a negative value if the function name is not found. - * This typically occurs for external functions. - */ - public static short lookupIndexByName(String name) { - FunctionMetadata fd = getInstance().getFunctionByNameInternal(name); - if (fd == null) { - // also try the cetab functions - fd = getInstanceCetab().getFunctionByNameInternal(name); - if (fd == null) { - return -1; - } - } - return (short) fd.getIndex(); - } + private FunctionMetadata getFunctionByIndexInternal(int index) { + return _functionDataByIndex[index]; + } + /** + * Resolves a built-in function index. + * @param name uppercase function name + * @return a negative value if the function name is not found. + * This typically occurs for external functions. + */ + public static short lookupIndexByName(String name) { + FunctionMetadata fd = getInstance().getFunctionByNameInternal(name); + if (fd == null) { + // also try the cetab functions + fd = getInstanceCetab().getFunctionByNameInternal(name); + if (fd == null) { + return -1; + } + } + return (short) fd.getIndex(); + } - private FunctionMetadata getFunctionByNameInternal(String name) { - return _functionDataByName.get(name); - } + private FunctionMetadata getFunctionByNameInternal(String name) { + return _functionDataByName.get(name); + } - public static FunctionMetadata getFunctionByName(String name) { - FunctionMetadata fm = getInstance().getFunctionByNameInternal(name); - if(fm == null) { - return getInstanceCetab().getFunctionByNameInternal(name); - } + public static FunctionMetadata getFunctionByName(String name) { + FunctionMetadata fm = getInstance().getFunctionByNameInternal(name); + if(fm == null) { + return getInstanceCetab().getFunctionByNameInternal(name); + } - return fm; - } + return fm; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/functions/Address.java b/poi/src/main/java/org/apache/poi/ss/formula/functions/Address.java index 315d689193..a72ed69656 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/functions/Address.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/functions/Address.java @@ -44,7 +44,7 @@ public class Address implements Function { if (args.length > 2 && args[2] != MissingArgEval.instance) { refType = (int)NumericFunction.singleOperandEvaluate(args[2], srcRowIndex, srcColumnIndex); } else { - refType = REF_ABSOLUTE; // this is also the default if parameter is not given + refType = REF_ABSOLUTE; // this is also the default if parameter is not given } switch (refType){ case REF_ABSOLUTE: diff --git a/poi/src/main/java/org/apache/poi/ss/formula/functions/BooleanFunction.java b/poi/src/main/java/org/apache/poi/ss/formula/functions/BooleanFunction.java index 885609ae41..d051dacc12 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/functions/BooleanFunction.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/functions/BooleanFunction.java @@ -37,45 +37,45 @@ import org.apache.poi.ss.formula.eval.ValueEval; */ public abstract class BooleanFunction implements Function,ArrayFunction { - public final ValueEval evaluate(ValueEval[] args, int srcRow, int srcCol) { - if (args.length < 1) { - return ErrorEval.VALUE_INVALID; - } - boolean boolResult; - try { - boolResult = calculate(args); - } catch (EvaluationException e) { - return e.getErrorEval(); - } - return BoolEval.valueOf(boolResult); - } + public final ValueEval evaluate(ValueEval[] args, int srcRow, int srcCol) { + if (args.length < 1) { + return ErrorEval.VALUE_INVALID; + } + boolean boolResult; + try { + boolResult = calculate(args); + } catch (EvaluationException e) { + return e.getErrorEval(); + } + return BoolEval.valueOf(boolResult); + } - private boolean calculate(ValueEval[] args) throws EvaluationException { + private boolean calculate(ValueEval[] args) throws EvaluationException { - boolean result = getInitialResultValue(); - boolean atLeastOneNonBlank = false; + boolean result = getInitialResultValue(); + boolean atLeastOneNonBlank = false; - /* - * Note: no short-circuit boolean loop exit because any ErrorEvals will override the result - */ - for (final ValueEval arg : args) { + /* + * Note: no short-circuit boolean loop exit because any ErrorEvals will override the result + */ + for (final ValueEval arg : args) { Boolean tempVe; - if (arg instanceof TwoDEval) { - TwoDEval ae = (TwoDEval) arg; - int height = ae.getHeight(); - int width = ae.getWidth(); - for (int rrIx=0; rrIx evaluate(new ValueEval[]{vA}, srcRowIndex, srcColumnIndex)); - } + @Override + public ValueEval evaluateArray(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { + if (args.length != 1) { + return ErrorEval.VALUE_INVALID; + } + return evaluateOneArrayArg(args[0], srcRowIndex, srcColumnIndex, + vA -> evaluate(new ValueEval[]{vA}, srcRowIndex, srcColumnIndex)); + } - private static ValueEval evaluateFalse(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { - return args.length != 0 ? ErrorEval.VALUE_INVALID : BoolEval.FALSE; - } + private static ValueEval evaluateFalse(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { + return args.length != 0 ? ErrorEval.VALUE_INVALID : BoolEval.FALSE; + } - private static ValueEval evaluateTrue(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { - return args.length != 0 ? ErrorEval.VALUE_INVALID : BoolEval.TRUE; - } + private static ValueEval evaluateTrue(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { + return args.length != 0 ? ErrorEval.VALUE_INVALID : BoolEval.TRUE; + } - private static ValueEval evaluateNot(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { - if (args.length != 1) { - return ErrorEval.VALUE_INVALID; - } - java.util.function.Function notInner = (va) -> { - try { - ValueEval ve = OperandResolver.getSingleValue(va, srcRowIndex, srcColumnIndex); - Boolean b = OperandResolver.coerceValueToBoolean(ve, false); - boolean boolArgVal = b != null && b; - return BoolEval.valueOf(!boolArgVal); - } catch (EvaluationException e) { - return e.getErrorEval(); - } - }; + private static ValueEval evaluateNot(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { + if (args.length != 1) { + return ErrorEval.VALUE_INVALID; + } + java.util.function.Function notInner = (va) -> { + try { + ValueEval ve = OperandResolver.getSingleValue(va, srcRowIndex, srcColumnIndex); + Boolean b = OperandResolver.coerceValueToBoolean(ve, false); + boolean boolArgVal = b != null && b; + return BoolEval.valueOf(!boolArgVal); + } catch (EvaluationException e) { + return e.getErrorEval(); + } + }; - return ArrayFunction._evaluateOneArrayArg(args[0], srcRowIndex, srcColumnIndex, notInner); - } + return ArrayFunction._evaluateOneArrayArg(args[0], srcRowIndex, srcColumnIndex, notInner); + } } \ No newline at end of file diff --git a/poi/src/main/java/org/apache/poi/ss/formula/functions/CalendarFieldFunction.java b/poi/src/main/java/org/apache/poi/ss/formula/functions/CalendarFieldFunction.java index 0a93244cc3..df2930e72b 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/functions/CalendarFieldFunction.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/functions/CalendarFieldFunction.java @@ -32,56 +32,56 @@ import org.apache.poi.ss.usermodel.DateUtil; * Time - HOUR, MINUTE and SECOND */ public final class CalendarFieldFunction extends Fixed1ArgFunction { - public static final Function YEAR = new CalendarFieldFunction(Calendar.YEAR); - public static final Function MONTH = new CalendarFieldFunction(Calendar.MONTH); - public static final Function DAY = new CalendarFieldFunction(Calendar.DAY_OF_MONTH); - public static final Function HOUR = new CalendarFieldFunction(Calendar.HOUR_OF_DAY); + public static final Function YEAR = new CalendarFieldFunction(Calendar.YEAR); + public static final Function MONTH = new CalendarFieldFunction(Calendar.MONTH); + public static final Function DAY = new CalendarFieldFunction(Calendar.DAY_OF_MONTH); + public static final Function HOUR = new CalendarFieldFunction(Calendar.HOUR_OF_DAY); public static final Function MINUTE = new CalendarFieldFunction(Calendar.MINUTE); public static final Function SECOND = new CalendarFieldFunction(Calendar.SECOND); - private final int _dateFieldId; + private final int _dateFieldId; - private CalendarFieldFunction(int dateFieldId) { - _dateFieldId = dateFieldId; - } + private CalendarFieldFunction(int dateFieldId) { + _dateFieldId = dateFieldId; + } - public final ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) { - double val; - try { - ValueEval ve = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); - val = OperandResolver.coerceValueToDouble(ve); - } catch (EvaluationException e) { - return e.getErrorEval(); - } - if (val < 0) { - return ErrorEval.NUM_ERROR; - } - return new NumberEval(getCalField(val)); - } + public final ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) { + double val; + try { + ValueEval ve = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); + val = OperandResolver.coerceValueToDouble(ve); + } catch (EvaluationException e) { + return e.getErrorEval(); + } + if (val < 0) { + return ErrorEval.NUM_ERROR; + } + return new NumberEval(getCalField(val)); + } - private int getCalField(double serialDate) { - // For some reason, a date of 0 in Excel gets shown - // as the non existant 1900-01-00 - if (((int)serialDate) == 0) { - switch (_dateFieldId) { - case Calendar.YEAR: return 1900; - case Calendar.MONTH: return 1; - case Calendar.DAY_OF_MONTH: return 0; - } - // They want time, that's normal - } + private int getCalField(double serialDate) { + // For some reason, a date of 0 in Excel gets shown + // as the non existant 1900-01-00 + if (((int)serialDate) == 0) { + switch (_dateFieldId) { + case Calendar.YEAR: return 1900; + case Calendar.MONTH: return 1; + case Calendar.DAY_OF_MONTH: return 0; + } + // They want time, that's normal + } - // TODO Figure out if we're in 1900 or 1904 - // EXCEL functions round up nearly a half second (probably to prevent floating point - // rounding issues); use UTC here to prevent daylight saving issues for HOUR - Calendar c = DateUtil.getJavaCalendarUTC(serialDate + 0.4995 / DateUtil.SECONDS_PER_DAY, false); - int result = c.get(_dateFieldId); + // TODO Figure out if we're in 1900 or 1904 + // EXCEL functions round up nearly a half second (probably to prevent floating point + // rounding issues); use UTC here to prevent daylight saving issues for HOUR + Calendar c = DateUtil.getJavaCalendarUTC(serialDate + 0.4995 / DateUtil.SECONDS_PER_DAY, false); + int result = c.get(_dateFieldId); - // Month is a special case due to C semantics - if (_dateFieldId == Calendar.MONTH) { - result++; - } + // Month is a special case due to C semantics + if (_dateFieldId == Calendar.MONTH) { + result++; + } - return result; - } + return result; + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/functions/Choose.java b/poi/src/main/java/org/apache/poi/ss/formula/functions/Choose.java index 6bcb825c3d..4f6e75e39d 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/functions/Choose.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/functions/Choose.java @@ -26,29 +26,29 @@ import org.apache.poi.ss.formula.eval.ValueEval; public final class Choose implements Function { - public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { - if (args.length < 2) { - return ErrorEval.VALUE_INVALID; - } + public ValueEval evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { + if (args.length < 2) { + return ErrorEval.VALUE_INVALID; + } - try { - int ix = evaluateFirstArg(args[0], srcRowIndex, srcColumnIndex); - if (ix < 1 || ix >= args.length) { - return ErrorEval.VALUE_INVALID; - } - ValueEval result = OperandResolver.getSingleValue(args[ix], srcRowIndex, srcColumnIndex); - if (result == MissingArgEval.instance) { - return BlankEval.instance; - } - return result; - } catch (EvaluationException e) { - return e.getErrorEval(); - } - } + try { + int ix = evaluateFirstArg(args[0], srcRowIndex, srcColumnIndex); + if (ix < 1 || ix >= args.length) { + return ErrorEval.VALUE_INVALID; + } + ValueEval result = OperandResolver.getSingleValue(args[ix], srcRowIndex, srcColumnIndex); + if (result == MissingArgEval.instance) { + return BlankEval.instance; + } + return result; + } catch (EvaluationException e) { + return e.getErrorEval(); + } + } - public static int evaluateFirstArg(ValueEval arg0, int srcRowIndex, int srcColumnIndex) - throws EvaluationException { - ValueEval ev = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); - return OperandResolver.coerceValueToInt(ev); - } + public static int evaluateFirstArg(ValueEval arg0, int srcRowIndex, int srcColumnIndex) + throws EvaluationException { + ValueEval ev = OperandResolver.getSingleValue(arg0, srcRowIndex, srcColumnIndex); + return OperandResolver.coerceValueToInt(ev); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/functions/Columns.java b/poi/src/main/java/org/apache/poi/ss/formula/functions/Columns.java index b129eb2f80..ff3ca6e88d 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/functions/Columns.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/functions/Columns.java @@ -28,16 +28,16 @@ import org.apache.poi.ss.formula.TwoDEval; */ public final class Columns extends Fixed1ArgFunction { - public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) { + public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0) { - int result; - if (arg0 instanceof TwoDEval) { - result = ((TwoDEval) arg0).getWidth(); - } else if (arg0 instanceof RefEval) { - result = 1; - } else { // anything else is not valid argument - return ErrorEval.VALUE_INVALID; - } - return new NumberEval(result); - } + int result; + if (arg0 instanceof TwoDEval) { + result = ((TwoDEval) arg0).getWidth(); + } else if (arg0 instanceof RefEval) { + result = 1; + } else { // anything else is not valid argument + return ErrorEval.VALUE_INVALID; + } + return new NumberEval(result); + } } diff --git a/poi/src/main/java/org/apache/poi/ss/formula/functions/Count.java b/poi/src/main/java/org/apache/poi/ss/formula/functions/Count.java index 25c0799054..9404e22599 100644 --- a/poi/src/main/java/org/apache/poi/ss/formula/functions/Count.java +++ b/poi/src/main/java/org/apache/poi/ss/formula/functions/Count.java @@ -47,44 +47,44 @@ public final class Count implements Function { _predicate = criteriaPredicate; } - public ValueEval evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) { - int nArgs = args.length; - if (nArgs < 1) { - // too few arguments - return ErrorEval.VALUE_INVALID; - } + public ValueEval evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) { + int nArgs = args.length; + if (nArgs < 1) { + // too few arguments + return ErrorEval.VALUE_INVALID; + } - if (nArgs > 30) { - // too many arguments - return ErrorEval.VALUE_INVALID; - } + if (nArgs > 30) { + // too many arguments + return ErrorEval.VALUE_INVALID; + } - int temp = 0; + int temp = 0; - for(int i=0; i