You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@tika.apache.org by ta...@apache.org on 2024/05/06 19:39:33 UTC
(tika) 01/01: tika-core first commit
This is an automated email from the ASF dual-hosted git repository.
tallison pushed a commit to branch google-java-format
in repository https://gitbox.apache.org/repos/asf/tika.git
commit 4a150fad9d89872a22cba56c6c968d8be1c5d309
Author: tallison <ta...@apache.org>
AuthorDate: Mon May 6 15:39:11 2024 -0400
tika-core first commit
---
.mvn/jvm.config | 1 +
tika-core/pom.xml | 44 +
tika-core/src/main/java/org/apache/tika/Tika.java | 385 ++--
.../concurrent/ConfigurableThreadPoolExecutor.java | 5 +-
.../tika/concurrent/SimpleThreadPoolExecutor.java | 11 +-
.../java/org/apache/tika/config/ConfigBase.java | 139 +-
.../main/java/org/apache/tika/config/Field.java | 5 +-
.../java/org/apache/tika/config/Initializable.java | 25 +-
.../tika/config/InitializableProblemHandler.java | 99 +-
.../org/apache/tika/config/LoadErrorHandler.java | 86 +-
.../main/java/org/apache/tika/config/Param.java | 81 +-
.../java/org/apache/tika/config/ParamField.java | 41 +-
.../java/org/apache/tika/config/ServiceLoader.java | 114 +-
.../java/org/apache/tika/config/TikaActivator.java | 25 +-
.../java/org/apache/tika/config/TikaConfig.java | 432 +++--
.../apache/tika/config/TikaConfigSerializer.java | 203 ++-
.../java/org/apache/tika/config/package-info.java | 4 +-
.../org/apache/tika/detect/AutoDetectReader.java | 46 +-
.../org/apache/tika/detect/CompositeDetector.java | 33 +-
.../tika/detect/CompositeEncodingDetector.java | 25 +-
.../org/apache/tika/detect/DefaultDetector.java | 49 +-
.../tika/detect/DefaultEncodingDetector.java | 24 +-
.../apache/tika/detect/DefaultProbDetector.java | 15 +-
.../main/java/org/apache/tika/detect/Detector.java | 36 +-
.../java/org/apache/tika/detect/EmptyDetector.java | 10 +-
.../org/apache/tika/detect/EncodingDetector.java | 34 +-
.../apache/tika/detect/FileCommandDetector.java | 63 +-
.../java/org/apache/tika/detect/MagicDetector.java | 213 ++-
.../apache/tika/detect/NNExampleModelDetector.java | 27 +-
.../org/apache/tika/detect/NNTrainedModel.java | 9 +-
.../apache/tika/detect/NNTrainedModelBuilder.java | 1 -
.../java/org/apache/tika/detect/NameDetector.java | 74 +-
.../tika/detect/NonDetectingEncodingDetector.java | 17 +-
.../org/apache/tika/detect/OverrideDetector.java | 11 +-
.../java/org/apache/tika/detect/TextDetector.java | 62 +-
.../org/apache/tika/detect/TextStatistics.java | 41 +-
.../java/org/apache/tika/detect/TrainedModel.java | 1 -
.../apache/tika/detect/TrainedModelDetector.java | 1 -
.../java/org/apache/tika/detect/TypeDetector.java | 19 +-
.../org/apache/tika/detect/XmlRootExtractor.java | 23 +-
.../apache/tika/detect/ZeroSizeFileDetector.java | 5 +-
.../java/org/apache/tika/detect/package-info.java | 4 +-
.../java/org/apache/tika/embedder/Embedder.java | 82 +-
.../org/apache/tika/embedder/ExternalEmbedder.java | 214 ++-
.../tika/exception/AccessPermissionException.java | 5 +-
.../tika/exception/CorruptedFileException.java | 4 +-
.../tika/exception/FileTooLongException.java | 9 +-
.../apache/tika/exception/RuntimeSAXException.java | 5 +-
.../apache/tika/exception/TikaConfigException.java | 5 +-
.../org/apache/tika/exception/TikaException.java | 5 +-
.../tika/exception/TikaMemoryLimitException.java | 9 +-
.../tika/exception/TikaTimeoutException.java | 4 +-
.../tika/exception/UnsupportedFormatException.java | 21 +-
.../tika/exception/WriteLimitReachedException.java | 16 +-
.../tika/exception/ZeroByteFileException.java | 22 +-
.../org/apache/tika/exception/package-info.java | 4 +-
.../AbstractEmbeddedDocumentBytesHandler.java | 37 +-
.../tika/extractor/BasicEmbeddedBytesSelector.java | 24 +-
.../BasicEmbeddedDocumentBytesHandler.java | 17 +-
.../apache/tika/extractor/ContainerExtractor.java | 47 +-
.../extractor/DefaultEmbeddedStreamTranslator.java | 18 +-
.../apache/tika/extractor/DocumentSelector.java | 17 +-
.../tika/extractor/EmbeddedBytesSelector.java | 1 +
.../EmbeddedDocumentByteStoreExtractorFactory.java | 19 +-
.../extractor/EmbeddedDocumentBytesHandler.java | 3 +-
.../tika/extractor/EmbeddedDocumentExtractor.java | 9 +-
.../EmbeddedDocumentExtractorFactory.java | 1 -
.../tika/extractor/EmbeddedDocumentUtil.java | 87 +-
.../tika/extractor/EmbeddedResourceHandler.java | 15 +-
.../tika/extractor/EmbeddedStreamTranslator.java | 10 +-
.../tika/extractor/ParserContainerExtractor.java | 33 +-
.../ParsingEmbeddedDocumentExtractor.java | 23 +-
.../ParsingEmbeddedDocumentExtractorFactory.java | 6 +-
.../apache/tika/extractor/RUnpackExtractor.java | 68 +-
.../tika/extractor/RUnpackExtractorFactory.java | 35 +-
.../org/apache/tika/extractor/package-info.java | 4 +-
.../org/apache/tika/fork/ClassLoaderProxy.java | 11 +-
.../org/apache/tika/fork/ClassLoaderResource.java | 24 +-
.../org/apache/tika/fork/ContentHandlerProxy.java | 10 +-
.../apache/tika/fork/ContentHandlerResource.java | 10 +-
.../main/java/org/apache/tika/fork/ForkClient.java | 101 +-
.../apache/tika/fork/ForkObjectInputStream.java | 41 +-
.../main/java/org/apache/tika/fork/ForkParser.java | 227 ++-
.../main/java/org/apache/tika/fork/ForkProxy.java | 1 -
.../java/org/apache/tika/fork/ForkResource.java | 1 -
.../main/java/org/apache/tika/fork/ForkServer.java | 76 +-
.../org/apache/tika/fork/InputStreamProxy.java | 5 +-
.../org/apache/tika/fork/InputStreamResource.java | 1 -
.../org/apache/tika/fork/MemoryURLConnection.java | 4 +-
.../apache/tika/fork/MemoryURLStreamHandler.java | 4 +-
.../tika/fork/MemoryURLStreamHandlerFactory.java | 1 -
.../apache/tika/fork/MemoryURLStreamRecord.java | 1 -
.../apache/tika/fork/MetadataContentHandler.java | 4 +-
.../org/apache/tika/fork/ParserFactoryFactory.java | 11 +-
.../fork/RecursiveMetadataContentHandlerProxy.java | 44 +-
.../RecursiveMetadataContentHandlerResource.java | 21 +-
.../java/org/apache/tika/fork/TimeoutLimits.java | 1 -
.../java/org/apache/tika/fork/package-info.java | 4 +-
.../org/apache/tika/io/BoundedInputStream.java | 29 +-
.../main/java/org/apache/tika/io/EndianUtils.java | 81 +-
.../java/org/apache/tika/io/FilenameUtils.java | 65 +-
.../src/main/java/org/apache/tika/io/IOUtils.java | 3 +-
.../org/apache/tika/io/InputStreamFactory.java | 15 +-
.../org/apache/tika/io/LookaheadInputStream.java | 37 +-
.../main/java/org/apache/tika/io/TailStream.java | 116 +-
.../org/apache/tika/io/TemporaryResources.java | 106 +-
.../java/org/apache/tika/io/TikaInputStream.java | 455 +++--
.../main/java/org/apache/tika/io/package-info.java | 4 +-
.../tika/language/detect/LanguageConfidence.java | 6 +-
.../tika/language/detect/LanguageDetector.java | 84 +-
.../tika/language/detect/LanguageHandler.java | 9 +-
.../apache/tika/language/detect/LanguageNames.java | 16 +-
.../tika/language/detect/LanguageResult.java | 15 +-
.../tika/language/detect/LanguageWriter.java | 19 +-
.../tika/language/translate/DefaultTranslator.java | 32 +-
.../tika/language/translate/EmptyTranslator.java | 5 +-
.../apache/tika/language/translate/Translator.java | 13 +-
.../apache/tika/metadata/AccessPermissions.java | 44 +-
.../org/apache/tika/metadata/ClimateForcast.java | 5 +-
.../org/apache/tika/metadata/CreativeCommons.java | 1 -
.../java/org/apache/tika/metadata/DublinCore.java | 220 ++-
.../main/java/org/apache/tika/metadata/Epub.java | 9 +-
.../org/apache/tika/metadata/ExternalProcess.java | 95 +-
.../java/org/apache/tika/metadata/FileSystem.java | 5 +-
.../main/java/org/apache/tika/metadata/Font.java | 40 +-
.../java/org/apache/tika/metadata/Geographic.java | 21 +-
.../main/java/org/apache/tika/metadata/HTML.java | 41 +-
.../java/org/apache/tika/metadata/HttpHeaders.java | 5 +-
.../main/java/org/apache/tika/metadata/IPTC.java | 1860 +++++++++++---------
.../org/apache/tika/metadata/MachineMetadata.java | 45 +-
.../java/org/apache/tika/metadata/Message.java | 57 +-
.../java/org/apache/tika/metadata/Metadata.java | 267 ++-
.../main/java/org/apache/tika/metadata/Office.java | 333 ++--
.../apache/tika/metadata/OfficeOpenXMLCore.java | 84 +-
.../tika/metadata/OfficeOpenXMLExtended.java | 92 +-
.../main/java/org/apache/tika/metadata/PDF.java | 119 +-
.../java/org/apache/tika/metadata/PagedText.java | 17 +-
.../java/org/apache/tika/metadata/Photoshop.java | 147 +-
.../java/org/apache/tika/metadata/Property.java | 118 +-
.../tika/metadata/PropertyTypeException.java | 16 +-
.../java/org/apache/tika/metadata/QuattroPro.java | 50 +-
.../java/org/apache/tika/metadata/RTFMetadata.java | 73 +-
.../main/java/org/apache/tika/metadata/TIFF.java | 93 +-
.../apache/tika/metadata/TikaCoreProperties.java | 287 +--
.../org/apache/tika/metadata/TikaMimeKeys.java | 5 +-
.../org/apache/tika/metadata/TikaPagedText.java | 13 +-
.../main/java/org/apache/tika/metadata/WARC.java | 2 +-
.../java/org/apache/tika/metadata/WordPerfect.java | 90 +-
.../main/java/org/apache/tika/metadata/XMP.java | 50 +-
.../main/java/org/apache/tika/metadata/XMPDM.java | 417 ++---
.../main/java/org/apache/tika/metadata/XMPIdq.java | 9 +-
.../main/java/org/apache/tika/metadata/XMPMM.java | 78 +-
.../java/org/apache/tika/metadata/XMPRights.java | 30 +-
.../filter/CaptureGroupMetadataFilter.java | 41 +-
.../metadata/filter/ClearByMimeMetadataFilter.java | 6 +-
.../metadata/filter/CompositeMetadataFilter.java | 1 -
.../filter/DateNormalizingMetadataFilter.java | 29 +-
.../metadata/filter/DefaultMetadataFilter.java | 4 +-
.../filter/ExcludeFieldMetadataFilter.java | 1 -
.../metadata/filter/FieldNameMappingFilter.java | 8 +-
.../metadata/filter/GeoPointMetadataFilter.java | 12 +-
.../filter/IncludeFieldMetadataFilter.java | 1 -
.../tika/metadata/filter/MetadataFilter.java | 17 +-
.../apache/tika/metadata/filter/NoOpFilter.java | 7 +-
.../org/apache/tika/metadata/package-info.java | 4 +-
.../metadata/writefilter/MetadataWriteFilter.java | 15 +-
.../metadata/writefilter/StandardWriteFilter.java | 189 +-
.../writefilter/StandardWriteFilterFactory.java | 32 +-
.../main/java/org/apache/tika/mime/AndClause.java | 1 -
.../src/main/java/org/apache/tika/mime/Clause.java | 13 +-
.../main/java/org/apache/tika/mime/HexCoDec.java | 28 +-
.../src/main/java/org/apache/tika/mime/Magic.java | 6 +-
.../main/java/org/apache/tika/mime/MagicMatch.java | 12 +-
.../main/java/org/apache/tika/mime/MediaType.java | 114 +-
.../org/apache/tika/mime/MediaTypeRegistry.java | 64 +-
.../main/java/org/apache/tika/mime/MimeType.java | 128 +-
.../org/apache/tika/mime/MimeTypeException.java | 10 +-
.../main/java/org/apache/tika/mime/MimeTypes.java | 240 ++-
.../org/apache/tika/mime/MimeTypesFactory.java | 78 +-
.../java/org/apache/tika/mime/MimeTypesReader.java | 81 +-
.../apache/tika/mime/MimeTypesReaderMetKeys.java | 4 +-
.../org/apache/tika/mime/MinShouldMatchClause.java | 7 +-
.../main/java/org/apache/tika/mime/OrClause.java | 1 -
.../main/java/org/apache/tika/mime/Patterns.java | 74 +-
.../mime/ProbabilisticMimeDetectionSelector.java | 64 +-
.../java/org/apache/tika/mime/package-info.java | 4 +-
.../main/java/org/apache/tika/package-info.java | 4 +-
.../parser/AbstractEncodingDetectorParser.java | 10 +-
.../tika/parser/AbstractExternalProcessParser.java | 24 +-
.../org/apache/tika/parser/AbstractParser.java | 30 +-
.../org/apache/tika/parser/AutoDetectParser.java | 120 +-
.../apache/tika/parser/AutoDetectParserConfig.java | 104 +-
.../tika/parser/AutoDetectParserFactory.java | 13 +-
.../org/apache/tika/parser/CompositeParser.java | 93 +-
.../java/org/apache/tika/parser/CryptoParser.java | 22 +-
.../java/org/apache/tika/parser/DefaultParser.java | 77 +-
.../org/apache/tika/parser/DelegatingParser.java | 42 +-
.../org/apache/tika/parser/DigestingParser.java | 50 +-
.../java/org/apache/tika/parser/EmptyParser.java | 25 +-
.../java/org/apache/tika/parser/ErrorParser.java | 19 +-
.../java/org/apache/tika/parser/NetworkParser.java | 55 +-
.../java/org/apache/tika/parser/ParseContext.java | 98 +-
.../java/org/apache/tika/parser/ParseRecord.java | 11 +-
.../main/java/org/apache/tika/parser/Parser.java | 42 +-
.../org/apache/tika/parser/ParserDecorator.java | 66 +-
.../java/org/apache/tika/parser/ParserFactory.java | 6 +-
.../apache/tika/parser/ParserPostProcessor.java | 22 +-
.../java/org/apache/tika/parser/ParsingReader.java | 170 +-
.../org/apache/tika/parser/PasswordProvider.java | 20 +-
.../apache/tika/parser/RecursiveParserWrapper.java | 184 +-
.../org/apache/tika/parser/RegexCaptureParser.java | 23 +-
.../org/apache/tika/parser/RenderingParser.java | 3 +-
.../org/apache/tika/parser/StatefulParser.java | 13 +-
.../tika/parser/digest/CompositeDigester.java | 2 -
.../tika/parser/digest/InputStreamDigester.java | 78 +-
.../parser/external/CompositeExternalParser.java | 8 +-
.../tika/parser/external/ExternalParser.java | 250 ++-
.../external/ExternalParsersConfigReader.java | 30 +-
.../ExternalParsersConfigReaderMetKeys.java | 4 +-
.../parser/external/ExternalParsersFactory.java | 9 +-
.../apache/tika/parser/external/package-info.java | 4 +-
.../tika/parser/external2/ExternalParser.java | 120 +-
.../parser/multiple/AbstractMultipleParser.java | 159 +-
.../tika/parser/multiple/FallbackParser.java | 41 +-
.../tika/parser/multiple/SupplementingParser.java | 54 +-
.../java/org/apache/tika/parser/package-info.java | 4 +-
.../apache/tika/pipes/CompositePipesReporter.java | 8 +-
.../tika/pipes/FailedToStartClientException.java | 4 +-
.../java/org/apache/tika/pipes/FetchEmitTuple.java | 86 +-
.../java/org/apache/tika/pipes/HandlerConfig.java | 70 +-
.../apache/tika/pipes/LoggingPipesReporter.java | 5 +-
.../java/org/apache/tika/pipes/PipesClient.java | 367 ++--
.../java/org/apache/tika/pipes/PipesConfig.java | 14 +-
.../org/apache/tika/pipes/PipesConfigBase.java | 34 +-
.../java/org/apache/tika/pipes/PipesException.java | 4 +-
.../java/org/apache/tika/pipes/PipesParser.java | 13 +-
.../java/org/apache/tika/pipes/PipesReporter.java | 71 +-
.../org/apache/tika/pipes/PipesReporterBase.java | 21 +-
.../java/org/apache/tika/pipes/PipesResult.java | 41 +-
.../java/org/apache/tika/pipes/PipesServer.java | 387 ++--
.../org/apache/tika/pipes/async/AsyncConfig.java | 13 +-
.../org/apache/tika/pipes/async/AsyncEmitter.java | 43 +-
.../apache/tika/pipes/async/AsyncProcessor.java | 188 +-
.../org/apache/tika/pipes/async/AsyncStatus.java | 29 +-
.../tika/pipes/async/OfferLargerThanQueueSize.java | 3 +-
.../apache/tika/pipes/emitter/AbstractEmitter.java | 6 +-
.../org/apache/tika/pipes/emitter/EmitData.java | 27 +-
.../org/apache/tika/pipes/emitter/EmitKey.java | 19 +-
.../org/apache/tika/pipes/emitter/Emitter.java | 5 +-
.../apache/tika/pipes/emitter/EmitterManager.java | 33 +-
.../apache/tika/pipes/emitter/EmptyEmitter.java | 9 +-
.../apache/tika/pipes/emitter/StreamEmitter.java | 1 -
.../extractor/EmbeddedDocumentBytesConfig.java | 36 +-
.../EmittingEmbeddedDocumentBytesHandler.java | 30 +-
.../apache/tika/pipes/fetcher/AbstractFetcher.java | 6 +-
.../apache/tika/pipes/fetcher/EmptyFetcher.java | 1 -
.../org/apache/tika/pipes/fetcher/FetchKey.java | 35 +-
.../org/apache/tika/pipes/fetcher/Fetcher.java | 10 +-
.../apache/tika/pipes/fetcher/FetcherManager.java | 31 +-
.../tika/pipes/fetcher/FetcherStringException.java | 4 +-
.../apache/tika/pipes/fetcher/RangeFetcher.java | 8 +-
.../tika/pipes/fetcher/fs/FileSystemFetcher.java | 61 +-
.../apache/tika/pipes/fetcher/url/UrlFetcher.java | 20 +-
.../pipes/pipesiterator/CallablePipesIterator.java | 72 +-
.../tika/pipes/pipesiterator/PipesIterator.java | 50 +-
.../tika/pipes/pipesiterator/TotalCounter.java | 23 +-
.../filelist/FileListPipesIterator.java | 43 +-
.../pipesiterator/fs/FileSystemPipesIterator.java | 61 +-
.../apache/tika/renderer/CompositeRenderer.java | 21 +-
.../tika/renderer/PageBasedRenderResults.java | 2 +-
.../org/apache/tika/renderer/PageRangeRequest.java | 4 +-
.../org/apache/tika/renderer/RenderRequest.java | 12 +-
.../org/apache/tika/renderer/RenderResult.java | 22 +-
.../org/apache/tika/renderer/RenderResults.java | 3 +-
.../java/org/apache/tika/renderer/Renderer.java | 16 +-
.../org/apache/tika/renderer/RenderingState.java | 9 +-
.../org/apache/tika/renderer/RenderingTracker.java | 9 +-
.../sax/AbstractRecursiveParserWrapperHandler.java | 49 +-
.../tika/sax/BasicContentHandlerFactory.java | 71 +-
.../org/apache/tika/sax/BodyContentHandler.java | 53 +-
.../java/org/apache/tika/sax/CleanPhoneText.java | 344 ++--
.../apache/tika/sax/ContentHandlerDecorator.java | 51 +-
.../tika/sax/ContentHandlerDecoratorFactory.java | 8 +-
.../org/apache/tika/sax/ContentHandlerFactory.java | 7 +-
.../org/apache/tika/sax/DIFContentHandler.java | 17 +-
.../tika/sax/ElementMappingContentHandler.java | 53 +-
.../apache/tika/sax/EmbeddedContentHandler.java | 30 +-
.../sax/EndDocumentShieldingContentHandler.java | 7 +-
.../tika/sax/ExpandedTitleContentHandler.java | 22 +-
.../src/main/java/org/apache/tika/sax/Link.java | 1 -
.../org/apache/tika/sax/LinkContentHandler.java | 36 +-
.../org/apache/tika/sax/OfflineContentHandler.java | 10 +-
.../tika/sax/PhoneExtractingContentHandler.java | 62 +-
.../tika/sax/RecursiveParserWrapperHandler.java | 62 +-
.../apache/tika/sax/RichTextContentHandler.java | 9 +-
.../org/apache/tika/sax/SafeContentHandler.java | 96 +-
.../org/apache/tika/sax/SecureContentHandler.java | 117 +-
.../org/apache/tika/sax/StandardOrganizations.java | 107 +-
.../org/apache/tika/sax/StandardReference.java | 20 +-
.../sax/StandardsExtractingContentHandler.java | 51 +-
.../java/org/apache/tika/sax/StandardsText.java | 94 +-
.../apache/tika/sax/StoppingEarlyException.java | 5 +-
.../org/apache/tika/sax/TaggedContentHandler.java | 32 +-
.../org/apache/tika/sax/TaggedSAXException.java | 17 +-
.../org/apache/tika/sax/TeeContentHandler.java | 5 +-
.../tika/sax/TextAndAttributeContentHandler.java | 4 +-
.../org/apache/tika/sax/TextContentHandler.java | 11 +-
.../org/apache/tika/sax/ToHTMLContentHandler.java | 29 +-
.../org/apache/tika/sax/ToTextContentHandler.java | 54 +-
.../org/apache/tika/sax/ToXMLContentHandler.java | 41 +-
.../java/org/apache/tika/sax/WriteLimiter.java | 1 +
.../apache/tika/sax/WriteOutContentHandler.java | 81 +-
.../org/apache/tika/sax/XHTMLContentHandler.java | 130 +-
.../org/apache/tika/sax/XMPContentHandler.java | 25 +-
.../java/org/apache/tika/sax/package-info.java | 4 +-
.../apache/tika/sax/xpath/AttributeMatcher.java | 5 +-
.../org/apache/tika/sax/xpath/ChildMatcher.java | 5 +-
.../apache/tika/sax/xpath/CompositeMatcher.java | 5 +-
.../org/apache/tika/sax/xpath/ElementMatcher.java | 5 +-
.../java/org/apache/tika/sax/xpath/Matcher.java | 32 +-
.../tika/sax/xpath/MatchingContentHandler.java | 17 +-
.../tika/sax/xpath/NamedAttributeMatcher.java | 4 +-
.../apache/tika/sax/xpath/NamedElementMatcher.java | 5 +-
.../org/apache/tika/sax/xpath/NodeMatcher.java | 5 +-
.../org/apache/tika/sax/xpath/SubtreeMatcher.java | 5 +-
.../org/apache/tika/sax/xpath/TextMatcher.java | 5 +-
.../org/apache/tika/sax/xpath/XPathParser.java | 50 +-
.../org/apache/tika/sax/xpath/package-info.java | 4 +-
.../org/apache/tika/utils/AnnotationUtils.java | 53 +-
.../java/org/apache/tika/utils/CharsetUtils.java | 61 +-
.../java/org/apache/tika/utils/CompareUtils.java | 7 +-
.../org/apache/tika/utils/ConcurrentUtils.java | 5 +-
.../main/java/org/apache/tika/utils/DateUtils.java | 74 +-
.../java/org/apache/tika/utils/ExceptionUtils.java | 25 +-
.../org/apache/tika/utils/FileProcessResult.java | 33 +-
.../java/org/apache/tika/utils/ParserUtils.java | 54 +-
.../java/org/apache/tika/utils/ProcessUtils.java | 47 +-
.../java/org/apache/tika/utils/RegexUtils.java | 17 +-
.../apache/tika/utils/RereadableInputStream.java | 130 +-
.../org/apache/tika/utils/ServiceLoaderUtils.java | 45 +-
.../java/org/apache/tika/utils/StreamGobbler.java | 6 +-
.../java/org/apache/tika/utils/StringUtils.java | 41 +-
.../java/org/apache/tika/utils/SystemUtils.java | 15 +-
.../java/org/apache/tika/utils/XMLReaderUtils.java | 432 +++--
.../java/org/apache/tika/utils/package-info.java | 4 +-
.../org/apache/custom/detect/MyCustomDetector.java | 1 -
.../org/apache/tika/MultiThreadedTikaTest.java | 254 +--
.../apache/tika/ResourceLoggingClassLoader.java | 6 +-
.../org/apache/tika/TestRereadableInputStream.java | 104 +-
.../java/org/apache/tika/TikaDetectionTest.java | 109 +-
.../src/test/java/org/apache/tika/TikaIT.java | 1 -
.../src/test/java/org/apache/tika/TikaTest.java | 275 +--
.../org/apache/tika/TypeDetectionBenchmark.java | 10 +-
.../apache/tika/config/AbstractTikaConfigTest.java | 12 +-
.../java/org/apache/tika/config/DummyExecutor.java | 1 -
.../java/org/apache/tika/config/DummyParser.java | 7 +-
.../org/apache/tika/config/MockConfigTest.java | 29 +-
.../java/org/apache/tika/config/ParamTest.java | 45 +-
.../tika/config/TikaConfigSerializerTest.java | 44 +-
.../org/apache/tika/config/TikaConfigTest.java | 119 +-
.../apache/tika/config/TikaPipesConfigTest.java | 93 +-
.../tika/detect/FileCommandDetectorTest.java | 34 +-
.../org/apache/tika/detect/MagicDetectorTest.java | 138 +-
.../tika/detect/MimeDetectionWithNNTest.java | 34 +-
.../org/apache/tika/detect/NameDetectorTest.java | 36 +-
.../org/apache/tika/detect/TextDetectorTest.java | 18 +-
.../org/apache/tika/detect/TypeDetectorTest.java | 10 +-
.../tika/detect/ZeroSizeFileDetectorTest.java | 7 +-
.../java/org/apache/tika/fork/ForkParserTest.java | 247 +--
.../apache/tika/fork/ForkParserTikaBinTest.java | 99 +-
.../java/org/apache/tika/fork/ForkTestParser.java | 25 +-
.../tika/fork/UpperCasingContentHandler.java | 2 -
.../fork/unusedpackage/ClassInUnusedPackage.java | 3 +-
.../java/org/apache/tika/io/EndianUtilsTest.java | 33 +-
.../java/org/apache/tika/io/FilenameUtilsTest.java | 23 +-
.../apache/tika/io/LookaheadInputStreamTest.java | 14 +-
.../java/org/apache/tika/io/TailStreamTest.java | 92 +-
.../org/apache/tika/io/TemporaryResourcesTest.java | 8 +-
.../org/apache/tika/io/TikaInputStreamTest.java | 67 +-
.../tika/language/detect/LanguageNamesTest.java | 1 -
.../org/apache/tika/metadata/TestMetadata.java | 96 +-
.../tika/metadata/filter/MockUpperCaseFilter.java | 5 +-
.../tika/metadata/filter/TestMetadataFilter.java | 12 +-
.../writefilter/StandardWriteFilterTest.java | 88 +-
.../org/apache/tika/mime/CustomReaderTest.java | 16 +-
.../java/org/apache/tika/mime/MediaTypeTest.java | 50 +-
.../org/apache/tika/mime/MimeDetectionTest.java | 143 +-
.../org/apache/tika/mime/MimeTypesReaderTest.java | 178 +-
.../java/org/apache/tika/mime/PatternsTest.java | 10 +-
.../tika/mime/ProbabilisticMimeDetectionTest.java | 131 +-
.../ProbabilisticMimeDetectionTestWithTika.java | 135 +-
.../org/apache/tika/mime/RFC822DetectionTest.java | 76 +-
.../tika/parser/AutoDetectParserConfigTest.java | 9 +-
.../apache/tika/parser/CompositeParserTest.java | 65 +-
.../tika/parser/DummyInitializableParser.java | 28 +-
.../tika/parser/DummyParameterizedParser.java | 39 +-
.../java/org/apache/tika/parser/DummyParser.java | 16 +-
.../tika/parser/InitializableParserTest.java | 4 +-
.../tika/parser/ParameterizedParserTest.java | 77 +-
.../apache/tika/parser/ParserDecoratorTest.java | 28 +-
.../apache/tika/parser/RegexCaptureParserTest.java | 18 +-
.../tika/parser/external2/ExternalParserTest.java | 41 +-
.../org/apache/tika/parser/mock/MockParser.java | 119 +-
.../apache/tika/parser/mock/MockParserFactory.java | 2 -
.../apache/tika/parser/mock/MockParserTest.java | 9 +-
.../org/apache/tika/parser/mock/VowelParser.java | 15 +-
.../tika/parser/multiple/MultipleParserTest.java | 61 +-
.../org/apache/tika/pipes/PipesServerTest.java | 166 +-
.../tika/pipes/async/AsyncChaosMonkeyTest.java | 162 +-
.../org/apache/tika/pipes/async/MockEmitter.java | 9 +-
.../org/apache/tika/pipes/async/MockFetcher.java | 11 +-
.../org/apache/tika/pipes/async/MockReporter.java | 9 +-
.../apache/tika/pipes/async/MockReporterTest.java | 12 +-
.../org/apache/tika/pipes/emitter/MockEmitter.java | 13 +-
.../org/apache/tika/pipes/fetcher/MockFetcher.java | 14 +-
.../pipes/fetcher/fs/FileSystemFetcherTest.java | 17 +-
.../pipesiterator/FileSystemPipesIteratorTest.java | 11 +-
.../filelist/FileListPipesIteratorTest.java | 4 +-
.../tika/sax/BasicContentHandlerFactoryTest.java | 66 +-
.../apache/tika/sax/BodyContentHandlerTest.java | 18 +-
.../apache/tika/sax/CustomErrorHandlerTest.java | 23 +-
.../apache/tika/sax/LinkContentHandlerTest.java | 20 +-
.../tika/sax/NonValidatingContentHandler.java | 10 +-
.../apache/tika/sax/OfflineContentHandlerTest.java | 12 +-
.../tika/sax/RichTextContentHandlerTest.java | 29 +-
.../apache/tika/sax/SafeContentHandlerTest.java | 5 +-
.../apache/tika/sax/SecureContentHandlerTest.java | 13 +-
.../java/org/apache/tika/sax/SerializerTest.java | 21 +-
.../apache/tika/sax/XHTMLContentHandlerTest.java | 27 +-
.../org/apache/tika/sax/xpath/XPathParserTest.java | 1 -
.../org/apache/tika/utils/AnnotationUtilsTest.java | 24 +-
.../org/apache/tika/utils/CharsetUtilsTest.java | 2 -
.../org/apache/tika/utils/ConcurrentUtilsTest.java | 35 +-
.../java/org/apache/tika/utils/RegexUtilsTest.java | 33 +-
.../apache/tika/utils/ServiceLoaderUtilsTest.java | 24 +-
.../org/apache/tika/utils/XMLReaderUtilsTest.java | 23 +-
tika-parent/checkstyle.xml | 102 --
tika-parent/pom.xml | 6 +-
438 files changed, 11398 insertions(+), 11476 deletions(-)
diff --git a/.mvn/jvm.config b/.mvn/jvm.config
new file mode 100644
index 000000000..e2a50e083
--- /dev/null
+++ b/.mvn/jvm.config
@@ -0,0 +1 @@
+--add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED
\ No newline at end of file
diff --git a/tika-core/pom.xml b/tika-core/pom.xml
index 8426ac55f..1fbef6228 100644
--- a/tika-core/pom.xml
+++ b/tika-core/pom.xml
@@ -34,6 +34,10 @@
<name>Apache Tika core</name>
<url>https://tika.apache.org/</url>
+ <properties>
+ <git-code-format-maven-plugin.version>5.3</git-code-format-maven-plugin.version>
+ </properties>
+
<dependencies>
<!-- See https://issues.apache.org/jira/browse/TIKA-2566 for more info -->
<dependency>
@@ -130,6 +134,46 @@
</execution>
</executions>
</plugin>
+ <plugin>
+ <groupId>com.cosium.code</groupId>
+ <artifactId>git-code-format-maven-plugin</artifactId>
+ <version>${git-code-format-maven-plugin.version}</version>
+ <executions>
+ <!-- On commit, format the modified java files -->
+ <execution>
+ <id>install-formatter-hook</id>
+ <goals>
+ <goal>install-hooks</goal>
+ </goals>
+ </execution>
+ <!-- On Maven verify phase, fail if any file (including
+ unmodified)
+ is badly formatted -->
+ <execution>
+ <id>validate-code-format</id>
+ <goals>
+ <goal>validate-code-format</goal>
+ </goals>
+ </execution>
+ </executions>
+ <dependencies>
+ <!-- Enable https://github.com/google/google-java-format -->
+ <dependency>
+ <groupId>com.cosium.code</groupId>
+ <artifactId>google-java-format</artifactId>
+ <version>${git-code-format-maven-plugin.version}</version>
+ </dependency>
+ </dependencies>
+ <configuration>
+ <formatterOptions>
+ <googleJavaFormat.aosp>true</googleJavaFormat.aosp>
+ <googleJavaFormat.fixImportsOnly>false</googleJavaFormat.fixImportsOnly>
+ <googleJavaFormat.skipSortingImports>false</googleJavaFormat.skipSortingImports>
+ <googleJavaFormat.skipRemovingUnusedImports>false</googleJavaFormat.skipRemovingUnusedImports>
+ </formatterOptions>
+ </configuration>
+ </plugin>
+
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
diff --git a/tika-core/src/main/java/org/apache/tika/Tika.java b/tika-core/src/main/java/org/apache/tika/Tika.java
index 22811f9c0..23f4769c5 100644
--- a/tika-core/src/main/java/org/apache/tika/Tika.java
+++ b/tika-core/src/main/java/org/apache/tika/Tika.java
@@ -24,9 +24,6 @@ import java.io.Reader;
import java.net.URL;
import java.nio.file.Path;
import java.util.Properties;
-
-import org.xml.sax.SAXException;
-
import org.apache.tika.config.TikaConfig;
import org.apache.tika.detect.Detector;
import org.apache.tika.exception.TikaException;
@@ -41,11 +38,12 @@ import org.apache.tika.parser.Parser;
import org.apache.tika.parser.ParsingReader;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.sax.WriteOutContentHandler;
+import org.xml.sax.SAXException;
/**
- * Facade class for accessing Tika functionality. This class hides much of
- * the underlying complexity of the lower level Tika classes and provides
- * simple methods for many common parsing and type detection operations.
+ * Facade class for accessing Tika functionality. This class hides much of the underlying complexity
+ * of the lower level Tika classes and provides simple methods for many common parsing and type
+ * detection operations.
*
* @see Parser
* @see Detector
@@ -53,25 +51,18 @@ import org.apache.tika.sax.WriteOutContentHandler;
*/
public class Tika {
- /**
- * The detector instance used by this facade.
- */
+ /** The detector instance used by this facade. */
private final Detector detector;
- /**
- * The parser instance used by this facade.
- */
+ /** The parser instance used by this facade. */
private final Parser parser;
- /**
- * The Translator instance used by this facade.
- */
+ /** The Translator instance used by this facade. */
private final Translator translator;
/**
- * Maximum length of the strings returned by the parseToString methods.
- * Used to prevent out of memory problems with huge input documents.
- * The default setting is 100k characters.
+ * Maximum length of the strings returned by the parseToString methods. Used to prevent out of
+ * memory problems with huge input documents. The default setting is 100k characters.
*/
private int maxStringLength = 100 * 1000;
@@ -80,7 +71,7 @@ public class Tika {
* Translator.
*
* @param detector type detector
- * @param parser document parser
+ * @param parser document parser
* @since Apache Tika 0.8
*/
public Tika(Detector detector, Parser parser) {
@@ -92,8 +83,8 @@ public class Tika {
/**
* Creates a Tika facade using the given detector, parser, and translator instances.
*
- * @param detector type detector
- * @param parser document parser
+ * @param detector type detector
+ * @param parser document parser
* @param translator text translator
* @since Apache Tika 1.6
*/
@@ -112,16 +103,14 @@ public class Tika {
this(config.getDetector(), new AutoDetectParser(config), config.getTranslator());
}
- /**
- * Creates a Tika facade using the default configuration.
- */
+ /** Creates a Tika facade using the default configuration. */
public Tika() {
this(TikaConfig.getDefaultConfig());
}
/**
- * Creates a Tika facade using the given detector instance, the
- * default parser configuration, and the default Translator.
+ * Creates a Tika facade using the given detector instance, the default parser configuration,
+ * and the default Translator.
*
* @param detector type detector
* @since Apache Tika 0.8
@@ -130,25 +119,21 @@ public class Tika {
this(detector, new AutoDetectParser(detector));
}
-
/**
- * Detects the media type of the given document. The type detection is
- * based on the content of the given document stream and any given
- * document metadata. The document stream can be <code>null</code>,
- * in which case only the given document metadata is used for type
- * detection.
- * <p>
- * If the document stream supports the
- * {@link InputStream#markSupported() mark feature}, then the stream is
- * marked and reset to the original position before this method returns.
- * Only a limited number of bytes are read from the stream.
- * <p>
- * The given document stream is <em>not</em> closed by this method.
- * <p>
- * Unlike in the {@link #parse(InputStream, Metadata)} method, the
- * given document metadata is <em>not</em> modified by this method.
+ * Detects the media type of the given document. The type detection is based on the content of
+ * the given document stream and any given document metadata. The document stream can be <code>
+ * null</code>, in which case only the given document metadata is used for type detection.
+ *
+ * <p>If the document stream supports the {@link InputStream#markSupported() mark feature}, then
+ * the stream is marked and reset to the original position before this method returns. Only a
+ * limited number of bytes are read from the stream.
*
- * @param stream the document stream, or <code>null</code>
+ * <p>The given document stream is <em>not</em> closed by this method.
+ *
+ * <p>Unlike in the {@link #parse(InputStream, Metadata)} method, the given document metadata is
+ * <em>not</em> modified by this method.
+ *
+ * @param stream the document stream, or <code>null</code>
* @param metadata document metadata
* @return detected media type
* @throws IOException if the stream can not be read
@@ -162,19 +147,17 @@ public class Tika {
}
/**
- * Detects the media type of the given document. The type detection is
- * based on the content of the given document stream and the name of the
- * document.
- * <p>
- * If the document stream supports the
- * {@link InputStream#markSupported() mark feature}, then the stream is
- * marked and reset to the original position before this method returns.
- * Only a limited number of bytes are read from the stream.
- * <p>
- * The given document stream is <em>not</em> closed by this method.
+ * Detects the media type of the given document. The type detection is based on the content of
+ * the given document stream and the name of the document.
+ *
+ * <p>If the document stream supports the {@link InputStream#markSupported() mark feature}, then
+ * the stream is marked and reset to the original position before this method returns. Only a
+ * limited number of bytes are read from the stream.
+ *
+ * <p>The given document stream is <em>not</em> closed by this method.
*
* @param stream the document stream
- * @param name document name
+ * @param name document name
* @return detected media type
* @throws IOException if the stream can not be read
* @since Apache Tika 0.9
@@ -186,15 +169,14 @@ public class Tika {
}
/**
- * Detects the media type of the given document. The type detection is
- * based on the content of the given document stream.
- * <p>
- * If the document stream supports the
- * {@link InputStream#markSupported() mark feature}, then the stream is
- * marked and reset to the original position before this method returns.
- * Only a limited number of bytes are read from the stream.
- * <p>
- * The given document stream is <em>not</em> closed by this method.
+ * Detects the media type of the given document. The type detection is based on the content of
+ * the given document stream.
+ *
+ * <p>If the document stream supports the {@link InputStream#markSupported() mark feature}, then
+ * the stream is marked and reset to the original position before this method returns. Only a
+ * limited number of bytes are read from the stream.
+ *
+ * <p>The given document stream is <em>not</em> closed by this method.
*
* @param stream the document stream
* @return detected media type
@@ -205,16 +187,15 @@ public class Tika {
}
/**
- * Detects the media type of the given document. The type detection is
- * based on the first few bytes of a document and the document name.
- * <p>
- * For best results at least a few kilobytes of the document data
- * are needed. See also the other detect() methods for better
- * alternatives when you have more than just the document prefix
- * available for type detection.
+ * Detects the media type of the given document. The type detection is based on the first few
+ * bytes of a document and the document name.
+ *
+ * <p>For best results at least a few kilobytes of the document data are needed. See also the
+ * other detect() methods for better alternatives when you have more than just the document
+ * prefix available for type detection.
*
* @param prefix first few bytes of the document
- * @param name document name
+ * @param name document name
* @return detected media type
* @since Apache Tika 0.9
*/
@@ -229,13 +210,12 @@ public class Tika {
}
/**
- * Detects the media type of the given document. The type detection is
- * based on the first few bytes of a document.
- * <p>
- * For best results at least a few kilobytes of the document data
- * are needed. See also the other detect() methods for better
- * alternatives when you have more than just the document prefix
- * available for type detection.
+ * Detects the media type of the given document. The type detection is based on the first few
+ * bytes of a document.
+ *
+ * <p>For best results at least a few kilobytes of the document data are needed. See also the
+ * other detect() methods for better alternatives when you have more than just the document
+ * prefix available for type detection.
*
* @param prefix first few bytes of the document
* @return detected media type
@@ -252,12 +232,11 @@ public class Tika {
}
/**
- * Detects the media type of the file at the given path. The type
- * detection is based on the document content and a potential known
- * file extension.
- * <p>
- * Use the {@link #detect(String)} method when you want to detect the
- * type of the document without actually accessing the file.
+ * Detects the media type of the file at the given path. The type detection is based on the
+ * document content and a potential known file extension.
+ *
+ * <p>Use the {@link #detect(String)} method when you want to detect the type of the document
+ * without actually accessing the file.
*
* @param path the path of the file
* @return detected media type
@@ -271,11 +250,11 @@ public class Tika {
}
/**
- * Detects the media type of the given file. The type detection is
- * based on the document content and a potential known file extension.
- * <p>
- * Use the {@link #detect(String)} method when you want to detect the
- * type of the document without actually accessing the file.
+ * Detects the media type of the given file. The type detection is based on the document content
+ * and a potential known file extension.
+ *
+ * <p>Use the {@link #detect(String)} method when you want to detect the type of the document
+ * without actually accessing the file.
*
* @param file the file
* @return detected media type
@@ -284,19 +263,18 @@ public class Tika {
*/
public String detect(File file) throws IOException {
Metadata metadata = new Metadata();
- try (@SuppressWarnings("deprecation") InputStream stream = TikaInputStream
- .get(file, metadata)) {
+ try (@SuppressWarnings("deprecation")
+ InputStream stream = TikaInputStream.get(file, metadata)) {
return detect(stream, metadata);
}
}
/**
- * Detects the media type of the resource at the given URL. The type
- * detection is based on the document content and a potential known
- * file extension included in the URL.
- * <p>
- * Use the {@link #detect(String)} method when you want to detect the
- * type of the document without actually accessing the URL.
+ * Detects the media type of the resource at the given URL. The type detection is based on the
+ * document content and a potential known file extension included in the URL.
+ *
+ * <p>Use the {@link #detect(String)} method when you want to detect the type of the document
+ * without actually accessing the URL.
*
* @param url the URL of the resource
* @return detected media type
@@ -310,11 +288,11 @@ public class Tika {
}
/**
- * Detects the media type of a document with the given file name.
- * The type detection is based on known file name extensions.
- * <p>
- * The given name can also be a URL or a full file path. In such cases
- * only the file name part of the string is used for type detection.
+ * Detects the media type of a document with the given file name. The type detection is based on
+ * known file name extensions.
+ *
+ * <p>The given name can also be a URL or a full file path. In such cases only the file name
+ * part of the string is used for type detection.
*
* @param name the file name of the document
* @return detected media type
@@ -330,11 +308,11 @@ public class Tika {
/**
* Translate the given text String to and from the given languages.
*
- * @param text The text to translate.
+ * @param text The text to translate.
* @param sourceLanguage The input text language (for example, "hi").
* @param targetLanguage The desired output language (for example, "fr").
- * @return The translated text. If translation is unavailable (client keys not set), returns
- * the same text back.
+ * @return The translated text. If translation is unavailable (client keys not set), returns the
+ * same text back.
* @see org.apache.tika.language.translate.Translator
*/
public String translate(String text, String sourceLanguage, String targetLanguage) {
@@ -346,13 +324,13 @@ public class Tika {
}
/**
- * Translate the given text String to the given language, attempting to auto-detect the
- * source language.
+ * Translate the given text String to the given language, attempting to auto-detect the source
+ * language.
*
- * @param text The text to translate.
+ * @param text The text to translate.
* @param targetLanguage The desired output language (for example, "en").
- * @return The translated text. If translation is unavailable (client keys not set), returns
- * the same text back.
+ * @return The translated text. If translation is unavailable (client keys not set), returns the
+ * same text back.
* @see org.apache.tika.language.translate.Translator
*/
public String translate(String text, String targetLanguage) {
@@ -363,18 +341,16 @@ public class Tika {
}
}
-
/**
- * Parses the given document and returns the extracted text content.
- * Input metadata like a file name or a content type hint can be passed
- * in the given metadata instance. Metadata information extracted from
- * the document is returned in that same metadata instance.
- * <p>
- * The returned reader will be responsible for closing the given stream.
- * The stream and any associated resources will be closed at or before
- * the time when the {@link Reader#close()} method is called.
- *
- * @param stream the document to be parsed
+ * Parses the given document and returns the extracted text content. Input metadata like a file
+ * name or a content type hint can be passed in the given metadata instance. Metadata
+ * information extracted from the document is returned in that same metadata instance.
+ *
+ * <p>The returned reader will be responsible for closing the given stream. The stream and any
+ * associated resources will be closed at or before the time when the {@link Reader#close()}
+ * method is called.
+ *
+ * @param stream the document to be parsed
* @param metadata where document's metadata will be populated
* @return extracted text content
* @throws IOException if the document can not be read or parsed
@@ -387,10 +363,10 @@ public class Tika {
/**
* Parses the given document and returns the extracted text content.
- * <p>
- * The returned reader will be responsible for closing the given stream.
- * The stream and any associated resources will be closed at or before
- * the time when the {@link Reader#close()} method is called.
+ *
+ * <p>The returned reader will be responsible for closing the given stream. The stream and any
+ * associated resources will be closed at or before the time when the {@link Reader#close()}
+ * method is called.
*
* @param stream the document to be parsed
* @return extracted text content
@@ -402,11 +378,11 @@ public class Tika {
/**
* Parses the file at the given path and returns the extracted text content.
- * <p>
- * Metadata information extracted from the document is returned in
- * the supplied metadata instance.
*
- * @param path the path of the file to be parsed
+ * <p>Metadata information extracted from the document is returned in the supplied metadata
+ * instance.
+ *
+ * @param path the path of the file to be parsed
* @param metadata where document's metadata will be populated
* @return extracted text content
* @throws IOException if the file can not be read or parsed
@@ -429,18 +405,19 @@ public class Tika {
/**
* Parses the given file and returns the extracted text content.
- * <p>
- * Metadata information extracted from the document is returned in
- * the supplied metadata instance.
*
- * @param file the file to be parsed
+ * <p>Metadata information extracted from the document is returned in the supplied metadata
+ * instance.
+ *
+ * @param file the file to be parsed
* @param metadata where document's metadata will be populated
* @return extracted text content
* @throws IOException if the file can not be read or parsed
* @see #parse(Path)
*/
public Reader parse(File file, Metadata metadata) throws IOException {
- @SuppressWarnings("deprecation") InputStream stream = TikaInputStream.get(file, metadata);
+ @SuppressWarnings("deprecation")
+ InputStream stream = TikaInputStream.get(file, metadata);
return parse(stream, metadata);
}
@@ -457,8 +434,7 @@ public class Tika {
}
/**
- * Parses the resource at the given URL and returns the extracted
- * text content.
+ * Parses the resource at the given URL and returns the extracted text content.
*
* @param url the URL of the resource to be parsed
* @return extracted text content
@@ -471,23 +447,21 @@ public class Tika {
}
/**
- * Parses the given document and returns the extracted text content.
- * The given input stream is closed by this method.
- * <p>
- * To avoid unpredictable excess memory use, the returned string contains
- * only up to {@link #getMaxStringLength()} first characters extracted
- * from the input document. Use the {@link #setMaxStringLength(int)}
- * method to adjust this limitation.
- * <p>
- * <strong>NOTE:</strong> Unlike most other Tika methods that take an
- * {@link InputStream}, this method will close the given stream for
- * you as a convenience. With other methods you are still responsible
- * for closing the stream or a wrapper instance returned by Tika.
- *
- * @param stream the document to be parsed
+ * Parses the given document and returns the extracted text content. The given input stream is
+ * closed by this method.
+ *
+ * <p>To avoid unpredictable excess memory use, the returned string contains only up to {@link
+ * #getMaxStringLength()} first characters extracted from the input document. Use the {@link
+ * #setMaxStringLength(int)} method to adjust this limitation.
+ *
+ * <p><strong>NOTE:</strong> Unlike most other Tika methods that take an {@link InputStream},
+ * this method will close the given stream for you as a convenience. With other methods you are
+ * still responsible for closing the stream or a wrapper instance returned by Tika.
+ *
+ * @param stream the document to be parsed
* @param metadata document metadata
* @return extracted text content
- * @throws IOException if the document can not be read
+ * @throws IOException if the document can not be read
* @throws TikaException if the document can not be parsed
*/
public String parseToString(InputStream stream, Metadata metadata)
@@ -496,24 +470,21 @@ public class Tika {
}
/**
- * Parses the given document and returns the extracted text content.
- * The given input stream is closed by this method. This method lets
- * you control the maxStringLength per call.
- * <p>
- * To avoid unpredictable excess memory use, the returned string contains
- * only up to maxLength (parameter) first characters extracted
- * from the input document.
- * <p>
- * <strong>NOTE:</strong> Unlike most other Tika methods that take an
- * {@link InputStream}, this method will close the given stream for
- * you as a convenience. With other methods you are still responsible
- * for closing the stream or a wrapper instance returned by Tika.
- *
- * @param stream the document to be parsed
- * @param metadata document metadata
+ * Parses the given document and returns the extracted text content. The given input stream is
+ * closed by this method. This method lets you control the maxStringLength per call.
+ *
+ * <p>To avoid unpredictable excess memory use, the returned string contains only up to
+ * maxLength (parameter) first characters extracted from the input document.
+ *
+ * <p><strong>NOTE:</strong> Unlike most other Tika methods that take an {@link InputStream},
+ * this method will close the given stream for you as a convenience. With other methods you are
+ * still responsible for closing the stream or a wrapper instance returned by Tika.
+ *
+ * @param stream the document to be parsed
+ * @param metadata document metadata
* @param maxLength maximum length of the returned string
* @return extracted text content
- * @throws IOException if the document can not be read
+ * @throws IOException if the document can not be read
* @throws TikaException if the document can not be parsed
*/
public String parseToString(InputStream stream, Metadata metadata, int maxLength)
@@ -535,22 +506,20 @@ public class Tika {
}
/**
- * Parses the given document and returns the extracted text content.
- * The given input stream is closed by this method.
- * <p>
- * To avoid unpredictable excess memory use, the returned string contains
- * only up to {@link #getMaxStringLength()} first characters extracted
- * from the input document. Use the {@link #setMaxStringLength(int)}
- * method to adjust this limitation.
- * <p>
- * <strong>NOTE:</strong> Unlike most other Tika methods that take an
- * {@link InputStream}, this method will close the given stream for
- * you as a convenience. With other methods you are still responsible
- * for closing the stream or a wrapper instance returned by Tika.
+ * Parses the given document and returns the extracted text content. The given input stream is
+ * closed by this method.
+ *
+ * <p>To avoid unpredictable excess memory use, the returned string contains only up to {@link
+ * #getMaxStringLength()} first characters extracted from the input document. Use the {@link
+ * #setMaxStringLength(int)} method to adjust this limitation.
+ *
+ * <p><strong>NOTE:</strong> Unlike most other Tika methods that take an {@link InputStream},
+ * this method will close the given stream for you as a convenience. With other methods you are
+ * still responsible for closing the stream or a wrapper instance returned by Tika.
*
* @param stream the document to be parsed
* @return extracted text content
- * @throws IOException if the document can not be read
+ * @throws IOException if the document can not be read
* @throws TikaException if the document can not be parsed
*/
public String parseToString(InputStream stream) throws IOException, TikaException {
@@ -559,15 +528,14 @@ public class Tika {
/**
* Parses the file at the given path and returns the extracted text content.
- * <p>
- * To avoid unpredictable excess memory use, the returned string contains
- * only up to {@link #getMaxStringLength()} first characters extracted
- * from the input document. Use the {@link #setMaxStringLength(int)}
- * method to adjust this limitation.
+ *
+ * <p>To avoid unpredictable excess memory use, the returned string contains only up to {@link
+ * #getMaxStringLength()} first characters extracted from the input document. Use the {@link
+ * #setMaxStringLength(int)} method to adjust this limitation.
*
* @param path the path of the file to be parsed
* @return extracted text content
- * @throws IOException if the file can not be read
+ * @throws IOException if the file can not be read
* @throws TikaException if the file can not be parsed
*/
public String parseToString(Path path) throws IOException, TikaException {
@@ -578,36 +546,34 @@ public class Tika {
/**
* Parses the given file and returns the extracted text content.
- * <p>
- * To avoid unpredictable excess memory use, the returned string contains
- * only up to {@link #getMaxStringLength()} first characters extracted
- * from the input document. Use the {@link #setMaxStringLength(int)}
- * method to adjust this limitation.
+ *
+ * <p>To avoid unpredictable excess memory use, the returned string contains only up to {@link
+ * #getMaxStringLength()} first characters extracted from the input document. Use the {@link
+ * #setMaxStringLength(int)} method to adjust this limitation.
*
* @param file the file to be parsed
* @return extracted text content
- * @throws IOException if the file can not be read
+ * @throws IOException if the file can not be read
* @throws TikaException if the file can not be parsed
* @see #parseToString(Path)
*/
public String parseToString(File file) throws IOException, TikaException {
Metadata metadata = new Metadata();
- @SuppressWarnings("deprecation") InputStream stream = TikaInputStream.get(file, metadata);
+ @SuppressWarnings("deprecation")
+ InputStream stream = TikaInputStream.get(file, metadata);
return parseToString(stream, metadata);
}
/**
- * Parses the resource at the given URL and returns the extracted
- * text content.
- * <p>
- * To avoid unpredictable excess memory use, the returned string contains
- * only up to {@link #getMaxStringLength()} first characters extracted
- * from the input document. Use the {@link #setMaxStringLength(int)}
- * method to adjust this limitation.
+ * Parses the resource at the given URL and returns the extracted text content.
+ *
+ * <p>To avoid unpredictable excess memory use, the returned string contains only up to {@link
+ * #getMaxStringLength()} first characters extracted from the input document. Use the {@link
+ * #setMaxStringLength(int)} method to adjust this limitation.
*
* @param url the URL of the resource to be parsed
* @return extracted text content
- * @throws IOException if the resource can not be read
+ * @throws IOException if the resource can not be read
* @throws TikaException if the resource can not be parsed
*/
public String parseToString(URL url) throws IOException, TikaException {
@@ -617,8 +583,7 @@ public class Tika {
}
/**
- * Returns the maximum length of strings returned by the
- * parseToString methods.
+ * Returns the maximum length of strings returned by the parseToString methods.
*
* @return maximum string length, or -1 if the limit has been disabled
* @since Apache Tika 0.7
@@ -628,11 +593,9 @@ public class Tika {
}
/**
- * Sets the maximum length of strings returned by the parseToString
- * methods.
+ * Sets the maximum length of strings returned by the parseToString methods.
*
- * @param maxStringLength maximum string length,
- * or -1 to disable this limit
+ * @param maxStringLength maximum string length, or -1 to disable this limit
* @since Apache Tika 0.7
*/
public void setMaxStringLength(int maxStringLength) {
@@ -669,7 +632,7 @@ public class Tika {
return translator;
}
- //--------------------------------------------------------------< Object >
+ // --------------------------------------------------------------< Object >
public String toString() {
return getString();
@@ -678,8 +641,9 @@ public class Tika {
public static String getString() {
String version = null;
- try (InputStream stream = Tika.class
- .getResourceAsStream("/META-INF/maven/org.apache.tika/tika-core/pom.properties")) {
+ try (InputStream stream =
+ Tika.class.getResourceAsStream(
+ "/META-INF/maven/org.apache.tika/tika-core/pom.properties")) {
if (stream != null) {
Properties properties = new Properties();
properties.load(stream);
@@ -694,5 +658,4 @@ public class Tika {
return "Apache Tika";
}
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/concurrent/ConfigurableThreadPoolExecutor.java b/tika-core/src/main/java/org/apache/tika/concurrent/ConfigurableThreadPoolExecutor.java
index 1f7c4a056..f3a5ffadf 100644
--- a/tika-core/src/main/java/org/apache/tika/concurrent/ConfigurableThreadPoolExecutor.java
+++ b/tika-core/src/main/java/org/apache/tika/concurrent/ConfigurableThreadPoolExecutor.java
@@ -24,9 +24,8 @@ import java.util.concurrent.ExecutorService;
* @since Apache Tika 1.11
*/
public interface ConfigurableThreadPoolExecutor extends ExecutorService {
-
+
public void setMaximumPoolSize(int threads);
-
- public void setCorePoolSize(int threads);
+ public void setCorePoolSize(int threads);
}
diff --git a/tika-core/src/main/java/org/apache/tika/concurrent/SimpleThreadPoolExecutor.java b/tika-core/src/main/java/org/apache/tika/concurrent/SimpleThreadPoolExecutor.java
index a4385e279..6a7ee32cf 100644
--- a/tika-core/src/main/java/org/apache/tika/concurrent/SimpleThreadPoolExecutor.java
+++ b/tika-core/src/main/java/org/apache/tika/concurrent/SimpleThreadPoolExecutor.java
@@ -25,11 +25,16 @@ import java.util.concurrent.TimeUnit;
*
* @since Apache Tika 1.11
*/
-public class SimpleThreadPoolExecutor extends ThreadPoolExecutor implements
- ConfigurableThreadPoolExecutor {
+public class SimpleThreadPoolExecutor extends ThreadPoolExecutor
+ implements ConfigurableThreadPoolExecutor {
public SimpleThreadPoolExecutor() {
- super(1, 2, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
+ super(
+ 1,
+ 2,
+ 0L,
+ TimeUnit.SECONDS,
+ new LinkedBlockingQueue<>(),
r -> new Thread(r, "Tika Executor Thread"));
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/config/ConfigBase.java b/tika-core/src/main/java/org/apache/tika/config/ConfigBase.java
index 405294fae..448f8820e 100644
--- a/tika-core/src/main/java/org/apache/tika/config/ConfigBase.java
+++ b/tika-core/src/main/java/org/apache/tika/config/ConfigBase.java
@@ -29,23 +29,21 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
-
+import org.apache.tika.exception.TikaConfigException;
+import org.apache.tika.exception.TikaException;
+import org.apache.tika.utils.XMLReaderUtils;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
-import org.apache.tika.exception.TikaConfigException;
-import org.apache.tika.exception.TikaException;
-import org.apache.tika.utils.XMLReaderUtils;
-
-
public abstract class ConfigBase {
private static Class[] SUPPORTED_PRIMITIVES =
- new Class[]{String.class, boolean.class, long.class, int.class, double.class,
- float.class};
+ new Class[] {
+ String.class, boolean.class, long.class, int.class, double.class, float.class
+ };
/**
* Use this to build a single class, where the user specifies the instance class, e.g.
@@ -81,8 +79,9 @@ public abstract class ConfigBase {
* @throws TikaConfigException
* @throws IOException
*/
- protected static <T> T buildSingle(String itemName, Class<T> itemClass, Element properties,
- T defaultValue) throws TikaConfigException, IOException {
+ protected static <T> T buildSingle(
+ String itemName, Class<T> itemClass, Element properties, T defaultValue)
+ throws TikaConfigException, IOException {
NodeList children = properties.getChildNodes();
T toConfigure = null;
@@ -110,10 +109,9 @@ public abstract class ConfigBase {
return toConfigure;
}
-
/**
- * Use this to build a list of components for a composite item (e.g.
- * CompositeMetadataFilter, FetcherManager), each with their own configurations
+ * Use this to build a list of components for a composite item (e.g. CompositeMetadataFilter,
+ * FetcherManager), each with their own configurations
*
* @param compositeElementName
* @param itemName
@@ -121,8 +119,12 @@ public abstract class ConfigBase {
* @throws TikaConfigException
* @throws IOException
*/
- protected static <P, T> P buildComposite(String compositeElementName, Class<P> compositeClass,
- String itemName, Class<T> itemClass, InputStream is)
+ protected static <P, T> P buildComposite(
+ String compositeElementName,
+ Class<P> compositeClass,
+ String itemName,
+ Class<T> itemClass,
+ InputStream is)
throws TikaConfigException, IOException {
Element properties = null;
try {
@@ -132,13 +134,16 @@ public abstract class ConfigBase {
} catch (TikaException e) {
throw new TikaConfigException("problem loading xml to dom", e);
}
- return buildComposite(compositeElementName, compositeClass, itemName, itemClass,
- properties);
+ return buildComposite(
+ compositeElementName, compositeClass, itemName, itemClass, properties);
}
- protected static <P, T> P buildComposite(String compositeElementName, Class<P> compositeClass,
- String itemName, Class<T> itemClass,
- Element properties)
+ protected static <P, T> P buildComposite(
+ String compositeElementName,
+ Class<P> compositeClass,
+ String itemName,
+ Class<T> itemClass,
+ Element properties)
throws TikaConfigException, IOException {
if (!properties.getLocalName().equals("properties")) {
@@ -159,8 +164,10 @@ public abstract class ConfigBase {
P composite = (P) constructor.newInstance(components);
setParams(composite, child, new HashSet<>(), itemName);
return composite;
- } catch (NoSuchMethodException | InvocationTargetException |
- InstantiationException | IllegalAccessException e) {
+ } catch (NoSuchMethodException
+ | InvocationTargetException
+ | InstantiationException
+ | IllegalAccessException e) {
throw new TikaConfigException("can't build composite class", e);
}
}
@@ -168,8 +175,8 @@ public abstract class ConfigBase {
throw new TikaConfigException("could not find " + compositeElementName);
}
- private static <T> List<T> loadComposite(Node composite, String itemName,
- Class<? extends T> itemClass)
+ private static <T> List<T> loadComposite(
+ Node composite, String itemName, Class<? extends T> itemClass)
throws TikaConfigException {
NodeList children = composite.getChildNodes();
List<T> items = new ArrayList<>();
@@ -199,14 +206,21 @@ public abstract class ConfigBase {
Class clazz = Class.forName(className);
if (!itemClass.isAssignableFrom(clazz)) {
throw new TikaConfigException(
- elementName + " with class name " + className + " must be of type '" +
- itemClass.getName() + "'");
+ elementName
+ + " with class name "
+ + className
+ + " must be of type '"
+ + itemClass.getName()
+ + "'");
}
return (T) clazz.getDeclaredConstructor().newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException |
- NoSuchMethodException | InvocationTargetException e) {
- throw new TikaConfigException("problem loading " + elementName +
- " with class " + itemClass.getName(), e);
+ } catch (InstantiationException
+ | IllegalAccessException
+ | ClassNotFoundException
+ | NoSuchMethodException
+ | InvocationTargetException e) {
+ throw new TikaConfigException(
+ "problem loading " + elementName + " with class " + itemClass.getName(), e);
}
}
@@ -215,8 +229,9 @@ public abstract class ConfigBase {
setParams(object, targetNode, settings, null);
}
- private static void setParams(Object object, Node targetNode, Set<String> settings,
- String exceptNodeName) throws TikaConfigException {
+ private static void setParams(
+ Object object, Node targetNode, Set<String> settings, String exceptNodeName)
+ throws TikaConfigException {
NodeList children = targetNode.getChildNodes();
List<Node> params = new ArrayList<>();
for (int i = 0; i < children.getLength(); i++) {
@@ -257,7 +272,7 @@ public abstract class ConfigBase {
if (isPrimitive(setterClassPair.itemClass)) {
tryToSetPrimitive(object, setterClassPair, param.getTextContent());
} else {
- //tryToSetPrimitive(object, localName, txt);
+ // tryToSetPrimitive(object, localName, txt);
Object item = buildClass(param, itemName, setterClassPair.itemClass);
setParams(setterClassPair.itemClass.cast(item), param, new HashSet<>());
try {
@@ -298,8 +313,8 @@ public abstract class ConfigBase {
private static SetterClassPair findSetterClassPair(Object object, String itemName)
throws TikaConfigException {
- //TODO -- we could do more with info from the node -- is it complex, does it have
- //a text value, does it have a class, etc... This works for now.
+ // TODO -- we could do more with info from the node -- is it complex, does it have
+ // a text value, does it have a class, etc... This works for now.
String setter =
"set" + itemName.substring(0, 1).toUpperCase(Locale.US) + itemName.substring(1);
Class itemClass = null;
@@ -308,7 +323,7 @@ public abstract class ConfigBase {
if (setter.equals(method.getName())) {
Class<?>[] classes = method.getParameterTypes();
if (classes.length == 1) {
- //if both setX(String) and setX(Object), prefer setX(String)
+ // if both setX(String) and setX(Object), prefer setX(String)
if (itemClass == null || classes[0].equals(String.class)) {
itemClass = classes[0];
setterMethod = method;
@@ -319,14 +334,14 @@ public abstract class ConfigBase {
if (setterMethod != null && itemClass != null) {
return new SetterClassPair(setterMethod, itemClass);
}
- //now try adders
+ // now try adders
String adder =
"add" + itemName.substring(0, 1).toUpperCase(Locale.US) + itemName.substring(1);
for (Method method : object.getClass().getMethods()) {
if (adder.equals(method.getName())) {
Class<?>[] classes = method.getParameterTypes();
if (classes.length == 1) {
- //if both setX(String) and setX(Object), prefer setX(String)
+ // if both setX(String) and setX(Object), prefer setX(String)
if (itemClass == null || classes[0].equals(String.class)) {
itemClass = classes[0];
setterMethod = method;
@@ -336,8 +351,14 @@ public abstract class ConfigBase {
}
if (setterMethod == null && itemClass == null) {
throw new TikaConfigException(
- "Couldn't find setter '" + setter + "' or adder '" + adder + "' for " + itemName +
- " of class: " + object.getClass());
+ "Couldn't find setter '"
+ + setter
+ + "' or adder '"
+ + adder
+ + "' for "
+ + itemName
+ + " of class: "
+ + object.getClass());
}
return new SetterClassPair(setterMethod, itemClass);
}
@@ -385,8 +406,10 @@ public abstract class ConfigBase {
Method m = object.getClass().getMethod(setter, List.class);
m.invoke(object, items);
- } catch (ClassNotFoundException | InvocationTargetException | NoSuchMethodException |
- IllegalAccessException e) {
+ } catch (ClassNotFoundException
+ | InvocationTargetException
+ | NoSuchMethodException
+ | IllegalAccessException e) {
throw new TikaConfigException("couldn't build class for " + name, e);
}
}
@@ -415,8 +438,8 @@ public abstract class ConfigBase {
private static void tryToSetMap(Object object, Node param) throws TikaConfigException {
String name = param.getLocalName();
- //only supports string, string at this point
- //use LinkedHashMap to keep insertion order!
+ // only supports string, string at this point
+ // use LinkedHashMap to keep insertion order!
Map<String, String> map = new LinkedHashMap<>();
NodeList nodeList = param.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
@@ -450,7 +473,6 @@ public abstract class ConfigBase {
}
map.put(key, value);
}
-
}
String setter = "set" + name.substring(0, 1).toUpperCase(Locale.US) + name.substring(1);
try {
@@ -467,11 +489,11 @@ public abstract class ConfigBase {
Node n = nodeList.item(i);
if (n.getNodeType() == 1) {
if (n.hasAttributes()) {
- if (n.getAttributes().getNamedItem("from") != null &&
- n.getAttributes().getNamedItem("to") != null) {
+ if (n.getAttributes().getNamedItem("from") != null
+ && n.getAttributes().getNamedItem("to") != null) {
return true;
- } else if (n.getAttributes().getNamedItem("k") != null &&
- n.getAttributes().getNamedItem("v") != null) {
+ } else if (n.getAttributes().getNamedItem("k") != null
+ && n.getAttributes().getNamedItem("v") != null) {
return true;
}
}
@@ -480,8 +502,9 @@ public abstract class ConfigBase {
return false;
}
- private static void tryToSetPrimitive(Object object, SetterClassPair setterClassPair,
- String value) throws TikaConfigException {
+ private static void tryToSetPrimitive(
+ Object object, SetterClassPair setterClassPair, String value)
+ throws TikaConfigException {
try {
if (setterClassPair.itemClass == int.class) {
setterClassPair.setterMethod.invoke(object, Integer.parseInt(value));
@@ -501,15 +524,13 @@ public abstract class ConfigBase {
}
}
-
/**
- * This should be overridden to do something with the settings
- * after loading the object.
+ * This should be overridden to do something with the settings after loading the object.
*
* @param settings
*/
protected void handleSettings(Set<String> settings) {
- //no-op
+ // no-op
}
/**
@@ -559,8 +580,12 @@ public abstract class ConfigBase {
@Override
public String toString() {
- return "SetterClassPair{" + "setterMethod=" + setterMethod + ", itemClass=" +
- itemClass + '}';
+ return "SetterClassPair{"
+ + "setterMethod="
+ + setterMethod
+ + ", itemClass="
+ + itemClass
+ + '}';
}
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/config/Field.java b/tika-core/src/main/java/org/apache/tika/config/Field.java
index 403ad6dcd..bd52e5bbd 100644
--- a/tika-core/src/main/java/org/apache/tika/config/Field.java
+++ b/tika-core/src/main/java/org/apache/tika/config/Field.java
@@ -23,9 +23,8 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
- * Field annotation is a contract for binding {@link Param} value from
- * Tika Configuration to an object.
- * services
+ * Field annotation is a contract for binding {@link Param} value from Tika Configuration to an
+ * object. services
*
* @since Apache Tika 1.14
*/
diff --git a/tika-core/src/main/java/org/apache/tika/config/Initializable.java b/tika-core/src/main/java/org/apache/tika/config/Initializable.java
index f37bdd909..df7a91d17 100644
--- a/tika-core/src/main/java/org/apache/tika/config/Initializable.java
+++ b/tika-core/src/main/java/org/apache/tika/config/Initializable.java
@@ -17,18 +17,16 @@
package org.apache.tika.config;
import java.util.Map;
-
import org.apache.tika.exception.TikaConfigException;
/**
- * Components that must do special processing across multiple fields
- * at initialization time should implement this interface.
- * <p>
- * TikaConfig will call initialize on Initializable classes after
- * setting the parameters for non-statically service loaded classes.
- * <p>
- * TikaConfig will call checkInitialization on all Initializables,
- * whether loaded statically
+ * Components that must do special processing across multiple fields at initialization time should
+ * implement this interface.
+ *
+ * <p>TikaConfig will call initialize on Initializable classes after setting the parameters for
+ * non-statically service loaded classes.
+ *
+ * <p>TikaConfig will call checkInitialization on all Initializables, whether loaded statically
*/
public interface Initializable {
@@ -38,15 +36,10 @@ public interface Initializable {
*/
void initialize(Map<String, Param> params) throws TikaConfigException;
-
/**
- * @param problemHandler if there is a problem and no
- * custom initializableProblemHandler has been configured
- * via Initializable parameters,
- * this is called to respond.
+ * @param problemHandler if there is a problem and no custom initializableProblemHandler has
+ * been configured via Initializable parameters, this is called to respond.
* @throws TikaConfigException
*/
void checkInitialization(InitializableProblemHandler problemHandler) throws TikaConfigException;
-
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/config/InitializableProblemHandler.java b/tika-core/src/main/java/org/apache/tika/config/InitializableProblemHandler.java
index fdca6901c..8f933f300 100644
--- a/tika-core/src/main/java/org/apache/tika/config/InitializableProblemHandler.java
+++ b/tika-core/src/main/java/org/apache/tika/config/InitializableProblemHandler.java
@@ -16,72 +16,71 @@
*/
package org.apache.tika.config;
-
-import org.slf4j.LoggerFactory;
-
import org.apache.tika.exception.TikaConfigException;
-
+import org.slf4j.LoggerFactory;
/**
- * This is to be used to handle potential recoverable problems that
- * might arise during initialization.
+ * This is to be used to handle potential recoverable problems that might arise during
+ * initialization.
*/
public interface InitializableProblemHandler {
+ /** Strategy that simply ignores all problems. */
+ InitializableProblemHandler IGNORE =
+ new InitializableProblemHandler() {
+ public void handleInitializableProblem(String className, String message) {}
- /**
- * Strategy that simply ignores all problems.
- */
- InitializableProblemHandler IGNORE = new InitializableProblemHandler() {
- public void handleInitializableProblem(String className, String message) {
- }
+ @Override
+ public String toString() {
+ return "IGNORE";
+ }
+ };
- @Override
- public String toString() {
- return "IGNORE";
- }
- };
/**
- * Strategy that logs warnings of all problems using a {@link org.slf4j.Logger}
- * created using the given class name.
+ * Strategy that logs warnings of all problems using a {@link org.slf4j.Logger} created using
+ * the given class name.
*/
- InitializableProblemHandler INFO = new InitializableProblemHandler() {
- public void handleInitializableProblem(String classname, String message) {
- LoggerFactory.getLogger(classname).info(message);
- }
+ InitializableProblemHandler INFO =
+ new InitializableProblemHandler() {
+ public void handleInitializableProblem(String classname, String message) {
+ LoggerFactory.getLogger(classname).info(message);
+ }
+
+ @Override
+ public String toString() {
+ return "INFO";
+ }
+ };
- @Override
- public String toString() {
- return "INFO";
- }
- };
/**
- * Strategy that logs warnings of all problems using a {@link org.slf4j.Logger}
- * created using the given class name.
+ * Strategy that logs warnings of all problems using a {@link org.slf4j.Logger} created using
+ * the given class name.
*/
- InitializableProblemHandler WARN = new InitializableProblemHandler() {
- public void handleInitializableProblem(String classname, String message) {
- LoggerFactory.getLogger(classname).warn(message);
- }
+ InitializableProblemHandler WARN =
+ new InitializableProblemHandler() {
+ public void handleInitializableProblem(String classname, String message) {
+ LoggerFactory.getLogger(classname).warn(message);
+ }
- @Override
- public String toString() {
- return "WARN";
- }
- };
- InitializableProblemHandler THROW = new InitializableProblemHandler() {
- public void handleInitializableProblem(String classname, String message)
- throws TikaConfigException {
- throw new TikaConfigException(message);
- }
+ @Override
+ public String toString() {
+ return "WARN";
+ }
+ };
- @Override
- public String toString() {
- return "THROW";
- }
- };
+ InitializableProblemHandler THROW =
+ new InitializableProblemHandler() {
+ public void handleInitializableProblem(String classname, String message)
+ throws TikaConfigException {
+ throw new TikaConfigException(message);
+ }
+
+ @Override
+ public String toString() {
+ return "THROW";
+ }
+ };
InitializableProblemHandler DEFAULT = WARN;
void handleInitializableProblem(String className, String message) throws TikaConfigException;
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/config/LoadErrorHandler.java b/tika-core/src/main/java/org/apache/tika/config/LoadErrorHandler.java
index 666c20d23..c134d0689 100644
--- a/tika-core/src/main/java/org/apache/tika/config/LoadErrorHandler.java
+++ b/tika-core/src/main/java/org/apache/tika/config/LoadErrorHandler.java
@@ -16,67 +16,65 @@
*/
package org.apache.tika.config;
-
import org.slf4j.LoggerFactory;
-
/**
- * Interface for error handling strategies in service class loading.
- * You can implement this interface for a custom error handling mechanism,
- * or use one of the predefined strategies.
+ * Interface for error handling strategies in service class loading. You can implement this
+ * interface for a custom error handling mechanism, or use one of the predefined strategies.
*
* @since Apache Tika 0.9
*/
public interface LoadErrorHandler {
- /**
- * Strategy that simply ignores all problems.
- */
- LoadErrorHandler IGNORE = new LoadErrorHandler() {
- public void handleLoadError(String classname, Throwable throwable) {
- }
+ /** Strategy that simply ignores all problems. */
+ LoadErrorHandler IGNORE =
+ new LoadErrorHandler() {
+ public void handleLoadError(String classname, Throwable throwable) {}
+
+ @Override
+ public String toString() {
+ return "IGNORE";
+ }
+ };
- @Override
- public String toString() {
- return "IGNORE";
- }
- };
/**
- * Strategy that logs warnings of all problems using a {@link org.slf4j.Logger}
- * created using the given class name.
+ * Strategy that logs warnings of all problems using a {@link org.slf4j.Logger} created using
+ * the given class name.
*/
- LoadErrorHandler WARN = new LoadErrorHandler() {
- public void handleLoadError(String classname, Throwable throwable) {
- LoggerFactory.getLogger(classname).warn("Unable to load {}", classname, throwable);
- }
+ LoadErrorHandler WARN =
+ new LoadErrorHandler() {
+ public void handleLoadError(String classname, Throwable throwable) {
+ LoggerFactory.getLogger(classname)
+ .warn("Unable to load {}", classname, throwable);
+ }
+
+ @Override
+ public String toString() {
+ return "WARN";
+ }
+ };
- @Override
- public String toString() {
- return "WARN";
- }
- };
/**
- * Strategy that throws a {@link RuntimeException} with the given
- * throwable as the root cause, thus interrupting the entire service
- * loading operation.
+ * Strategy that throws a {@link RuntimeException} with the given throwable as the root cause,
+ * thus interrupting the entire service loading operation.
*/
- LoadErrorHandler THROW = new LoadErrorHandler() {
- public void handleLoadError(String classname, Throwable throwable) {
- throw new RuntimeException("Unable to load " + classname, throwable);
- }
+ LoadErrorHandler THROW =
+ new LoadErrorHandler() {
+ public void handleLoadError(String classname, Throwable throwable) {
+ throw new RuntimeException("Unable to load " + classname, throwable);
+ }
- @Override
- public String toString() {
- return "THROW";
- }
- };
+ @Override
+ public String toString() {
+ return "THROW";
+ }
+ };
/**
- * Handles a problem encountered when trying to load the specified
- * service class. The implementation can log or otherwise process
- * the given error information. If the method returns normally, then
- * the service loader simply skips this class and continues with the
- * next one.
+ * Handles a problem encountered when trying to load the specified service class. The
+ * implementation can log or otherwise process the given error information. If the method
+ * returns normally, then the service loader simply skips this class and continues with the next
+ * one.
*
* @param classname name of the service class
* @param throwable the encountered problem
diff --git a/tika-core/src/main/java/org/apache/tika/config/Param.java b/tika-core/src/main/java/org/apache/tika/config/Param.java
index 25d367fe1..0ebbc4ad4 100644
--- a/tika-core/src/main/java/org/apache/tika/config/Param.java
+++ b/tika-core/src/main/java/org/apache/tika/config/Param.java
@@ -38,24 +38,20 @@ import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-
+import org.apache.tika.exception.TikaConfigException;
+import org.apache.tika.exception.TikaException;
+import org.apache.tika.parser.multiple.AbstractMultipleParser;
+import org.apache.tika.utils.XMLReaderUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
-import org.apache.tika.exception.TikaConfigException;
-import org.apache.tika.exception.TikaException;
-import org.apache.tika.parser.multiple.AbstractMultipleParser;
-import org.apache.tika.utils.XMLReaderUtils;
-
-
/**
* This is a serializable model class for parameters from configuration file.
*
- * @param <T> value type. Should be serializable to string and have a constructor
- * with string param
+ * @param <T> value type. Should be serializable to string and have a constructor with string param
* @since Apache Tika 1.14
*/
public class Param<T> implements Serializable {
@@ -88,7 +84,7 @@ public class Param<T> implements Serializable {
wellKnownMap.put("metadataPolicy", AbstractMultipleParser.MetadataPolicy.class);
}
- //one of these two is used for serialization
+ // one of these two is used for serialization
private final List<String> valueStrings = new ArrayList<>();
private final Map<String, String> valueMap = new LinkedHashMap<>();
@@ -96,8 +92,7 @@ public class Param<T> implements Serializable {
private String name;
private T actualValue;
- public Param() {
- }
+ public Param() {}
public Param(String name, Class<T> type, T value) {
this.name = name;
@@ -106,7 +101,7 @@ public class Param<T> implements Serializable {
if (List.class.isAssignableFrom(value.getClass())) {
this.valueStrings.addAll((List) value);
} else if (Map.class.isAssignableFrom(value.getClass())) {
- valueMap.putAll((Map)value);
+ valueMap.putAll((Map) value);
} else {
this.valueStrings.add(value.toString());
}
@@ -156,8 +151,8 @@ public class Param<T> implements Serializable {
String type = typeAttr.getTextContent();
if ("class".equals(type)) {
if (classAttr == null) {
- throw new TikaConfigException("must specify a class attribute if " +
- "type=\"class\"");
+ throw new TikaConfigException(
+ "must specify a class attribute if " + "type=\"class\"");
}
ret.setType(clazz);
} else {
@@ -180,7 +175,7 @@ public class Param<T> implements Serializable {
} else if (Map.class.isAssignableFrom(ret.type)) {
loadMap(ret, node);
} else {
- //allow the empty string
+ // allow the empty string
String textContent = "";
if (value != null) {
textContent = value.getTextContent();
@@ -190,12 +185,16 @@ public class Param<T> implements Serializable {
}
return ret;
}
- private static <T> void loadObject(Param<T> ret, Node root, Class clazz) throws TikaConfigException {
+
+ private static <T> void loadObject(Param<T> ret, Node root, Class clazz)
+ throws TikaConfigException {
try {
- ret.actualValue = (T)clazz.getDeclaredConstructor().newInstance();
- } catch (InstantiationException | IllegalAccessException | NoSuchMethodException |
- InvocationTargetException e) {
+ ret.actualValue = (T) clazz.getDeclaredConstructor().newInstance();
+ } catch (InstantiationException
+ | IllegalAccessException
+ | NoSuchMethodException
+ | InvocationTargetException e) {
throw new TikaConfigException("can't build class: " + clazz, e);
}
@@ -209,19 +208,23 @@ public class Param<T> implements Serializable {
Param param = load(params.item(j));
Method method = null;
- String methodName = "set" +
- param.getName().substring(0,1).toUpperCase(Locale.US) +
- param.getName().substring(1);
+ String methodName =
+ "set"
+ + param.getName().substring(0, 1).toUpperCase(Locale.US)
+ + param.getName().substring(1);
try {
- method = ret.actualValue.getClass().getMethod(methodName,
- param.getType());
+ method =
+ ret.actualValue
+ .getClass()
+ .getMethod(methodName, param.getType());
} catch (NoSuchMethodException e) {
throw new TikaConfigException("can't find method: " + methodName, e);
}
try {
method.invoke(ret.actualValue, param.getValue());
} catch (IllegalAccessException | InvocationTargetException e) {
- throw new TikaConfigException("can't set param value: " + param.getName(), e);
+ throw new TikaConfigException(
+ "can't set param value: " + param.getName(), e);
}
}
}
@@ -247,10 +250,10 @@ public class Param<T> implements Serializable {
key = child.getLocalName();
value = child.getTextContent();
}
- if (((Map)ret.actualValue).containsKey(key)) {
+ if (((Map) ret.actualValue).containsKey(key)) {
throw new TikaConfigException("Duplicate keys are not allowed: " + key);
}
- ((Map)ret.actualValue).put(key, value);
+ ((Map) ret.actualValue).put(key, value);
ret.valueMap.put(key, value);
}
child = child.getNextSibling();
@@ -293,8 +296,8 @@ public class Param<T> implements Serializable {
constructor.setAccessible(true);
return constructor.newInstance(value);
} catch (NoSuchMethodException e) {
- throw new RuntimeException(type + " doesnt have a constructor that takes String arg",
- e);
+ throw new RuntimeException(
+ type + " doesnt have a constructor that takes String arg", e);
} catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
throw new RuntimeException(e);
}
@@ -344,13 +347,20 @@ public class Param<T> implements Serializable {
@Override
public String toString() {
- return "Param{" + "name='" + name + '\'' + ", valueStrings='" + valueStrings + '\'' +
- ", actualValue=" + actualValue + '}';
+ return "Param{"
+ + "name='"
+ + name
+ + '\''
+ + ", valueStrings='"
+ + valueStrings
+ + '\''
+ + ", actualValue="
+ + actualValue
+ + '}';
}
public void save(OutputStream stream) throws TransformerException, TikaException {
-
DocumentBuilder builder = XMLReaderUtils.getDocumentBuilder();
Document doc = builder.newDocument();
Element paramEl = doc.createElement("param");
@@ -381,9 +391,9 @@ public class Param<T> implements Serializable {
el.appendChild(item);
}
} else if (Map.class.isAssignableFrom(actualValue.getClass())) {
- for (Object key : ((Map)actualValue).keySet()) {
+ for (Object key : ((Map) actualValue).keySet()) {
String keyString = (String) key;
- String valueString = (String)((Map)actualValue).get(keyString);
+ String valueString = (String) ((Map) actualValue).get(keyString);
Node item = doc.createElement(keyString);
item.setTextContent(valueString);
el.appendChild(item);
@@ -392,5 +402,4 @@ public class Param<T> implements Serializable {
el.setTextContent(valueStrings.get(0));
}
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/config/ParamField.java b/tika-core/src/main/java/org/apache/tika/config/ParamField.java
index 15e977ae6..8a9707b47 100644
--- a/tika-core/src/main/java/org/apache/tika/config/ParamField.java
+++ b/tika-core/src/main/java/org/apache/tika/config/ParamField.java
@@ -22,12 +22,11 @@ import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
-
import org.apache.tika.exception.TikaConfigException;
/**
- * This class stores metdata for {@link Field} annotation are used to map them
- * to {@link Param} at runtime
+ * This class stores metdata for {@link Field} annotation are used to map them to {@link Param} at
+ * runtime
*
* @since Apache Tika 1.14
*/
@@ -35,18 +34,20 @@ public class ParamField {
public static final String DEFAULT = "#default";
- //NOTE: since (primitive type) is NOT AssignableFrom (BoxedType),
+ // NOTE: since (primitive type) is NOT AssignableFrom (BoxedType),
// we just use boxed type for everything!
// Example : short.class.isAssignableFrom(Short.class) ? false
private static final Map<Class<?>, Class<?>> PRIMITIVE_MAP =
- new HashMap<Class<?>, Class<?>>() {{
+ new HashMap<Class<?>, Class<?>>() {
+ {
put(int.class, Integer.class);
put(short.class, Short.class);
put(boolean.class, Boolean.class);
put(long.class, Long.class);
put(float.class, Float.class);
put(double.class, Double.class);
- }};
+ }
+ };
private final String name;
private final Class<?> type;
private final boolean required;
@@ -94,9 +95,9 @@ public class ParamField {
/**
* Sets given value to the annotated field of bean
*
- * @param bean bean with annotation for field
+ * @param bean bean with annotation for field
* @param value value of field
- * @throws IllegalAccessException when it occurs
+ * @throws IllegalAccessException when it occurs
* @throws InvocationTargetException when it occurs
*/
public void assignValue(Object bean, Object value)
@@ -117,15 +118,17 @@ public class ParamField {
if (params.length != 1) {
String msg = "Invalid setter method. Must have one and only one parameter. ";
if (setter.getName().startsWith("get")) {
- msg += "Perhaps the annotation is misplaced on " + setter.getName() +
- " while a set'X' is expected?";
+ msg +=
+ "Perhaps the annotation is misplaced on "
+ + setter.getName()
+ + " while a set'X' is expected?";
}
throw new TikaConfigException(msg);
}
type = params[0];
}
if (type.isPrimitive() && PRIMITIVE_MAP.containsKey(type)) {
- type = PRIMITIVE_MAP.get(type); //primitive types have hard time
+ type = PRIMITIVE_MAP.get(type); // primitive types have hard time
}
return type;
}
@@ -138,8 +141,9 @@ public class ParamField {
} else {
String setterName = setter.getName();
if (setterName.startsWith("set") && setterName.length() > 3) {
- name = setterName.substring(3, 4).toLowerCase(Locale.ROOT) +
- setterName.substring(4);
+ name =
+ setterName.substring(3, 4).toLowerCase(Locale.ROOT)
+ + setterName.substring(4);
} else {
name = setter.getName();
}
@@ -152,7 +156,14 @@ public class ParamField {
@Override
public String toString() {
- return "ParamField{" + "name='" + name + '\'' + ", type=" + type + ", required=" +
- required + '}';
+ return "ParamField{"
+ + "name='"
+ + name
+ + '\''
+ + ", type="
+ + type
+ + ", required="
+ + required
+ + '}';
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/config/ServiceLoader.java b/tika-core/src/main/java/org/apache/tika/config/ServiceLoader.java
index acc53ca88..32e624ba2 100644
--- a/tika-core/src/main/java/org/apache/tika/config/ServiceLoader.java
+++ b/tika-core/src/main/java/org/apache/tika/config/ServiceLoader.java
@@ -33,7 +33,6 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
-
import org.apache.tika.exception.TikaConfigException;
import org.apache.tika.utils.ServiceLoaderUtils;
@@ -45,32 +44,37 @@ import org.apache.tika.utils.ServiceLoaderUtils;
public class ServiceLoader {
/**
- * The dynamic set of services available in an OSGi environment.
- * Managed by the {@link TikaActivator} class and used as an additional
- * source of service instances in the {@link #loadServiceProviders(Class)}
- * method.
+ * The dynamic set of services available in an OSGi environment. Managed by the {@link
+ * TikaActivator} class and used as an additional source of service instances in the {@link
+ * #loadServiceProviders(Class)} method.
*/
private static final Map<Object, RankedService> SERVICES = new HashMap<>();
+
private static final Pattern COMMENT = Pattern.compile("#.*");
private static final Pattern WHITESPACE = Pattern.compile("\\s+");
+
/**
- * The default context class loader to use for all threads, or
- * <code>null</code> to automatically select the context class loader.
+ * The default context class loader to use for all threads, or <code>null</code> to
+ * automatically select the context class loader.
*/
private static volatile ClassLoader CONTEXT_CLASS_LOADER = null;
+
private final ClassLoader loader;
private final LoadErrorHandler handler;
private final InitializableProblemHandler initializableProblemHandler;
private final boolean dynamic;
- public ServiceLoader(ClassLoader loader, LoadErrorHandler handler,
- InitializableProblemHandler initializableProblemHandler, boolean dynamic) {
+ public ServiceLoader(
+ ClassLoader loader,
+ LoadErrorHandler handler,
+ InitializableProblemHandler initializableProblemHandler,
+ boolean dynamic) {
this.loader = loader;
this.handler = handler;
this.initializableProblemHandler = initializableProblemHandler;
this.dynamic = dynamic;
-
}
+
public ServiceLoader(ClassLoader loader, LoadErrorHandler handler, boolean dynamic) {
this(loader, handler, InitializableProblemHandler.WARN, dynamic);
}
@@ -80,24 +84,27 @@ public class ServiceLoader {
}
public ServiceLoader(ClassLoader loader) {
- this(loader,
- Boolean.getBoolean("org.apache.tika.service.error.warn") ? LoadErrorHandler.WARN :
- LoadErrorHandler.IGNORE);
+ this(
+ loader,
+ Boolean.getBoolean("org.apache.tika.service.error.warn")
+ ? LoadErrorHandler.WARN
+ : LoadErrorHandler.IGNORE);
}
public ServiceLoader() {
- this(getContextClassLoader(),
- Boolean.getBoolean("org.apache.tika.service.error.warn") ? LoadErrorHandler.WARN :
- LoadErrorHandler.IGNORE, true);
+ this(
+ getContextClassLoader(),
+ Boolean.getBoolean("org.apache.tika.service.error.warn")
+ ? LoadErrorHandler.WARN
+ : LoadErrorHandler.IGNORE,
+ true);
}
/**
- * Returns the context class loader of the current thread. If such
- * a class loader is not available, then the loader of this class or
- * finally the system class loader is returned.
+ * Returns the context class loader of the current thread. If such a class loader is not
+ * available, then the loader of this class or finally the system class loader is returned.
*
- * @return context class loader, or <code>null</code> if no loader
- * is available
+ * @return context class loader, or <code>null</code> if no loader is available
* @see <a href="https://issues.apache.org/jira/browse/TIKA-441">TIKA-441</a>
*/
static ClassLoader getContextClassLoader() {
@@ -112,12 +119,11 @@ public class ServiceLoader {
}
/**
- * Sets the context class loader to use for all threads that access
- * this class. Used for example in an OSGi environment to avoid problems
- * with the default context class loader.
+ * Sets the context class loader to use for all threads that access this class. Used for example
+ * in an OSGi environment to avoid problems with the default context class loader.
*
- * @param loader default context class loader,
- * or <code>null</code> to automatically pick the loader
+ * @param loader default context class loader, or <code>null</code> to automatically pick the
+ * loader
*/
public static void setContextClassLoader(ClassLoader loader) {
CONTEXT_CLASS_LOADER = loader;
@@ -166,8 +172,7 @@ public class ServiceLoader {
}
/**
- * Returns an input stream for reading the specified resource from the
- * configured class loader.
+ * Returns an input stream for reading the specified resource from the configured class loader.
*
* @param name resource name
* @return input stream, or <code>null</code> if the resource was not found
@@ -192,18 +197,16 @@ public class ServiceLoader {
}
/**
- * Loads and returns the named service class that's expected to implement
- * the given interface.
- * <p>
- * Note that this class does not use the {@link LoadErrorHandler}, a
- * {@link ClassNotFoundException} is always returned for unknown
- * classes or classes of the wrong type
+ * Loads and returns the named service class that's expected to implement the given interface.
+ *
+ * <p>Note that this class does not use the {@link LoadErrorHandler}, a {@link
+ * ClassNotFoundException} is always returned for unknown classes or classes of the wrong type
*
* @param iface service interface
- * @param name service class name
+ * @param name service class name
* @return service class
- * @throws ClassNotFoundException if the service class can not be found
- * or does not implement the given interface
+ * @throws ClassNotFoundException if the service class can not be found or does not implement
+ * the given interface
* @see Class#forName(String, boolean, ClassLoader)
* @since Apache Tika 1.1
*/
@@ -225,10 +228,8 @@ public class ServiceLoader {
}
/**
- * Returns all the available service resources matching the
- * given pattern, such as all instances of tika-mimetypes.xml
- * on the classpath, or all org.apache.tika.parser.Parser
- * service files.
+ * Returns all the available service resources matching the given pattern, such as all instances
+ * of tika-mimetypes.xml on the classpath, or all org.apache.tika.parser.Parser service files.
*/
public Enumeration<URL> findServiceResources(String filePattern) {
try {
@@ -243,7 +244,7 @@ public class ServiceLoader {
/**
* Returns all the available service providers of the given type.
*
- * As of versions after 2.4.1, this removes duplicate classes
+ * <p>As of versions after 2.4.1, this removes duplicate classes
*
* @param iface service provider interface
* @return available service providers
@@ -256,7 +257,7 @@ public class ServiceLoader {
List<T> providers = new ArrayList<>();
Set<String> seen = new HashSet<>();
for (T provider : tmp) {
- if (! seen.contains(provider.getClass().getCanonicalName())) {
+ if (!seen.contains(provider.getClass().getCanonicalName())) {
providers.add(provider);
seen.add(provider.getClass().getCanonicalName());
}
@@ -265,9 +266,8 @@ public class ServiceLoader {
}
/**
- * Returns the available dynamic service providers of the given type.
- * The returned list is newly allocated and may be freely modified
- * by the caller.
+ * Returns the available dynamic service providers of the given type. The returned list is newly
+ * allocated and may be freely modified by the caller.
*
* @param iface service provider interface
* @return dynamic service providers
@@ -294,10 +294,9 @@ public class ServiceLoader {
}
/**
- * Returns the defined static service providers of the given type, without
- * attempting to load them.
- * The providers are loaded using the service provider mechanism using
- * the configured class loader (if any).
+ * Returns the defined static service providers of the given type, without attempting to load
+ * them. The providers are loaded using the service provider mechanism using the configured
+ * class loader (if any).
*
* @param iface service provider interface
* @return static list of uninitialised service providers
@@ -326,19 +325,18 @@ public class ServiceLoader {
}
/**
- * Returns the available static service providers of the given type.
- * The providers are loaded using the service provider mechanism using
- * the configured class loader (if any). The returned list is newly
- * allocated and may be freely modified by the caller.
+ * Returns the available static service providers of the given type. The providers are loaded
+ * using the service provider mechanism using the configured class loader (if any). The returned
+ * list is newly allocated and may be freely modified by the caller.
*
- * @param iface service provider interface
+ * @param iface service provider interface
* @param excludes -- do not load these classes
* @return static service providers
* @since Apache Tika 1.2
*/
@SuppressWarnings("unchecked")
- public <T> List<T> loadStaticServiceProviders(Class<T> iface,
- Collection<Class<? extends T>> excludes) {
+ public <T> List<T> loadStaticServiceProviders(
+ Class<T> iface, Collection<Class<? extends T>> excludes) {
List<T> providers = new ArrayList<>();
if (loader != null) {
@@ -407,7 +405,5 @@ public class ServiceLoader {
public int compareTo(RankedService that) {
return that.rank - rank; // highest number first
}
-
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/config/TikaActivator.java b/tika-core/src/main/java/org/apache/tika/config/TikaActivator.java
index e076f1c2d..54e05ce54 100644
--- a/tika-core/src/main/java/org/apache/tika/config/TikaActivator.java
+++ b/tika-core/src/main/java/org/apache/tika/config/TikaActivator.java
@@ -16,6 +16,8 @@
*/
package org.apache.tika.config;
+import org.apache.tika.detect.Detector;
+import org.apache.tika.parser.Parser;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
@@ -23,17 +25,13 @@ import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
-import org.apache.tika.detect.Detector;
-import org.apache.tika.parser.Parser;
-
/**
- * Bundle activator that adjust the class loading mechanism of the
- * {@link ServiceLoader} class to work correctly in an OSGi environment.
- * <p>
- * Note that you should <strong>not</strong> access this class directly.
- * Instead the OSGi environment (if present) will automatically invoke the
- * methods of this class based on the Bundle-Activator setting in the bundle
- * manifest.
+ * Bundle activator that adjust the class loading mechanism of the {@link ServiceLoader} class to
+ * work correctly in an OSGi environment.
+ *
+ * <p>Note that you should <strong>not</strong> access this class directly. Instead the OSGi
+ * environment (if present) will automatically invoke the methods of this class based on the
+ * Bundle-Activator setting in the bundle manifest.
*
* @since Apache Tika 0.9
*/
@@ -44,7 +42,8 @@ public class TikaActivator implements BundleActivator, ServiceTrackerCustomizer
private ServiceTracker parserTracker;
private BundleContext bundleContext;
- //-----------------------------------------------------< BundleActivator >
+
+ // -----------------------------------------------------< BundleActivator >
public void start(final BundleContext context) throws Exception {
bundleContext = context;
@@ -73,12 +72,10 @@ public class TikaActivator implements BundleActivator, ServiceTrackerCustomizer
return service;
}
- public void modifiedService(ServiceReference reference, Object service) {
- }
+ public void modifiedService(ServiceReference reference, Object service) {}
public void removedService(ServiceReference reference, Object service) {
ServiceLoader.removeService(reference);
bundleContext.ungetService(reference);
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/config/TikaConfig.java b/tika-core/src/main/java/org/apache/tika/config/TikaConfig.java
index e68ad10d6..7fe261430 100644
--- a/tika-core/src/main/java/org/apache/tika/config/TikaConfig.java
+++ b/tika-core/src/main/java/org/apache/tika/config/TikaConfig.java
@@ -39,15 +39,6 @@ import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import javax.imageio.spi.ServiceRegistry;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-
import org.apache.tika.concurrent.ConfigurableThreadPoolExecutor;
import org.apache.tika.concurrent.SimpleThreadPoolExecutor;
import org.apache.tika.detect.CompositeDetector;
@@ -81,16 +72,21 @@ import org.apache.tika.renderer.Renderer;
import org.apache.tika.utils.AnnotationUtils;
import org.apache.tika.utils.StringUtils;
import org.apache.tika.utils.XMLReaderUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+import org.xml.sax.SAXException;
-/**
- * Parse xml config file.
- */
+/** Parse xml config file. */
public class TikaConfig {
- public static int DEFAULT_MAX_JSON_STRING_FIELD_LENGTH = 20_000_000;//jackson's default
+ public static int DEFAULT_MAX_JSON_STRING_FIELD_LENGTH = 20_000_000; // jackson's default
public static String MAX_JSON_STRING_FIELD_LENGTH_ELEMENT_NAME = "maxJsonStringFieldLength";
- //use this to look for unneeded instantiations of TikaConfig
+ // use this to look for unneeded instantiations of TikaConfig
protected static final AtomicInteger TIMES_INSTANTIATED = new AtomicInteger();
private static final Logger LOG = LoggerFactory.getLogger(TikaConfig.class);
@@ -124,13 +120,16 @@ public class TikaConfig {
public TikaConfig(File file) throws TikaException, IOException, SAXException {
this(XMLReaderUtils.buildDOM(file.toPath()));
}
+
public TikaConfig(File file, ServiceLoader loader)
throws TikaException, IOException, SAXException {
this(XMLReaderUtils.buildDOM(file.toPath()), loader);
}
+
public TikaConfig(URL url) throws TikaException, IOException, SAXException {
this(url, ServiceLoader.getContextClassLoader());
}
+
public TikaConfig(URL url, ClassLoader loader) throws TikaException, IOException, SAXException {
this(XMLReaderUtils.buildDOM(url.toString()).getDocumentElement(), loader);
}
@@ -184,15 +183,14 @@ public class TikaConfig {
}
/**
- * Creates a Tika configuration from the built-in media type rules
- * and all the {@link Parser} implementations available through the
- * {@link ServiceRegistry service provider mechanism} in the given
- * class loader.
+ * Creates a Tika configuration from the built-in media type rules and all the {@link Parser}
+ * implementations available through the {@link ServiceRegistry service provider mechanism} in
+ * the given class loader.
*
- * @param loader the class loader through which parser implementations
- * are loaded, or <code>null</code> for no parsers
+ * @param loader the class loader through which parser implementations are loaded, or <code>null
+ * </code> for no parsers
* @throws MimeTypeException if the built-in media type rules are broken
- * @throws IOException if the built-in media type rules can not be read
+ * @throws IOException if the built-in media type rules can not be read
* @since Apache Tika 0.8
*/
public TikaConfig(ClassLoader loader) throws MimeTypeException, IOException {
@@ -210,20 +208,21 @@ public class TikaConfig {
}
/**
- * Creates a default Tika configuration.
- * First checks whether an XML config file is specified, either in
+ * Creates a default Tika configuration. First checks whether an XML config file is specified,
+ * either in
+ *
* <ol>
- * <li>System property "tika.config", or</li>
- * <li>Environment variable TIKA_CONFIG</li>
+ * <li>System property "tika.config", or
+ * <li>Environment variable TIKA_CONFIG
* </ol>
- * <p>If one of these have a value, try to resolve it relative to file
- * system or classpath.</p>
- * <p>If XML config is not specified, initialize from the built-in media
- * type rules and all the {@link Parser} implementations available through
- * the {@link ServiceRegistry service provider mechanism} in the context
- * class loader of the current thread.</p>
*
- * @throws IOException if the configuration can not be read
+ * <p>If one of these have a value, try to resolve it relative to file system or classpath.
+ *
+ * <p>If XML config is not specified, initialize from the built-in media type rules and all the
+ * {@link Parser} implementations available through the {@link ServiceRegistry service provider
+ * mechanism} in the context class loader of the current thread.
+ *
+ * @throws IOException if the configuration can not be read
* @throws TikaException if problem with MimeTypes or parsing XML config
*/
public TikaConfig() throws TikaException, IOException {
@@ -281,17 +280,16 @@ public class TikaConfig {
this.autoDetectParserConfig = AutoDetectParserConfig.load(element);
setMaxJsonStringFieldLength(element);
} catch (SAXException e) {
- throw new TikaException("Specified Tika configuration has syntax errors: " + config,
- e);
+ throw new TikaException(
+ "Specified Tika configuration has syntax errors: " + config, e);
}
}
TIMES_INSTANTIATED.incrementAndGet();
}
/**
- *
* @return maximum field length when serializing String fields in Tika's metadata or metadata
- * list into JSON
+ * list into JSON
*/
public static int getMaxJsonStringFieldLength() {
return MAX_JSON_STRING_FIELD_LENGTH;
@@ -305,8 +303,9 @@ public class TikaConfig {
try {
MAX_JSON_STRING_FIELD_LENGTH = Integer.parseInt(n.getTextContent());
} catch (NumberFormatException e) {
- throw new TikaConfigException(MAX_JSON_STRING_FIELD_LENGTH_ELEMENT_NAME + " " +
- "is not an integer", e);
+ throw new TikaConfigException(
+ MAX_JSON_STRING_FIELD_LENGTH_ELEMENT_NAME + " " + "is not an integer",
+ e);
}
return;
}
@@ -328,8 +327,12 @@ public class TikaConfig {
protected static CompositeRenderer getDefaultRenderer(ServiceLoader loader) {
return new CompositeRenderer(loader);
}
- private static CompositeParser getDefaultParser(MimeTypes types, ServiceLoader loader,
- EncodingDetector encodingDetector, Renderer renderer) {
+
+ private static CompositeParser getDefaultParser(
+ MimeTypes types,
+ ServiceLoader loader,
+ EncodingDetector encodingDetector,
+ Renderer renderer) {
return new DefaultParser(types.getMediaTypeRegistry(), loader, encodingDetector, renderer);
}
@@ -379,9 +382,9 @@ public class TikaConfig {
}
/**
- * Provides a default configuration (TikaConfig). Currently creates a
- * new instance each time it's called; we may be able to have it
- * return a shared instance once it is completely immutable.
+ * Provides a default configuration (TikaConfig). Currently creates a new instance each time
+ * it's called; we may be able to have it return a shared instance once it is completely
+ * immutable.
*
* @return default configuration
*/
@@ -406,9 +409,8 @@ public class TikaConfig {
return null;
}
- private static List<Element> getTopLevelElementChildren(Element element, String parentName,
- String childrenName)
- throws TikaException {
+ private static List<Element> getTopLevelElementChildren(
+ Element element, String parentName, String childrenName) throws TikaException {
Node parentNode = null;
if (parentName != null) {
// Should be only zero or one <parsers> / <detectors> etc tag
@@ -505,8 +507,9 @@ public class TikaConfig {
if (loader == null) {
loader = ServiceLoader.getContextClassLoader();
}
- serviceLoader = new ServiceLoader(loader, loadErrorHandler, initializableProblemHandler,
- dynamic);
+ serviceLoader =
+ new ServiceLoader(
+ loader, loadErrorHandler, initializableProblemHandler, dynamic);
} else if (loader != null) {
serviceLoader = new ServiceLoader(loader);
} else {
@@ -520,22 +523,28 @@ public class TikaConfig {
if (initializableProblemHandler == null || initializableProblemHandler.length() == 0) {
return InitializableProblemHandler.DEFAULT;
}
- if (InitializableProblemHandler.IGNORE.toString()
+ if (InitializableProblemHandler.IGNORE
+ .toString()
.equalsIgnoreCase(initializableProblemHandler)) {
return InitializableProblemHandler.IGNORE;
- } else if (InitializableProblemHandler.INFO.toString()
+ } else if (InitializableProblemHandler.INFO
+ .toString()
.equalsIgnoreCase(initializableProblemHandler)) {
return InitializableProblemHandler.INFO;
- } else if (InitializableProblemHandler.WARN.toString()
+ } else if (InitializableProblemHandler.WARN
+ .toString()
.equalsIgnoreCase(initializableProblemHandler)) {
return InitializableProblemHandler.WARN;
- } else if (InitializableProblemHandler.THROW.toString()
+ } else if (InitializableProblemHandler.THROW
+ .toString()
.equalsIgnoreCase(initializableProblemHandler)) {
return InitializableProblemHandler.THROW;
}
- throw new TikaConfigException(String.format(Locale.US,
- "Couldn't parse non-null '%s'. Must be one of 'ignore', 'info', 'warn' or 'throw'",
- initializableProblemHandler));
+ throw new TikaConfigException(
+ String.format(
+ Locale.US,
+ "Couldn't parse non-null '%s'. Must be one of 'ignore', 'info', 'warn' or 'throw'",
+ initializableProblemHandler));
}
public static void mustNotBeEmpty(String paramName, String paramValue)
@@ -562,17 +571,16 @@ public class TikaConfig {
}
if (child.hasAttribute("maxEntityExpansions")) {
- XMLReaderUtils.setMaxEntityExpansions(Integer.parseInt(child.getAttribute("maxEntityExpansions")));
+ XMLReaderUtils.setMaxEntityExpansions(
+ Integer.parseInt(child.getAttribute("maxEntityExpansions")));
}
// make sure to call this after set entity expansions
if (child.hasAttribute("poolSize")) {
XMLReaderUtils.setPoolSize(Integer.parseInt(child.getAttribute("poolSize")));
}
-
}
-
/**
* Returns the configured parser instance.
*
@@ -633,7 +641,7 @@ public class TikaConfig {
return autoDetectParserConfig;
}
- private static abstract class XmlLoader<CT, T> {
+ private abstract static class XmlLoader<CT, T> {
protected static final String PARAMS_TAG_NAME = "params";
abstract boolean supportsComposite();
@@ -655,10 +663,13 @@ public class TikaConfig {
abstract CT createComposite(List<T> loaded, MimeTypes mimeTypes, ServiceLoader loader);
- abstract T createComposite(Class<? extends T> compositeClass, List<T> children,
- Set<Class<? extends T>> excludeChildren,
- Map<String, Param> params, MimeTypes mimeTypes,
- ServiceLoader loader)
+ abstract T createComposite(
+ Class<? extends T> compositeClass,
+ List<T> children,
+ Set<Class<? extends T>> excludeChildren,
+ Map<String, Param> params,
+ MimeTypes mimeTypes,
+ ServiceLoader loader)
throws InvocationTargetException, IllegalAccessException, InstantiationException;
abstract T decorate(T created, Element element)
@@ -670,8 +681,8 @@ public class TikaConfig {
List<T> loaded = new ArrayList<>();
// Find the children of the parent tag, if any
- for (Element le : getTopLevelElementChildren(element, getParentTagName(),
- getLoaderTagName())) {
+ for (Element le :
+ getTopLevelElementChildren(element, getParentTagName(), getLoaderTagName())) {
T loadedChild = loadOne(le, mimeTypes, loader);
if (loadedChild != null) {
loaded.add(loadedChild);
@@ -694,10 +705,11 @@ public class TikaConfig {
return (CT) loaded.get(0);
} else if (loaded.size() > 1) {
throw new TikaConfigException(
- "Composite not supported for " + getParentTagName() +
- ". Must specify only one child!");
+ "Composite not supported for "
+ + getParentTagName()
+ + ". Must specify only one child!");
} else {
- //throw exception if empty?
+ // throw exception if empty?
}
}
// Wrap the defined parsers/detectors up in a Composite
@@ -724,7 +736,7 @@ public class TikaConfig {
Class<? extends T> loadedClass = loader.getServiceClass(getLoaderClass(), name);
// Do pre-load checks and short-circuits
- //TODO : allow duplicate instances with different configurations
+ // TODO : allow duplicate instances with different configurations
loaded = preLoadOne(loadedClass, name, mimeTypes);
if (loaded != null) {
return loaded;
@@ -762,10 +774,10 @@ public class TikaConfig {
Element excl = (Element) excludeChildNodes.item(i);
String exclName = excl.getAttribute("class");
try {
- excludeChildren
- .add(loader.getServiceClass(getLoaderClass(), exclName));
+ excludeChildren.add(
+ loader.getServiceClass(getLoaderClass(), exclName));
} catch (ClassNotFoundException e) {
- //TIKA-3268 -- This should stop the world.
+ // TIKA-3268 -- This should stop the world.
throw new TikaConfigException(
"Class not found in -exclude list: " + exclName);
}
@@ -773,8 +785,14 @@ public class TikaConfig {
}
// Create the Composite
- loaded = createComposite(loadedClass, children, excludeChildren, params,
- mimeTypes, loader);
+ loaded =
+ createComposite(
+ loadedClass,
+ children,
+ excludeChildren,
+ params,
+ mimeTypes,
+ loader);
// Default constructor fallback
if (loaded == null) {
@@ -787,7 +805,7 @@ public class TikaConfig {
// See the thread "Configuring parsers and translators" for details
}
- //Assigning the params to bean fields/setters
+ // Assigning the params to bean fields/setters
AnnotationUtils.assignFieldParams(loaded, params);
if (loaded instanceof Initializable) {
((Initializable) loaded).initialize(params);
@@ -817,15 +835,19 @@ public class TikaConfig {
"Unable to instantiate a " + getLoaderTagName() + " class: " + name, e);
} catch (NoSuchMethodException e) {
throw new TikaException(
- "Unable to find the right constructor for " + getLoaderTagName() +
- " class: " + name, e);
+ "Unable to find the right constructor for "
+ + getLoaderTagName()
+ + " class: "
+ + name,
+ e);
}
}
-
T newInstance(Class<? extends T> loadedClass)
- throws IllegalAccessException, InstantiationException, NoSuchMethodException,
- InvocationTargetException {
+ throws IllegalAccessException,
+ InstantiationException,
+ NoSuchMethodException,
+ InvocationTargetException {
return loadedClass.getDeclaredConstructor().newInstance();
}
@@ -838,8 +860,8 @@ public class TikaConfig {
Map<String, Param> getParams(Element el) throws TikaException {
Map<String, Param> params = new HashMap<>();
for (Node child = el.getFirstChild(); child != null; child = child.getNextSibling()) {
- if (PARAMS_TAG_NAME.equals(child.getNodeName())) { //found the node
- if (child.hasChildNodes()) { //it has children
+ if (PARAMS_TAG_NAME.equals(child.getNodeName())) { // found the node
+ if (child.hasChildNodes()) { // it has children
NodeList childNodes = child.getChildNodes();
for (int i = 0; i < childNodes.getLength(); i++) {
Node item = childNodes.item(i);
@@ -849,12 +871,11 @@ public class TikaConfig {
}
}
}
- break; //only the first one is used
+ break; // only the first one is used
}
}
return params;
}
-
}
private static class ParserXmlLoader extends XmlLoader<CompositeParser, Parser> {
@@ -885,13 +906,16 @@ public class TikaConfig {
}
@Override
- Parser preLoadOne(Class<? extends Parser> loadedClass, String classname,
- MimeTypes mimeTypes) throws TikaException {
+ Parser preLoadOne(
+ Class<? extends Parser> loadedClass, String classname, MimeTypes mimeTypes)
+ throws TikaException {
// Check for classes which can't be set in config
if (AutoDetectParser.class.isAssignableFrom(loadedClass)) {
// https://issues.apache.org/jira/browse/TIKA-866
- throw new TikaException("AutoDetectParser not supported in a <parser>" +
- " configuration element: " + classname);
+ throw new TikaException(
+ "AutoDetectParser not supported in a <parser>"
+ + " configuration element: "
+ + classname);
}
// Continue with normal loading
return null;
@@ -904,9 +928,9 @@ public class TikaConfig {
@Override
boolean isComposite(Class<? extends Parser> loadedClass) {
- return CompositeParser.class.isAssignableFrom(loadedClass) ||
- AbstractMultipleParser.class.isAssignableFrom(loadedClass) ||
- ParserDecorator.class.isAssignableFrom(loadedClass);
+ return CompositeParser.class.isAssignableFrom(loadedClass)
+ || AbstractMultipleParser.class.isAssignableFrom(loadedClass)
+ || ParserDecorator.class.isAssignableFrom(loadedClass);
}
@Override
@@ -915,16 +939,20 @@ public class TikaConfig {
}
@Override
- CompositeParser createComposite(List<Parser> parsers, MimeTypes mimeTypes,
- ServiceLoader loader) {
+ CompositeParser createComposite(
+ List<Parser> parsers, MimeTypes mimeTypes, ServiceLoader loader) {
MediaTypeRegistry registry = mimeTypes.getMediaTypeRegistry();
return new CompositeParser(registry, parsers);
}
@Override
- Parser createComposite(Class<? extends Parser> parserClass, List<Parser> childParsers,
- Set<Class<? extends Parser>> excludeParsers,
- Map<String, Param> params, MimeTypes mimeTypes, ServiceLoader loader)
+ Parser createComposite(
+ Class<? extends Parser> parserClass,
+ List<Parser> childParsers,
+ Set<Class<? extends Parser>> excludeParsers,
+ Map<String, Param> params,
+ MimeTypes mimeTypes,
+ ServiceLoader loader)
throws InvocationTargetException, IllegalAccessException, InstantiationException {
Parser parser = null;
Constructor<? extends Parser> c = null;
@@ -933,47 +961,61 @@ public class TikaConfig {
// Try the possible default and composite parser constructors
if (parser == null) {
try {
- c = parserClass.getConstructor(MediaTypeRegistry.class, ServiceLoader.class,
- Collection.class, EncodingDetector.class, Renderer.class);
- parser = c.newInstance(registry, loader, excludeParsers, encodingDetector, renderer);
+ c =
+ parserClass.getConstructor(
+ MediaTypeRegistry.class,
+ ServiceLoader.class,
+ Collection.class,
+ EncodingDetector.class,
+ Renderer.class);
+ parser =
+ c.newInstance(
+ registry, loader, excludeParsers, encodingDetector, renderer);
} catch (NoSuchMethodException me) {
- //swallow
+ // swallow
}
}
if (parser == null) {
try {
- c = parserClass.getConstructor(MediaTypeRegistry.class, ServiceLoader.class,
- Collection.class, EncodingDetector.class);
+ c =
+ parserClass.getConstructor(
+ MediaTypeRegistry.class,
+ ServiceLoader.class,
+ Collection.class,
+ EncodingDetector.class);
parser = c.newInstance(registry, loader, excludeParsers, encodingDetector);
} catch (NoSuchMethodException me) {
- //swallow
+ // swallow
}
}
if (parser == null) {
try {
- c = parserClass.getConstructor(MediaTypeRegistry.class, ServiceLoader.class,
- Collection.class);
+ c =
+ parserClass.getConstructor(
+ MediaTypeRegistry.class, ServiceLoader.class, Collection.class);
parser = c.newInstance(registry, loader, excludeParsers);
} catch (NoSuchMethodException me) {
- //swallow
+ // swallow
}
}
if (parser == null) {
try {
- c = parserClass
- .getConstructor(MediaTypeRegistry.class, List.class, Collection.class);
+ c =
+ parserClass.getConstructor(
+ MediaTypeRegistry.class, List.class, Collection.class);
parser = c.newInstance(registry, childParsers, excludeParsers);
} catch (NoSuchMethodException me) {
- //swallow
+ // swallow
}
}
if (parser == null) {
try {
- c = parserClass
- .getConstructor(MediaTypeRegistry.class, Collection.class, Map.class);
+ c =
+ parserClass.getConstructor(
+ MediaTypeRegistry.class, Collection.class, Map.class);
parser = c.newInstance(registry, childParsers, params);
} catch (NoSuchMethodException me) {
- //swallow
+ // swallow
}
}
if (parser == null) {
@@ -981,7 +1023,7 @@ public class TikaConfig {
c = parserClass.getConstructor(MediaTypeRegistry.class, List.class);
parser = c.newInstance(registry, childParsers);
} catch (NoSuchMethodException me) {
- //swallow
+ // swallow
}
}
@@ -989,8 +1031,9 @@ public class TikaConfig {
if (parser == null && ParserDecorator.class.isAssignableFrom(parserClass)) {
try {
CompositeParser cp = null;
- if (childParsers.size() == 1 && excludeParsers.size() == 0 &&
- childParsers.get(0) instanceof CompositeParser) {
+ if (childParsers.size() == 1
+ && excludeParsers.size() == 0
+ && childParsers.get(0) instanceof CompositeParser) {
cp = (CompositeParser) childParsers.get(0);
} else {
cp = new CompositeParser(registry, childParsers, excludeParsers);
@@ -998,7 +1041,7 @@ public class TikaConfig {
c = parserClass.getConstructor(Parser.class);
parser = c.newInstance(cp);
} catch (NoSuchMethodException me) {
- //swallow
+ // swallow
}
}
return parser;
@@ -1006,8 +1049,10 @@ public class TikaConfig {
@Override
Parser newInstance(Class<? extends Parser> loadedClass)
- throws IllegalAccessException, InstantiationException, NoSuchMethodException,
- InvocationTargetException {
+ throws IllegalAccessException,
+ InstantiationException,
+ NoSuchMethodException,
+ InvocationTargetException {
Parser parser = null;
if (AbstractEncodingDetectorParser.class.isAssignableFrom(loadedClass)) {
Constructor ctor = loadedClass.getConstructor(EncodingDetector.class);
@@ -1017,7 +1062,7 @@ public class TikaConfig {
}
if (parser instanceof RenderingParser) {
- ((RenderingParser)parser).setRenderer(renderer);
+ ((RenderingParser) parser).setRenderer(renderer);
}
return parser;
}
@@ -1040,7 +1085,6 @@ public class TikaConfig {
// All done with decoration
return parser;
}
-
}
private static class DetectorXmlLoader extends XmlLoader<CompositeDetector, Detector> {
@@ -1062,8 +1106,9 @@ public class TikaConfig {
}
@Override
- Detector preLoadOne(Class<? extends Detector> loadedClass, String classname,
- MimeTypes mimeTypes) throws TikaException {
+ Detector preLoadOne(
+ Class<? extends Detector> loadedClass, String classname, MimeTypes mimeTypes)
+ throws TikaException {
// If they asked for the mime types as a detector, give
// them the one we've already created. TIKA-1708
if (MimeTypes.class.equals(loadedClass)) {
@@ -1089,18 +1134,20 @@ public class TikaConfig {
}
@Override
- CompositeDetector createComposite(List<Detector> detectors, MimeTypes mimeTypes,
- ServiceLoader loader) {
+ CompositeDetector createComposite(
+ List<Detector> detectors, MimeTypes mimeTypes, ServiceLoader loader) {
MediaTypeRegistry registry = mimeTypes.getMediaTypeRegistry();
return new CompositeDetector(registry, detectors);
}
@Override
- Detector createComposite(Class<? extends Detector> detectorClass,
- List<Detector> childDetectors,
- Set<Class<? extends Detector>> excludeDetectors,
- Map<String, Param> params, MimeTypes mimeTypes,
- ServiceLoader loader)
+ Detector createComposite(
+ Class<? extends Detector> detectorClass,
+ List<Detector> childDetectors,
+ Set<Class<? extends Detector>> excludeDetectors,
+ Map<String, Param> params,
+ MimeTypes mimeTypes,
+ ServiceLoader loader)
throws InvocationTargetException, IllegalAccessException, InstantiationException {
Detector detector = null;
Constructor<? extends Detector> c;
@@ -1109,20 +1156,22 @@ public class TikaConfig {
// Try the possible default and composite detector constructors
if (detector == null) {
try {
- c = detectorClass
- .getConstructor(MimeTypes.class, ServiceLoader.class, Collection.class);
+ c =
+ detectorClass.getConstructor(
+ MimeTypes.class, ServiceLoader.class, Collection.class);
detector = c.newInstance(mimeTypes, loader, excludeDetectors);
} catch (NoSuchMethodException me) {
- //swallow
+ // swallow
}
}
if (detector == null) {
try {
- c = detectorClass
- .getConstructor(MediaTypeRegistry.class, List.class, Collection.class);
+ c =
+ detectorClass.getConstructor(
+ MediaTypeRegistry.class, List.class, Collection.class);
detector = c.newInstance(registry, childDetectors, excludeDetectors);
} catch (NoSuchMethodException me) {
- //swallow
+ // swallow
}
}
if (detector == null) {
@@ -1130,7 +1179,7 @@ public class TikaConfig {
c = detectorClass.getConstructor(MediaTypeRegistry.class, List.class);
detector = c.newInstance(registry, childDetectors);
} catch (NoSuchMethodException me) {
- //swallow
+ // swallow
}
}
if (detector == null) {
@@ -1138,7 +1187,7 @@ public class TikaConfig {
c = detectorClass.getConstructor(List.class);
detector = c.newInstance(childDetectors);
} catch (NoSuchMethodException me) {
- //swallow
+ // swallow
}
}
@@ -1170,8 +1219,9 @@ public class TikaConfig {
}
@Override
- Translator preLoadOne(Class<? extends Translator> loadedClass, String classname,
- MimeTypes mimeTypes) throws TikaException {
+ Translator preLoadOne(
+ Class<? extends Translator> loadedClass, String classname, MimeTypes mimeTypes)
+ throws TikaException {
// Continue with normal loading
return null;
}
@@ -1192,17 +1242,19 @@ public class TikaConfig {
}
@Override
- Translator createComposite(List<Translator> loaded, MimeTypes mimeTypes,
- ServiceLoader loader) {
+ Translator createComposite(
+ List<Translator> loaded, MimeTypes mimeTypes, ServiceLoader loader) {
return loaded.get(0);
}
@Override
- Translator createComposite(Class<? extends Translator> compositeClass,
- List<Translator> children,
- Set<Class<? extends Translator>> excludeChildren,
- Map<String, Param> params, MimeTypes mimeTypes,
- ServiceLoader loader)
+ Translator createComposite(
+ Class<? extends Translator> compositeClass,
+ List<Translator> children,
+ Set<Class<? extends Translator>> excludeChildren,
+ Map<String, Param> params,
+ MimeTypes mimeTypes,
+ ServiceLoader loader)
throws InvocationTargetException, IllegalAccessException, InstantiationException {
throw new InstantiationException("Only one translator supported");
}
@@ -1220,14 +1272,18 @@ public class TikaConfig {
Class<? extends ConfigurableThreadPoolExecutor> compositeClass,
List<ConfigurableThreadPoolExecutor> children,
Set<Class<? extends ConfigurableThreadPoolExecutor>> excludeChildren,
- Map<String, Param> params, MimeTypes mimeTypes, ServiceLoader loader)
+ Map<String, Param> params,
+ MimeTypes mimeTypes,
+ ServiceLoader loader)
throws InvocationTargetException, IllegalAccessException, InstantiationException {
throw new InstantiationException("Only one executor service supported");
}
@Override
- ConfigurableThreadPoolExecutor createComposite(List<ConfigurableThreadPoolExecutor> loaded,
- MimeTypes mimeTypes, ServiceLoader loader) {
+ ConfigurableThreadPoolExecutor createComposite(
+ List<ConfigurableThreadPoolExecutor> loaded,
+ MimeTypes mimeTypes,
+ ServiceLoader loader) {
return loaded.get(0);
}
@@ -1237,8 +1293,9 @@ public class TikaConfig {
}
@Override
- ConfigurableThreadPoolExecutor decorate(ConfigurableThreadPoolExecutor created,
- Element element) throws IOException, TikaException {
+ ConfigurableThreadPoolExecutor decorate(
+ ConfigurableThreadPoolExecutor created, Element element)
+ throws IOException, TikaException {
Element maxThreadElement = getChild(element, "max-threads");
if (maxThreadElement != null) {
@@ -1258,8 +1315,8 @@ public class TikaConfig {
}
@Override
- ConfigurableThreadPoolExecutor loadOne(Element element, MimeTypes mimeTypes,
- ServiceLoader loader)
+ ConfigurableThreadPoolExecutor loadOne(
+ Element element, MimeTypes mimeTypes, ServiceLoader loader)
throws TikaException, IOException {
return super.loadOne(element, mimeTypes, loader);
}
@@ -1291,8 +1348,10 @@ public class TikaConfig {
@Override
ConfigurableThreadPoolExecutor preLoadOne(
- Class<? extends ConfigurableThreadPoolExecutor> loadedClass, String classname,
- MimeTypes mimeTypes) throws TikaException {
+ Class<? extends ConfigurableThreadPoolExecutor> loadedClass,
+ String classname,
+ MimeTypes mimeTypes)
+ throws TikaException {
return null;
}
}
@@ -1317,7 +1376,6 @@ public class TikaConfig {
return EncodingDetector.class;
}
-
@Override
boolean isComposite(EncodingDetector loaded) {
return loaded instanceof CompositeEncodingDetector;
@@ -1329,8 +1387,11 @@ public class TikaConfig {
}
@Override
- EncodingDetector preLoadOne(Class<? extends EncodingDetector> loadedClass, String classname,
- MimeTypes mimeTypes) throws TikaException {
+ EncodingDetector preLoadOne(
+ Class<? extends EncodingDetector> loadedClass,
+ String classname,
+ MimeTypes mimeTypes)
+ throws TikaException {
// Check for classes which can't be set in config
// Continue with normal loading
return null;
@@ -1342,17 +1403,21 @@ public class TikaConfig {
}
@Override
- CompositeEncodingDetector createComposite(List<EncodingDetector> encodingDetectors,
- MimeTypes mimeTypes, ServiceLoader loader) {
+ CompositeEncodingDetector createComposite(
+ List<EncodingDetector> encodingDetectors,
+ MimeTypes mimeTypes,
+ ServiceLoader loader) {
return new CompositeEncodingDetector(encodingDetectors);
}
@Override
- EncodingDetector createComposite(Class<? extends EncodingDetector> encodingDetectorClass,
- List<EncodingDetector> childEncodingDetectors,
- Set<Class<? extends EncodingDetector>> excludeDetectors,
- Map<String, Param> params, MimeTypes mimeTypes,
- ServiceLoader loader)
+ EncodingDetector createComposite(
+ Class<? extends EncodingDetector> encodingDetectorClass,
+ List<EncodingDetector> childEncodingDetectors,
+ Set<Class<? extends EncodingDetector>> excludeDetectors,
+ Map<String, Param> params,
+ MimeTypes mimeTypes,
+ ServiceLoader loader)
throws InvocationTargetException, IllegalAccessException, InstantiationException {
EncodingDetector encodingDetector = null;
Constructor<? extends EncodingDetector> c;
@@ -1363,7 +1428,8 @@ public class TikaConfig {
c = encodingDetectorClass.getConstructor(ServiceLoader.class, Collection.class);
encodingDetector = c.newInstance(loader, excludeDetectors);
} catch (NoSuchMethodException me) {
- LOG.debug("couldn't find constructor for service loader + collection for {}",
+ LOG.debug(
+ "couldn't find constructor for service loader + collection for {}",
encodingDetectorClass);
}
}
@@ -1372,7 +1438,8 @@ public class TikaConfig {
c = encodingDetectorClass.getConstructor(List.class);
encodingDetector = c.newInstance(childEncodingDetectors);
} catch (NoSuchMethodException me) {
- LOG.debug("couldn't find constructor for EncodingDetector(List) for {}",
+ LOG.debug(
+ "couldn't find constructor for EncodingDetector(List) for {}",
encodingDetectorClass);
}
}
@@ -1386,8 +1453,7 @@ public class TikaConfig {
}
}
- private static class RendererXmlLoader
- extends XmlLoader<Renderer, Renderer> {
+ private static class RendererXmlLoader extends XmlLoader<Renderer, Renderer> {
boolean supportsComposite() {
return true;
@@ -1406,7 +1472,6 @@ public class TikaConfig {
return Renderer.class;
}
-
@Override
boolean isComposite(Renderer loaded) {
return loaded instanceof CompositeRenderer;
@@ -1418,8 +1483,9 @@ public class TikaConfig {
}
@Override
- Renderer preLoadOne(Class<? extends Renderer> loadedClass, String classname,
- MimeTypes mimeTypes) throws TikaException {
+ Renderer preLoadOne(
+ Class<? extends Renderer> loadedClass, String classname, MimeTypes mimeTypes)
+ throws TikaException {
// Check for classes which can't be set in config
// Continue with normal loading
return null;
@@ -1431,17 +1497,19 @@ public class TikaConfig {
}
@Override
- Renderer createComposite(List<Renderer> renderers,
- MimeTypes mimeTypes, ServiceLoader loader) {
+ Renderer createComposite(
+ List<Renderer> renderers, MimeTypes mimeTypes, ServiceLoader loader) {
return new CompositeRenderer(renderers);
}
@Override
- Renderer createComposite(Class<? extends Renderer> rendererClass,
- List<Renderer> childRenderers,
- Set<Class<? extends Renderer>> excludeRenderers,
- Map<String, Param> params, MimeTypes mimeTypes,
- ServiceLoader loader)
+ Renderer createComposite(
+ Class<? extends Renderer> rendererClass,
+ List<Renderer> childRenderers,
+ Set<Class<? extends Renderer>> excludeRenderers,
+ Map<String, Param> params,
+ MimeTypes mimeTypes,
+ ServiceLoader loader)
throws InvocationTargetException, IllegalAccessException, InstantiationException {
Renderer renderer = null;
Constructor<? extends Renderer> c;
@@ -1452,7 +1520,8 @@ public class TikaConfig {
c = rendererClass.getConstructor(ServiceLoader.class, Collection.class);
renderer = c.newInstance(loader, excludeRenderers);
} catch (NoSuchMethodException me) {
- LOG.debug("couldn't find constructor for service loader + collection for {}",
+ LOG.debug(
+ "couldn't find constructor for service loader + collection for {}",
renderer);
}
}
@@ -1461,8 +1530,7 @@ public class TikaConfig {
c = rendererClass.getConstructor(List.class);
renderer = c.newInstance(childRenderers);
} catch (NoSuchMethodException me) {
- LOG.debug("couldn't find constructor for Renderer(List) for {}",
- rendererClass);
+ LOG.debug("couldn't find constructor for Renderer(List) for {}", rendererClass);
}
}
return renderer;
diff --git a/tika-core/src/main/java/org/apache/tika/config/TikaConfigSerializer.java b/tika-core/src/main/java/org/apache/tika/config/TikaConfigSerializer.java
index a2313f408..8077c2bd2 100644
--- a/tika-core/src/main/java/org/apache/tika/config/TikaConfigSerializer.java
+++ b/tika-core/src/main/java/org/apache/tika/config/TikaConfigSerializer.java
@@ -39,13 +39,6 @@ import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
import org.apache.tika.detect.CompositeDetector;
import org.apache.tika.detect.CompositeEncodingDetector;
import org.apache.tika.detect.DefaultDetector;
@@ -63,6 +56,11 @@ import org.apache.tika.parser.ParserDecorator;
import org.apache.tika.parser.multiple.AbstractMultipleParser;
import org.apache.tika.utils.StringUtils;
import org.apache.tika.utils.XMLReaderUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
public class TikaConfigSerializer {
@@ -86,9 +84,9 @@ public class TikaConfigSerializer {
}
/**
- * @param config config to serialize
- * @param mode serialization mode
- * @param writer writer
+ * @param config config to serialize
+ * @param mode serialization mode
+ * @param writer writer
* @param charset charset
* @throws Exception
*/
@@ -121,8 +119,8 @@ public class TikaConfigSerializer {
transformer.transform(source, result);
}
- private static void addExecutorService(Mode mode, Element rootElement, Document doc,
- TikaConfig config) {
+ private static void addExecutorService(
+ Mode mode, Element rootElement, Document doc, TikaConfig config) {
ExecutorService executor = config.getExecutorService();
// TODO Implement the reverse of ExecutorServiceXmlLoader
@@ -130,8 +128,8 @@ public class TikaConfigSerializer {
// TODO Make it possible to get the current values from ConfigurableThreadPoolExecutor
}
- private static void addServiceLoader(Mode mode, Element rootElement, Document doc,
- TikaConfig config) {
+ private static void addServiceLoader(
+ Mode mode, Element rootElement, Document doc, TikaConfig config) {
ServiceLoader loader = config.getServiceLoader();
if (mode == Mode.MINIMAL) {
@@ -148,18 +146,20 @@ public class TikaConfigSerializer {
rootElement.appendChild(dslEl);
}
- private static void addTranslator(Mode mode, Element rootElement, Document doc,
- TikaConfig config) {
+ private static void addTranslator(
+ Mode mode, Element rootElement, Document doc, TikaConfig config) {
// Unlike the other entries, TikaConfig only wants one of
// these, and no outer <translators> list
Translator translator = config.getTranslator();
if (mode == Mode.MINIMAL && translator instanceof DefaultTranslator) {
- Node mimeComment = doc.createComment("for example: <translator " +
- "class=\"org.apache.tika.language.translate.GoogleTranslator\"/>");
+ Node mimeComment =
+ doc.createComment(
+ "for example: <translator "
+ + "class=\"org.apache.tika.language.translate.GoogleTranslator\"/>");
rootElement.appendChild(mimeComment);
} else {
- if (translator instanceof DefaultTranslator &&
- (mode == Mode.STATIC || mode == Mode.STATIC_FULL)) {
+ if (translator instanceof DefaultTranslator
+ && (mode == Mode.STATIC || mode == Mode.STATIC_FULL)) {
translator = ((DefaultTranslator) translator).getTranslator();
}
if (translator != null) {
@@ -173,28 +173,31 @@ public class TikaConfigSerializer {
}
private static void addMimeComment(Mode mode, Element rootElement, Document doc) {
- Node mimeComment = doc.createComment("for example: <mimeTypeRepository " +
- "resource=\"/org/apache/tika/mime/tika-mimetypes.xml\"/>");
+ Node mimeComment =
+ doc.createComment(
+ "for example: <mimeTypeRepository "
+ + "resource=\"/org/apache/tika/mime/tika-mimetypes.xml\"/>");
rootElement.appendChild(mimeComment);
}
- private static void addEncodingDetectors(Mode mode, Element rootElement, Document doc,
- TikaConfig config) throws Exception {
+ private static void addEncodingDetectors(
+ Mode mode, Element rootElement, Document doc, TikaConfig config) throws Exception {
EncodingDetector encDetector = config.getEncodingDetector();
if (mode == Mode.MINIMAL && encDetector instanceof DefaultEncodingDetector) {
// Don't output anything, all using defaults
- Node detComment = doc.createComment(
- "for example: <encodingDetectors><encodingDetector class=\"" +
- "org.apache.tika.detect.DefaultEncodingDetector\">" +
- "</encodingDetectors>");
+ Node detComment =
+ doc.createComment(
+ "for example: <encodingDetectors><encodingDetector class=\""
+ + "org.apache.tika.detect.DefaultEncodingDetector\">"
+ + "</encodingDetectors>");
rootElement.appendChild(detComment);
return;
}
Element encDetectorsElement = doc.createElement("encodingDetectors");
- if (mode == Mode.CURRENT && encDetector instanceof DefaultEncodingDetector ||
- !(encDetector instanceof CompositeEncodingDetector)) {
+ if (mode == Mode.CURRENT && encDetector instanceof DefaultEncodingDetector
+ || !(encDetector instanceof CompositeEncodingDetector)) {
Element encDetectorElement = doc.createElement("encodingDetector");
encDetectorElement.setAttribute("class", encDetector.getClass().getCanonicalName());
encDetectorsElement.appendChild(encDetectorElement);
@@ -212,21 +215,23 @@ public class TikaConfigSerializer {
rootElement.appendChild(encDetectorsElement);
}
- private static void addDetectors(Mode mode, Element rootElement, Document doc,
- TikaConfig config) throws Exception {
+ private static void addDetectors(
+ Mode mode, Element rootElement, Document doc, TikaConfig config) throws Exception {
Detector detector = config.getDetector();
if (mode == Mode.MINIMAL && detector instanceof DefaultDetector) {
// Don't output anything, all using defaults
- Node detComment = doc.createComment("for example: <detectors><detector " +
- "class=\"org.apache.tika.detector.MimeTypes\"></detectors>");
+ Node detComment =
+ doc.createComment(
+ "for example: <detectors><detector "
+ + "class=\"org.apache.tika.detector.MimeTypes\"></detectors>");
rootElement.appendChild(detComment);
return;
}
Element detectorsElement = doc.createElement("detectors");
- if (mode == Mode.CURRENT && detector instanceof DefaultDetector ||
- !(detector instanceof CompositeDetector)) {
+ if (mode == Mode.CURRENT && detector instanceof DefaultDetector
+ || !(detector instanceof CompositeDetector)) {
Element detectorElement = doc.createElement("detector");
detectorElement.setAttribute("class", detector.getClass().getCanonicalName());
detectorsElement.appendChild(detectorElement);
@@ -280,8 +285,8 @@ public class TikaConfigSerializer {
outputParser = false;
}
// Special case for making Default to static
- if (parser instanceof DefaultParser &&
- (mode == Mode.STATIC || mode == Mode.STATIC_FULL)) {
+ if (parser instanceof DefaultParser
+ && (mode == Mode.STATIC || mode == Mode.STATIC_FULL)) {
outputParser = false;
}
} else if (parser instanceof AbstractMultipleParser) {
@@ -298,8 +303,9 @@ public class TikaConfigSerializer {
// TODO Parser Exclusions
}
- private static Element addParser(Mode mode, Element rootElement, Document doc, Parser parser,
- ParserDecorator decorator) throws Exception {
+ private static Element addParser(
+ Mode mode, Element rootElement, Document doc, Parser parser, ParserDecorator decorator)
+ throws Exception {
ParseContext context = new ParseContext();
Set<MediaType> addedTypes = new TreeSet<>();
@@ -343,7 +349,7 @@ public class TikaConfigSerializer {
Matcher setterMatcher = Pattern.compile("\\Aset([A-Z].*)").matcher("");
Matcher getterMatcher = Pattern.compile("\\A(?:get|is)([A-Z].+)\\Z").matcher("");
- //TODO -- check code base for setters with lowercase initial letters?!
+ // TODO -- check code base for setters with lowercase initial letters?!
MethodTuples nonPrimitiveSetters = new MethodTuples();
MethodTuples primitiveSetters = new MethodTuples();
MethodTuples nonPrimitiveGetters = new MethodTuples();
@@ -353,18 +359,22 @@ public class TikaConfigSerializer {
if (setterMatcher.reset(method.getName()).find()) {
if (!Modifier.isPublic(method.getModifiers())) {
- //we could just call getMethods, but this can be helpful debugging inf
+ // we could just call getMethods, but this can be helpful debugging inf
LOG.trace("inaccessible setter: {} in {}", method.getName(), object.getClass());
continue;
}
- //require @Field on setters
+ // require @Field on setters
if (method.getAnnotation(Field.class) == null) {
- // LOG.warn("unannotated setter {} in {}", method.getName(), object.getClass());
+ // LOG.warn("unannotated setter {} in {}", method.getName(), object.getClass());
continue;
}
if (parameterTypes.length != 1) {
- //TODO -- check code base for setX() zero parameters that set boolean to true
- LOG.warn("setter with wrong number of params " + method.getName() + " " + parameterTypes.length);
+ // TODO -- check code base for setX() zero parameters that set boolean to true
+ LOG.warn(
+ "setter with wrong number of params "
+ + method.getName()
+ + " "
+ + parameterTypes.length);
continue;
}
String paramName = methodToParamName(setterMatcher.group(1));
@@ -375,23 +385,23 @@ public class TikaConfigSerializer {
}
} else if (getterMatcher.reset(method.getName()).find()) {
if (parameterTypes.length != 0) {
- //require 0 parameters for the getter
+ // require 0 parameters for the getter
continue;
}
String paramName = methodToParamName(getterMatcher.group(1));
if (PRIMITIVES.containsKey(method.getReturnType())) {
- primitiveGetters.add(new MethodTuple(paramName, method, method.getReturnType()));
+ primitiveGetters.add(
+ new MethodTuple(paramName, method, method.getReturnType()));
} else {
- nonPrimitiveGetters.add(new MethodTuple(paramName, method, method.getReturnType()));
+ nonPrimitiveGetters.add(
+ new MethodTuple(paramName, method, method.getReturnType()));
}
-
}
}
- //TODO -- remove nonprimitive setters/getters that have a string equivalent
+ // TODO -- remove nonprimitive setters/getters that have a string equivalent
serializePrimitives(doc, element, object, primitiveSetters, primitiveGetters);
serializeNonPrimitives(doc, element, object, nonPrimitiveSetters, nonPrimitiveGetters);
-
}
private static String methodToParamName(String name) {
@@ -399,28 +409,35 @@ public class TikaConfigSerializer {
return name;
}
return name.substring(0, 1).toLowerCase(Locale.US) + name.substring(1);
-
}
- private static void serializeNonPrimitives(Document doc, Element element,
- Object object,
- MethodTuples setterTuples,
- MethodTuples getterTuples) {
+ private static void serializeNonPrimitives(
+ Document doc,
+ Element element,
+ Object object,
+ MethodTuples setterTuples,
+ MethodTuples getterTuples) {
for (Map.Entry<String, Set<MethodTuple>> e : setterTuples.tuples.entrySet()) {
Set<MethodTuple> getters = getterTuples.tuples.get(e.getKey());
processNonPrimitive(e.getKey(), e.getValue(), getters, doc, element, object);
if (!getterTuples.tuples.containsKey(e.getKey())) {
- LOG.warn("no getter for setter non-primitive: {} in {}", e.getKey(),
+ LOG.warn(
+ "no getter for setter non-primitive: {} in {}",
+ e.getKey(),
object.getClass());
continue;
}
}
}
- private static void processNonPrimitive(String name, Set<MethodTuple> setters,
- Set<MethodTuple> getters, Document doc, Element element,
- Object object) {
+ private static void processNonPrimitive(
+ String name,
+ Set<MethodTuple> setters,
+ Set<MethodTuple> getters,
+ Document doc,
+ Element element,
+ Object object) {
for (MethodTuple setter : setters) {
for (MethodTuple getter : getters) {
if (setter.singleParam.equals(getter.singleParam)) {
@@ -431,9 +448,13 @@ public class TikaConfigSerializer {
}
}
- private static void serializeObject(String name, Document doc, Element element,
- MethodTuple setter,
- MethodTuple getter, Object object) {
+ private static void serializeObject(
+ String name,
+ Document doc,
+ Element element,
+ MethodTuple setter,
+ MethodTuple getter,
+ Object object) {
Object item = null;
try {
@@ -451,17 +472,20 @@ public class TikaConfigSerializer {
serializeParams(doc, element, item);
}
- private static void serializePrimitives(Document doc, Element root,
- Object object,
- MethodTuples setterTuples, MethodTuples getterTuples) {
+ private static void serializePrimitives(
+ Document doc,
+ Element root,
+ Object object,
+ MethodTuples setterTuples,
+ MethodTuples getterTuples) {
Element paramsElement = null;
if (object instanceof AbstractMultipleParser) {
paramsElement = doc.createElement("params");
Element paramElement = doc.createElement("param");
paramElement.setAttribute("name", "metadataPolicy");
- paramElement.setAttribute("value",
- ((AbstractMultipleParser) object).getMetadataPolicy().toString());
+ paramElement.setAttribute(
+ "value", ((AbstractMultipleParser) object).getMetadataPolicy().toString());
paramsElement.appendChild(paramElement);
root.appendChild(paramsElement);
}
@@ -504,10 +528,10 @@ public class TikaConfigSerializer {
param.setAttribute("name", getterTuple.name);
param.setAttribute("type", PRIMITIVES.get(getterTuple.singleParam));
if (List.class.isAssignableFrom(getterTuple.singleParam)) {
- //this outputs even empty list elements, which I think is good.
+ // this outputs even empty list elements, which I think is good.
addList(param, doc, getterTuple, (List<String>) value);
} else if (Map.class.isAssignableFrom(getterTuple.singleParam)) {
- //this outputs even empty lists, which I think is good.
+ // this outputs even empty lists, which I think is good.
addMap(param, doc, getterTuple, (Map<String, String>) value);
} else {
param.setTextContent(valString);
@@ -520,19 +544,18 @@ public class TikaConfigSerializer {
}
}
- private static void addMap(Element param, Document doc, MethodTuple getterTuple,
- Map<String, String> object) {
+ private static void addMap(
+ Element param, Document doc, MethodTuple getterTuple, Map<String, String> object) {
for (Map.Entry<String, String> e : new TreeMap<String, String>(object).entrySet()) {
Element element = doc.createElement("string");
element.setAttribute("key", e.getKey());
element.setAttribute("value", e.getValue());
param.appendChild(element);
}
-
}
- private static void addList(Element param, Document doc, MethodTuple getterTuple,
- List<String> list) {
+ private static void addList(
+ Element param, Document doc, MethodTuple getterTuple, List<String> list) {
for (String s : list) {
Element element = doc.createElement("string");
element.setTextContent(s);
@@ -563,8 +586,8 @@ public class TikaConfigSerializer {
}
private static MethodTuple pickBestSetter(Set<MethodTuple> tuples) {
- //TODO -- if both string and integer, which one do we pick?
- //stub for now -- just pick the first
+ // TODO -- if both string and integer, which one do we pick?
+ // stub for now -- just pick the first
for (MethodTuple t : tuples) {
return t;
}
@@ -587,6 +610,7 @@ public class TikaConfigSerializer {
return tuples.size();
}
}
+
private static class MethodTuple {
String name;
Method method;
@@ -607,8 +631,9 @@ public class TikaConfigSerializer {
return false;
}
MethodTuple that = (MethodTuple) o;
- return name.equals(that.name) && method.equals(that.method) &&
- singleParam.equals(that.singleParam);
+ return name.equals(that.name)
+ && method.equals(that.method)
+ && singleParam.equals(that.singleParam);
}
@Override
@@ -616,24 +641,18 @@ public class TikaConfigSerializer {
return Objects.hash(name, method, singleParam);
}
}
+
public enum Mode {
- /**
- * Minimal version of the config, defaults where possible
- */
+ /** Minimal version of the config, defaults where possible */
MINIMAL,
- /**
- * Current config, roughly as loaded
- */
+ /** Current config, roughly as loaded */
CURRENT,
- /**
- * Static version of the config, with explicit lists of parsers/decorators/etc
- */
+ /** Static version of the config, with explicit lists of parsers/decorators/etc */
STATIC,
/**
- * Static version of the config, with explicit lists of decorators etc,
- * and all parsers given with their detected supported mime types
+ * Static version of the config, with explicit lists of decorators etc, and all parsers
+ * given with their detected supported mime types
*/
STATIC_FULL
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/config/package-info.java b/tika-core/src/main/java/org/apache/tika/config/package-info.java
index 77a0559f7..93b2ca862 100644
--- a/tika-core/src/main/java/org/apache/tika/config/package-info.java
+++ b/tika-core/src/main/java/org/apache/tika/config/package-info.java
@@ -15,8 +15,6 @@
* limitations under the License.
*/
-/**
- * Tika configuration tools.
- */
+/** Tika configuration tools. */
@aQute.bnd.annotation.Version("1.0.0")
package org.apache.tika.config;
diff --git a/tika-core/src/main/java/org/apache/tika/detect/AutoDetectReader.java b/tika-core/src/main/java/org/apache/tika/detect/AutoDetectReader.java
index bd7d4f2a9..ee9833d53 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/AutoDetectReader.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/AutoDetectReader.java
@@ -22,9 +22,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
-
-import org.xml.sax.InputSource;
-
import org.apache.tika.config.LoadErrorHandler;
import org.apache.tika.config.ServiceLoader;
import org.apache.tika.exception.TikaException;
@@ -32,10 +29,11 @@ import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.mime.MediaType;
import org.apache.tika.utils.CharsetUtils;
+import org.xml.sax.InputSource;
/**
- * An input stream reader that automatically detects the character encoding
- * to be used for converting bytes to characters.
+ * An input stream reader that automatically detects the character encoding to be used for
+ * converting bytes to characters.
*
* @since Apache Tika 1.2
*/
@@ -47,8 +45,9 @@ public class AutoDetectReader extends BufferedReader {
private static final EncodingDetector DEFAULT_DETECTOR;
static {
- DEFAULT_DETECTOR = new CompositeEncodingDetector(
- DEFAULT_LOADER.loadServiceProviders(EncodingDetector.class));
+ DEFAULT_DETECTOR =
+ new CompositeEncodingDetector(
+ DEFAULT_LOADER.loadServiceProviders(EncodingDetector.class));
}
private final Charset charset;
@@ -65,28 +64,33 @@ public class AutoDetectReader extends BufferedReader {
}
/**
- * @param stream stream from which to read -- make sure that it supports mark!
+ * @param stream stream from which to read -- make sure that it supports mark!
* @param metadata
* @param detector
* @param handler
* @throws IOException
* @throws TikaException
*/
- private AutoDetectReader(InputStream stream, Metadata metadata,
- EncodingDetector detector, LoadErrorHandler handler)
+ private AutoDetectReader(
+ InputStream stream,
+ Metadata metadata,
+ EncodingDetector detector,
+ LoadErrorHandler handler)
throws IOException, TikaException {
this(stream, detect(stream, metadata, detector, handler));
}
- public AutoDetectReader(InputStream stream, Metadata metadata,
- EncodingDetector encodingDetector) throws IOException, TikaException {
- this(getBuffered(stream), metadata, encodingDetector,
- DEFAULT_LOADER.getLoadErrorHandler());
+ public AutoDetectReader(
+ InputStream stream, Metadata metadata, EncodingDetector encodingDetector)
+ throws IOException, TikaException {
+ this(getBuffered(stream), metadata, encodingDetector, DEFAULT_LOADER.getLoadErrorHandler());
}
public AutoDetectReader(InputStream stream, Metadata metadata, ServiceLoader loader)
throws IOException, TikaException {
- this(getBuffered(stream), metadata,
+ this(
+ getBuffered(stream),
+ metadata,
new CompositeEncodingDetector(loader.loadServiceProviders(EncodingDetector.class)),
loader.getLoadErrorHandler());
}
@@ -100,8 +104,11 @@ public class AutoDetectReader extends BufferedReader {
this(stream, new Metadata());
}
- private static Charset detect(InputStream input, Metadata metadata,
- EncodingDetector detector, LoadErrorHandler handler)
+ private static Charset detect(
+ InputStream input,
+ Metadata metadata,
+ EncodingDetector detector,
+ LoadErrorHandler handler)
throws IOException, TikaException {
// Ask all given detectors for the character encoding
try {
@@ -122,7 +129,8 @@ public class AutoDetectReader extends BufferedReader {
try {
Charset cs = CharsetUtils.forName(charset);
metadata.set(TikaCoreProperties.DETECTED_ENCODING, cs.name());
- metadata.set(TikaCoreProperties.ENCODING_DETECTOR,
+ metadata.set(
+ TikaCoreProperties.ENCODING_DETECTOR,
"AutoDetectReader-charset-metadata-fallback");
return cs;
} catch (IllegalArgumentException e) {
@@ -141,7 +149,6 @@ public class AutoDetectReader extends BufferedReader {
return new BufferedInputStream(stream);
}
-
public Charset getCharset() {
return charset;
}
@@ -151,5 +158,4 @@ public class AutoDetectReader extends BufferedReader {
source.setEncoding(charset.name());
return source;
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/CompositeDetector.java b/tika-core/src/main/java/org/apache/tika/detect/CompositeDetector.java
index ed5391854..13d5396d4 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/CompositeDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/CompositeDetector.java
@@ -23,29 +23,26 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.mime.MediaType;
import org.apache.tika.mime.MediaTypeRegistry;
import org.apache.tika.utils.StringUtils;
-/**
- * Content type detector that combines multiple different detection mechanisms.
- */
+/** Content type detector that combines multiple different detection mechanisms. */
public class CompositeDetector implements Detector {
- /**
- * Serial version UID
- */
+ /** Serial version UID */
private static final long serialVersionUID = 5980683158436430252L;
private final MediaTypeRegistry registry;
private final List<Detector> detectors;
- public CompositeDetector(MediaTypeRegistry registry, List<Detector> detectors,
- Collection<Class<? extends Detector>> excludeDetectors) {
+ public CompositeDetector(
+ MediaTypeRegistry registry,
+ List<Detector> detectors,
+ Collection<Class<? extends Detector>> excludeDetectors) {
if (excludeDetectors == null || excludeDetectors.isEmpty()) {
this.detectors = detectors;
} else {
@@ -78,8 +75,8 @@ public class CompositeDetector implements Detector {
}
MediaType type = MediaType.OCTET_STREAM;
- //we have to iterate through all detectors because the override detector may
- //be within a CompositeDetector
+ // we have to iterate through all detectors because the override detector may
+ // be within a CompositeDetector
for (Detector detector : getDetectors()) {
MediaType detected = detector.detect(input, metadata);
if (registry.isSpecializationOf(detected, type)) {
@@ -90,7 +87,6 @@ public class CompositeDetector implements Detector {
}
/**
- *
* @param metadata
* @return mediaType if a parseable mediatype was sent in via user or parser overrides
*/
@@ -111,20 +107,19 @@ public class CompositeDetector implements Detector {
}
return null;
}
- /**
- * Returns the component detectors.
- */
+
+ /** Returns the component detectors. */
public List<Detector> getDetectors() {
return Collections.unmodifiableList(detectors);
}
- private boolean isExcluded(Collection<Class<? extends Detector>> excludeDetectors,
- Class<? extends Detector> d) {
+ private boolean isExcluded(
+ Collection<Class<? extends Detector>> excludeDetectors, Class<? extends Detector> d) {
return excludeDetectors.contains(d) || assignableFrom(excludeDetectors, d);
}
- private boolean assignableFrom(Collection<Class<? extends Detector>> excludeDetectors,
- Class<? extends Detector> d) {
+ private boolean assignableFrom(
+ Collection<Class<? extends Detector>> excludeDetectors, Class<? extends Detector> d) {
for (Class<? extends Detector> e : excludeDetectors) {
if (e.isAssignableFrom(d)) {
return true;
diff --git a/tika-core/src/main/java/org/apache/tika/detect/CompositeEncodingDetector.java b/tika-core/src/main/java/org/apache/tika/detect/CompositeEncodingDetector.java
index 7db79ccc7..999ed60e9 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/CompositeEncodingDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/CompositeEncodingDetector.java
@@ -24,29 +24,25 @@ import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
public class CompositeEncodingDetector implements EncodingDetector, Serializable {
- /**
- * Serial version UID
- */
+ /** Serial version UID */
private static final long serialVersionUID = 5980683158436430252L;
private final List<EncodingDetector> detectors;
- public CompositeEncodingDetector(List<EncodingDetector> detectors,
- Collection<Class<? extends EncodingDetector>>
- excludeEncodingDetectors) {
+ public CompositeEncodingDetector(
+ List<EncodingDetector> detectors,
+ Collection<Class<? extends EncodingDetector>> excludeEncodingDetectors) {
this.detectors = new LinkedList<>();
for (EncodingDetector encodingDetector : detectors) {
if (!isExcluded(excludeEncodingDetectors, encodingDetector.getClass())) {
this.detectors.add(encodingDetector);
}
}
-
}
public CompositeEncodingDetector(List<EncodingDetector> detectors) {
@@ -55,7 +51,7 @@ public class CompositeEncodingDetector implements EncodingDetector, Serializable
}
/**
- * @param input text document input stream, or <code>null</code>
+ * @param input text document input stream, or <code>null</code>
* @param metadata input metadata for the document
* @return the detected Charset or null if no charset could be detected
* @throws IOException
@@ -66,9 +62,10 @@ public class CompositeEncodingDetector implements EncodingDetector, Serializable
Charset detected = detector.detect(input, metadata);
if (detected != null) {
metadata.set(TikaCoreProperties.DETECTED_ENCODING, detected.name());
- //if this has been set by a leaf detector, do not overwrite
- if (! detector.getClass().getSimpleName().equals("CompositeEncodingDetector")) {
- metadata.set(TikaCoreProperties.ENCODING_DETECTOR,
+ // if this has been set by a leaf detector, do not overwrite
+ if (!detector.getClass().getSimpleName().equals("CompositeEncodingDetector")) {
+ metadata.set(
+ TikaCoreProperties.ENCODING_DETECTOR,
detector.getClass().getSimpleName());
}
return detected;
@@ -84,8 +81,8 @@ public class CompositeEncodingDetector implements EncodingDetector, Serializable
private boolean isExcluded(
Collection<Class<? extends EncodingDetector>> excludeEncodingDetectors,
Class<? extends EncodingDetector> encodingDetector) {
- return excludeEncodingDetectors.contains(encodingDetector) ||
- assignableFrom(excludeEncodingDetectors, encodingDetector);
+ return excludeEncodingDetectors.contains(encodingDetector)
+ || assignableFrom(excludeEncodingDetectors, encodingDetector);
}
private boolean assignableFrom(
diff --git a/tika-core/src/main/java/org/apache/tika/detect/DefaultDetector.java b/tika-core/src/main/java/org/apache/tika/detect/DefaultDetector.java
index 038d274e4..755c1767e 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/DefaultDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/DefaultDetector.java
@@ -20,33 +20,32 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.imageio.spi.ServiceRegistry;
-
import org.apache.tika.config.ServiceLoader;
import org.apache.tika.mime.MimeTypes;
import org.apache.tika.utils.ServiceLoaderUtils;
/**
- * A composite detector based on all the {@link Detector} implementations
- * available through the {@link ServiceRegistry service provider mechanism}.
- * <p>
- * Detectors are loaded and returned in a specified order, of user supplied
- * followed by non-MimeType Tika, followed by the Tika MimeType class.
- * If you need to control the order of the Detectors, you should instead
- * construct your own {@link CompositeDetector} and pass in the list
+ * A composite detector based on all the {@link Detector} implementations available through the
+ * {@link ServiceRegistry service provider mechanism}.
+ *
+ * <p>Detectors are loaded and returned in a specified order, of user supplied followed by
+ * non-MimeType Tika, followed by the Tika MimeType class. If you need to control the order of the
+ * Detectors, you should instead construct your own {@link CompositeDetector} and pass in the list
* of Detectors in the required order.
*
* @since Apache Tika 0.9
*/
public class DefaultDetector extends CompositeDetector {
- /**
- * Serial version UID
- */
+ /** Serial version UID */
private static final long serialVersionUID = -8170114575326908027L;
- private transient final ServiceLoader loader;
- public DefaultDetector(MimeTypes types, ServiceLoader loader,
- Collection<Class<? extends Detector>> excludeDetectors) {
+ private final transient ServiceLoader loader;
+
+ public DefaultDetector(
+ MimeTypes types,
+ ServiceLoader loader,
+ Collection<Class<? extends Detector>> excludeDetectors) {
super(types.getMediaTypeRegistry(), getDefaultDetectors(types, loader, excludeDetectors));
this.loader = loader;
}
@@ -72,25 +71,24 @@ public class DefaultDetector extends CompositeDetector {
}
/**
- * Finds all statically loadable detectors and sort the list by name,
- * rather than discovery order. Detectors are used in the given order,
- * so put the Tika parsers last so that non-Tika (user supplied)
- * parsers can take precedence.
- * <p>
- * If an {@link OverrideDetector} is loaded, it takes precedence over
- * all other detectors.
+ * Finds all statically loadable detectors and sort the list by name, rather than discovery
+ * order. Detectors are used in the given order, so put the Tika parsers last so that non-Tika
+ * (user supplied) parsers can take precedence.
+ *
+ * <p>If an {@link OverrideDetector} is loaded, it takes precedence over all other detectors.
*
* @param loader service loader
* @return ordered list of statically loadable detectors
*/
- private static List<Detector> getDefaultDetectors(MimeTypes types, ServiceLoader loader,
- Collection<Class<? extends Detector>>
- excludeDetectors) {
+ private static List<Detector> getDefaultDetectors(
+ MimeTypes types,
+ ServiceLoader loader,
+ Collection<Class<? extends Detector>> excludeDetectors) {
List<Detector> detectors =
loader.loadStaticServiceProviders(Detector.class, excludeDetectors);
ServiceLoaderUtils.sortLoadedClasses(detectors);
- //look for the override index and put that first
+ // look for the override index and put that first
int overrideIndex = -1;
int i = 0;
for (Detector detector : detectors) {
@@ -123,5 +121,4 @@ public class DefaultDetector extends CompositeDetector {
return super.getDetectors();
}
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/DefaultEncodingDetector.java b/tika-core/src/main/java/org/apache/tika/detect/DefaultEncodingDetector.java
index 4cf64d5e9..347cd4db4 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/DefaultEncodingDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/DefaultEncodingDetector.java
@@ -19,19 +19,18 @@ package org.apache.tika.detect;
import java.util.Collection;
import javax.imageio.spi.ServiceRegistry;
-
import org.apache.tika.config.ServiceLoader;
/**
- * A composite encoding detector based on all the {@link EncodingDetector} implementations
- * available through the {@link ServiceRegistry service provider mechanism}. Those
- * loaded via the service provider mechanism are ordered by how they appear in the
- * file, if there is a single service file. If multiple, there is no guarantee of order.
- * <p>
+ * A composite encoding detector based on all the {@link EncodingDetector} implementations available
+ * through the {@link ServiceRegistry service provider mechanism}. Those loaded via the service
+ * provider mechanism are ordered by how they appear in the file, if there is a single service file.
+ * If multiple, there is no guarantee of order.
+ *
* <p>
- * If you need to control the order of the Detectors, you should instead
- * construct your own {@link CompositeDetector} and pass in the list
- * of Detectors in the required order.
+ *
+ * <p>If you need to control the order of the Detectors, you should instead construct your own
+ * {@link CompositeDetector} and pass in the list of Detectors in the required order.
*
* @since Apache Tika 1.15
*/
@@ -45,10 +44,9 @@ public class DefaultEncodingDetector extends CompositeEncodingDetector {
super(loader.loadServiceProviders(EncodingDetector.class));
}
- public DefaultEncodingDetector(ServiceLoader loader,
- Collection<Class<? extends EncodingDetector>>
- excludeEncodingDetectors) {
+ public DefaultEncodingDetector(
+ ServiceLoader loader,
+ Collection<Class<? extends EncodingDetector>> excludeEncodingDetectors) {
super(loader.loadServiceProviders(EncodingDetector.class), excludeEncodingDetectors);
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/DefaultProbDetector.java b/tika-core/src/main/java/org/apache/tika/detect/DefaultProbDetector.java
index b7df0b6fa..c4de0667b 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/DefaultProbDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/DefaultProbDetector.java
@@ -17,22 +17,19 @@
package org.apache.tika.detect;
import java.util.List;
-
import org.apache.tika.config.ServiceLoader;
import org.apache.tika.mime.MimeTypes;
import org.apache.tika.mime.ProbabilisticMimeDetectionSelector;
import org.apache.tika.utils.ServiceLoaderUtils;
/**
- * A version of {@link DefaultDetector} for probabilistic mime
- * detectors, which use statistical techniques to blend the
- * results of differing underlying detectors when attempting
- * to detect the type of a given file.
- * TODO Link to documentation on configuring these probabilities
+ * A version of {@link DefaultDetector} for probabilistic mime detectors, which use statistical
+ * techniques to blend the results of differing underlying detectors when attempting to detect the
+ * type of a given file. TODO Link to documentation on configuring these probabilities
*/
public class DefaultProbDetector extends CompositeDetector {
private static final long serialVersionUID = -8836240060532323352L;
- private transient final ServiceLoader loader;
+ private final transient ServiceLoader loader;
public DefaultProbDetector(ProbabilisticMimeDetectionSelector sel, ServiceLoader loader) {
super(sel.getMediaTypeRegistry(), getDefaultDetectors(sel, loader));
@@ -55,8 +52,8 @@ public class DefaultProbDetector extends CompositeDetector {
this(MimeTypes.getDefaultMimeTypes());
}
- private static List<Detector> getDefaultDetectors(ProbabilisticMimeDetectionSelector sel,
- ServiceLoader loader) {
+ private static List<Detector> getDefaultDetectors(
+ ProbabilisticMimeDetectionSelector sel, ServiceLoader loader) {
List<Detector> detectors = loader.loadStaticServiceProviders(Detector.class);
ServiceLoaderUtils.sortLoadedClasses(detectors);
detectors.add(sel);
diff --git a/tika-core/src/main/java/org/apache/tika/detect/Detector.java b/tika-core/src/main/java/org/apache/tika/detect/Detector.java
index fc237aa5a..ead745a3c 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/Detector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/Detector.java
@@ -19,41 +19,35 @@ package org.apache.tika.detect;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
/**
- * Content type detector. Implementations of this interface use various
- * heuristics to detect the content type of a document based on given
- * input metadata or the first few bytes of the document stream.
+ * Content type detector. Implementations of this interface use various heuristics to detect the
+ * content type of a document based on given input metadata or the first few bytes of the document
+ * stream.
*
* @since Apache Tika 0.3
*/
public interface Detector extends Serializable {
/**
- * Detects the content type of the given input document. Returns
- * <code>application/octet-stream</code> if the type of the document
- * can not be detected.
- * <p>
- * If the document input stream is not available, then the first
- * argument may be <code>null</code>. Otherwise the detector may
- * read bytes from the start of the stream to help in type detection.
- * The given stream is guaranteed to support the
- * {@link InputStream#markSupported() mark feature} and the detector
- * is expected to {@link InputStream#mark(int) mark} the stream before
- * reading any bytes from it, and to {@link InputStream#reset() reset}
- * the stream before returning. The stream must not be closed by the
- * detector.
- * <p>
- * The given input metadata is only read, not modified, by the detector.
+ * Detects the content type of the given input document. Returns <code>application/octet-stream
+ * </code> if the type of the document can not be detected.
+ *
+ * <p>If the document input stream is not available, then the first argument may be <code>null
+ * </code>. Otherwise the detector may read bytes from the start of the stream to help in type
+ * detection. The given stream is guaranteed to support the {@link InputStream#markSupported()
+ * mark feature} and the detector is expected to {@link InputStream#mark(int) mark} the stream
+ * before reading any bytes from it, and to {@link InputStream#reset() reset} the stream before
+ * returning. The stream must not be closed by the detector.
*
- * @param input document input stream, or <code>null</code>
+ * <p>The given input metadata is only read, not modified, by the detector.
+ *
+ * @param input document input stream, or <code>null</code>
* @param metadata input metadata for the document
* @return detected media type, or <code>application/octet-stream</code>
* @throws IOException if the document input stream could not be read
*/
MediaType detect(InputStream input, Metadata metadata) throws IOException;
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/EmptyDetector.java b/tika-core/src/main/java/org/apache/tika/detect/EmptyDetector.java
index 9f996301c..c76d79e21 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/EmptyDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/EmptyDetector.java
@@ -18,22 +18,16 @@ package org.apache.tika.detect;
import java.io.IOException;
import java.io.InputStream;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
-/**
- * Dummy detector that returns application/octet-stream for all documents.
- */
+/** Dummy detector that returns application/octet-stream for all documents. */
public class EmptyDetector implements Detector {
- /**
- * Singleton instance of this class.
- */
+ /** Singleton instance of this class. */
public static final EmptyDetector INSTANCE = new EmptyDetector();
public MediaType detect(InputStream input, Metadata metadata) throws IOException {
return MediaType.OCTET_STREAM;
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/EncodingDetector.java b/tika-core/src/main/java/org/apache/tika/detect/EncodingDetector.java
index 9dbad4c27..be6001844 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/EncodingDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/EncodingDetector.java
@@ -20,39 +20,35 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.charset.Charset;
-
import org.apache.tika.metadata.Metadata;
/**
- * Character encoding detector. Implementations of this interface use
- * various heuristics to detect the character encoding of a text document
- * based on given input metadata or the first few bytes of the document stream.
+ * Character encoding detector. Implementations of this interface use various heuristics to detect
+ * the character encoding of a text document based on given input metadata or the first few bytes of
+ * the document stream.
*
* @since Apache Tika 0.4
*/
public interface EncodingDetector extends Serializable {
/**
- * Detects the character encoding of the given text document, or
- * <code>null</code> if the encoding of the document can not be detected.
- * <p>
- * If the document input stream is not available, then the first
- * argument may be <code>null</code>. Otherwise the detector may
- * read bytes from the start of the stream to help in encoding detection.
- * The given stream is guaranteed to support the
- * {@link InputStream#markSupported() mark feature} and the detector
- * is expected to {@link InputStream#mark(int) mark} the stream before
- * reading any bytes from it, and to {@link InputStream#reset() reset}
- * the stream before returning. The stream must not be closed by the
+ * Detects the character encoding of the given text document, or <code>null</code> if the
+ * encoding of the document can not be detected.
+ *
+ * <p>If the document input stream is not available, then the first argument may be <code>null
+ * </code>. Otherwise the detector may read bytes from the start of the stream to help in
+ * encoding detection. The given stream is guaranteed to support the {@link
+ * InputStream#markSupported() mark feature} and the detector is expected to {@link
+ * InputStream#mark(int) mark} the stream before reading any bytes from it, and to {@link
+ * InputStream#reset() reset} the stream before returning. The stream must not be closed by the
* detector.
- * <p>
- * The given input metadata is only read, not modified, by the detector.
*
- * @param input text document input stream, or <code>null</code>
+ * <p>The given input metadata is only read, not modified, by the detector.
+ *
+ * @param input text document input stream, or <code>null</code>
* @param metadata input metadata for the document
* @return detected character encoding, or <code>null</code>
* @throws IOException if the document input stream could not be read
*/
Charset detect(InputStream input, Metadata metadata) throws IOException;
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/FileCommandDetector.java b/tika-core/src/main/java/org/apache/tika/detect/FileCommandDetector.java
index 42349faec..a3a721153 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/FileCommandDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/FileCommandDetector.java
@@ -22,10 +22,6 @@ import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import org.apache.tika.config.Field;
import org.apache.tika.io.BoundedInputStream;
import org.apache.tika.io.TemporaryResources;
@@ -38,26 +34,27 @@ import org.apache.tika.parser.external.ExternalParser;
import org.apache.tika.utils.FileProcessResult;
import org.apache.tika.utils.ProcessUtils;
import org.apache.tika.utils.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * This runs the linux 'file' command against a file. If
- * this is called on a TikaInputStream, it will use the underlying Path
- * or spool the full file to disk and then run file against that.
- * <p>
- * If this is run against any other type of InputStream, it will spool
- * up to {@link #maxBytes} to disk and then run the detector.
- * <p>
- * As with all detectors, mark must be supported.
- * <p>
- * If you want to use file's mime type in the parse, e.g.
- * to select the parser in AutoDetectParser, set {@link FileCommandDetector#setUseMime(boolean)}
- * to true. The default behavior is to store the value as {@link FileCommandDetector#FILE_MIME}
- * but rely on other detectors for the "active" mime used by Tika.
+ * This runs the linux 'file' command against a file. If this is called on a TikaInputStream, it
+ * will use the underlying Path or spool the full file to disk and then run file against that.
+ *
+ * <p>If this is run against any other type of InputStream, it will spool up to {@link #maxBytes} to
+ * disk and then run the detector.
+ *
+ * <p>As with all detectors, mark must be supported.
+ *
+ * <p>If you want to use file's mime type in the parse, e.g. to select the parser in
+ * AutoDetectParser, set {@link FileCommandDetector#setUseMime(boolean)} to true. The default
+ * behavior is to store the value as {@link FileCommandDetector#FILE_MIME} but rely on other
+ * detectors for the "active" mime used by Tika.
*/
public class FileCommandDetector implements Detector {
- //TODO: file has some diff mimes names for some very common mimes
- //should we map file mimes to Tika mimes, e.g. text/xml -> application/xml??
+ // TODO: file has some diff mimes names for some very common mimes
+ // should we map file mimes to Tika mimes, e.g. text/xml -> application/xml??
public static Property FILE_MIME = Property.externalText("file:mime");
private static final Logger LOGGER = LoggerFactory.getLogger(FileCommandDetector.class);
@@ -75,14 +72,13 @@ public class FileCommandDetector implements Detector {
return checkHasFile(DEFAULT_FILE_COMMAND_PATH);
}
-
public static boolean checkHasFile(String fileCommandPath) {
- String[] commandline = new String[]{fileCommandPath, "-v"};
+ String[] commandline = new String[] {fileCommandPath, "-v"};
return ExternalParser.check(commandline);
}
/**
- * @param input document input stream, or <code>null</code>
+ * @param input document input stream, or <code>null</code>
* @param metadata input metadata for the document
* @return mime as identified by the file command or application/octet-stream otherwise
* @throws IOException
@@ -101,8 +97,8 @@ public class FileCommandDetector implements Detector {
}
TikaInputStream tis = TikaInputStream.cast(input);
if (tis != null) {
- //spool the full file to disk, if called with a TikaInputStream
- //and there is no underlying file
+ // spool the full file to disk, if called with a TikaInputStream
+ // and there is no underlying file
return detectOnPath(tis.getPath(), metadata);
}
@@ -119,8 +115,12 @@ public class FileCommandDetector implements Detector {
private MediaType detectOnPath(Path path, Metadata metadata) throws IOException {
String[] args =
- new String[]{ProcessUtils.escapeCommandLine(fileCommandPath), "-b", "--mime-type",
- ProcessUtils.escapeCommandLine(path.toAbsolutePath().toString())};
+ new String[] {
+ ProcessUtils.escapeCommandLine(fileCommandPath),
+ "-b",
+ "--mime-type",
+ ProcessUtils.escapeCommandLine(path.toAbsolutePath().toString())
+ };
ProcessBuilder builder = new ProcessBuilder(args);
FileProcessResult result = ProcessUtils.execute(builder, timeoutMs, 10000, 10000);
if (result.isTimeout()) {
@@ -149,8 +149,8 @@ public class FileCommandDetector implements Detector {
@Field
public void setFilePath(String fileCommandPath) {
- //this opens up a potential command vulnerability.
- //Don't ever let an untrusted user set this.
+ // this opens up a potential command vulnerability.
+ // Don't ever let an untrusted user set this.
this.fileCommandPath = fileCommandPath;
checkHasFile(this.fileCommandPath);
}
@@ -163,10 +163,10 @@ public class FileCommandDetector implements Detector {
public boolean isUseMime() {
return useMime;
}
+
/**
- * If this is not called on a TikaInputStream, this detector
- * will spool up to this many bytes to a file to be detected
- * by the 'file' command.
+ * If this is not called on a TikaInputStream, this detector will spool up to this many bytes to
+ * a file to be detected by the 'file' command.
*
* @param maxBytes
*/
@@ -179,5 +179,4 @@ public class FileCommandDetector implements Detector {
public void setTimeoutMs(long timeoutMs) {
this.timeoutMs = timeoutMs;
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/MagicDetector.java b/tika-core/src/main/java/org/apache/tika/detect/MagicDetector.java
index bb9ec1da0..b8d5205e2 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/MagicDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/MagicDetector.java
@@ -27,75 +27,72 @@ import java.nio.CharBuffer;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
/**
- * Content type detection based on magic bytes, i.e. type-specific patterns
- * near the beginning of the document input stream.
- * <p>
- * Because this works on bytes, not characters, by default any string
- * matching is done as ISO_8859_1. To use an explicit different
- * encoding, supply a type other than "string" / "stringignorecase"
+ * Content type detection based on magic bytes, i.e. type-specific patterns near the beginning of
+ * the document input stream.
+ *
+ * <p>Because this works on bytes, not characters, by default any string matching is done as
+ * ISO_8859_1. To use an explicit different encoding, supply a type other than "string" /
+ * "stringignorecase"
*
* @since Apache Tika 0.3
*/
public class MagicDetector implements Detector {
/**
- * The matching media type. Returned by the
- * {@link #detect(InputStream, Metadata)} method if a match is found.
+ * The matching media type. Returned by the {@link #detect(InputStream, Metadata)} method if a
+ * match is found.
*/
private final MediaType type;
- /**
- * Length of the comparison window.
- */
+
+ /** Length of the comparison window. */
private final int length;
+
/**
- * The magic match pattern. If this byte pattern is equal to the
- * possibly bit-masked bytes from the input stream, then the type
- * detection succeeds and the configured {@link #type} is returned.
+ * The magic match pattern. If this byte pattern is equal to the possibly bit-masked bytes from
+ * the input stream, then the type detection succeeds and the configured {@link #type} is
+ * returned.
*/
private final byte[] pattern;
+
/**
- * Length of the pattern, which in the case of regular expressions will
- * not be the same as the comparison window length.
+ * Length of the pattern, which in the case of regular expressions will not be the same as the
+ * comparison window length.
*/
private final int patternLength;
- /**
- * True if pattern is a regular expression, false otherwise.
- */
+
+ /** True if pattern is a regular expression, false otherwise. */
private final boolean isRegex;
- /**
- * True if we're doing a case-insensitive string match, false otherwise.
- */
+
+ /** True if we're doing a case-insensitive string match, false otherwise. */
private final boolean isStringIgnoreCase;
- /**
- * Bit mask that is applied to the source bytes before pattern matching.
- */
+
+ /** Bit mask that is applied to the source bytes before pattern matching. */
private final byte[] mask;
+
/**
- * First offset (inclusive) of the comparison window within the
- * document input stream. Greater than or equal to zero.
+ * First offset (inclusive) of the comparison window within the document input stream. Greater
+ * than or equal to zero.
*/
private final int offsetRangeBegin;
+
/**
- * Last offset (inclusive) of the comparison window within the document
- * input stream. Greater than or equal to the
- * {@link #offsetRangeBegin first offset}.
- * <p>
- * Note that this is <em>not</em> the offset of the last byte read from
- * the document stream. Instead, the last window of bytes to be compared
- * starts at this offset.
+ * Last offset (inclusive) of the comparison window within the document input stream. Greater
+ * than or equal to the {@link #offsetRangeBegin first offset}.
+ *
+ * <p>Note that this is <em>not</em> the offset of the last byte read from the document stream.
+ * Instead, the last window of bytes to be compared starts at this offset.
*/
private final int offsetRangeEnd;
/**
- * Creates a detector for input documents that have the exact given byte
- * pattern at the beginning of the document stream.
+ * Creates a detector for input documents that have the exact given byte pattern at the
+ * beginning of the document stream.
*
- * @param type matching media type
+ * @param type matching media type
* @param pattern magic match pattern
*/
public MagicDetector(MediaType type, byte[] pattern) {
@@ -103,42 +100,46 @@ public class MagicDetector implements Detector {
}
/**
- * Creates a detector for input documents that have the exact given byte
- * pattern at the given offset of the document stream.
+ * Creates a detector for input documents that have the exact given byte pattern at the given
+ * offset of the document stream.
*
- * @param type matching media type
+ * @param type matching media type
* @param pattern magic match pattern
- * @param offset offset of the pattern match
+ * @param offset offset of the pattern match
*/
public MagicDetector(MediaType type, byte[] pattern, int offset) {
this(type, pattern, null, offset, offset);
}
/**
- * Creates a detector for input documents that meet the specified magic
- * match. {@code pattern} must NOT be a regular expression.
- * Constructor maintained for legacy reasons.
+ * Creates a detector for input documents that meet the specified magic match. {@code pattern}
+ * must NOT be a regular expression. Constructor maintained for legacy reasons.
*/
- public MagicDetector(MediaType type, byte[] pattern, byte[] mask, int offsetRangeBegin,
- int offsetRangeEnd) {
+ public MagicDetector(
+ MediaType type, byte[] pattern, byte[] mask, int offsetRangeBegin, int offsetRangeEnd) {
this(type, pattern, mask, false, offsetRangeBegin, offsetRangeEnd);
}
- /**
- * Creates a detector for input documents that meet the specified
- * magic match.
- */
- public MagicDetector(MediaType type, byte[] pattern, byte[] mask, boolean isRegex,
- int offsetRangeBegin, int offsetRangeEnd) {
+ /** Creates a detector for input documents that meet the specified magic match. */
+ public MagicDetector(
+ MediaType type,
+ byte[] pattern,
+ byte[] mask,
+ boolean isRegex,
+ int offsetRangeBegin,
+ int offsetRangeEnd) {
this(type, pattern, mask, isRegex, false, offsetRangeBegin, offsetRangeEnd);
}
- /**
- * Creates a detector for input documents that meet the specified
- * magic match.
- */
- public MagicDetector(MediaType type, byte[] pattern, byte[] mask, boolean isRegex,
- boolean isStringIgnoreCase, int offsetRangeBegin, int offsetRangeEnd) {
+ /** Creates a detector for input documents that meet the specified magic match. */
+ public MagicDetector(
+ MediaType type,
+ byte[] pattern,
+ byte[] mask,
+ boolean isRegex,
+ boolean isStringIgnoreCase,
+ int offsetRangeBegin,
+ int offsetRangeEnd) {
if (type == null) {
throw new IllegalArgumentException("Matching media type is null");
} else if (pattern == null) {
@@ -183,8 +184,8 @@ public class MagicDetector implements Detector {
this.offsetRangeEnd = offsetRangeEnd;
}
- public static MagicDetector parse(MediaType mediaType, String type, String offset, String value,
- String mask) {
+ public static MagicDetector parse(
+ MediaType mediaType, String type, String offset, String value, String mask) {
int start = 0;
int end = 0;
if (offset != null) {
@@ -204,8 +205,14 @@ public class MagicDetector implements Detector {
maskBytes = decodeValue(mask, type);
}
- return new MagicDetector(mediaType, patternBytes, maskBytes, type.equals("regex"),
- type.equals("stringignorecase"), start, end);
+ return new MagicDetector(
+ mediaType,
+ patternBytes,
+ maskBytes,
+ type.equals("regex"),
+ type.equals("stringignorecase"),
+ start,
+ end);
}
private static byte[] decodeValue(String value, String type) {
@@ -241,29 +248,43 @@ public class MagicDetector implements Detector {
decoded = tmpVal.getBytes(UTF_8);
break;
case "host16":
- case "little16": {
- int i = Integer.parseInt(tmpVal, radix);
- decoded = new byte[]{(byte) (i & 0x00FF), (byte) (i >> 8)};
- break;
- }
- case "big16": {
- int i = Integer.parseInt(tmpVal, radix);
- decoded = new byte[]{(byte) (i >> 8), (byte) (i & 0x00FF)};
- break;
- }
+ case "little16":
+ {
+ int i = Integer.parseInt(tmpVal, radix);
+ decoded = new byte[] {(byte) (i & 0x00FF), (byte) (i >> 8)};
+ break;
+ }
+ case "big16":
+ {
+ int i = Integer.parseInt(tmpVal, radix);
+ decoded = new byte[] {(byte) (i >> 8), (byte) (i & 0x00FF)};
+ break;
+ }
case "host32":
- case "little32": {
- long i = Long.parseLong(tmpVal, radix);
- decoded = new byte[]{(byte) ((i & 0x000000FF)), (byte) ((i & 0x0000FF00) >> 8),
- (byte) ((i & 0x00FF0000) >> 16), (byte) ((i & 0xFF000000) >> 24)};
- break;
- }
- case "big32": {
- long i = Long.parseLong(tmpVal, radix);
- decoded = new byte[]{(byte) ((i & 0xFF000000) >> 24), (byte) ((i & 0x00FF0000) >> 16),
- (byte) ((i & 0x0000FF00) >> 8), (byte) ((i & 0x000000FF))};
- break;
- }
+ case "little32":
+ {
+ long i = Long.parseLong(tmpVal, radix);
+ decoded =
+ new byte[] {
+ (byte) ((i & 0x000000FF)),
+ (byte) ((i & 0x0000FF00) >> 8),
+ (byte) ((i & 0x00FF0000) >> 16),
+ (byte) ((i & 0xFF000000) >> 24)
+ };
+ break;
+ }
+ case "big32":
+ {
+ long i = Long.parseLong(tmpVal, radix);
+ decoded =
+ new byte[] {
+ (byte) ((i & 0xFF000000) >> 24),
+ (byte) ((i & 0x00FF0000) >> 16),
+ (byte) ((i & 0x0000FF00) >> 8),
+ (byte) ((i & 0x000000FF))
+ };
+ break;
+ }
}
return decoded;
}
@@ -295,8 +316,9 @@ public class MagicDetector implements Detector {
i++;
} else {
int j = i + 1;
- while ((j < i + 4) && (j < value.length()) &&
- (Character.isDigit(value.charAt(j)))) {
+ while ((j < i + 4)
+ && (j < value.length())
+ && (Character.isDigit(value.charAt(j)))) {
j++;
}
decoded.write(Short.decode("0" + value.substring(i + 1, j)).byteValue());
@@ -333,7 +355,7 @@ public class MagicDetector implements Detector {
}
/**
- * @param input document input stream, or <code>null</code>
+ * @param input document input stream, or <code>null</code>
* @param metadata ignored
*/
public MediaType detect(InputStream input, Metadata metadata) throws IOException {
@@ -425,13 +447,18 @@ public class MagicDetector implements Detector {
}
/**
- * Returns a string representation of the Detection Rule.
- * Should sort nicely by type and details, as we sometimes
- * compare these.
+ * Returns a string representation of the Detection Rule. Should sort nicely by type and
+ * details, as we sometimes compare these.
*/
public String toString() {
// Needs to be unique, as these get compared.
- return "Magic Detection for " + type + " looking for " + pattern.length + " bytes = " +
- this.pattern + " mask = " + this.mask;
+ return "Magic Detection for "
+ + type
+ + " looking for "
+ + pattern.length
+ + " bytes = "
+ + this.pattern
+ + " mask = "
+ + this.mask;
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/NNExampleModelDetector.java b/tika-core/src/main/java/org/apache/tika/detect/NNExampleModelDetector.java
index bcbf48feb..76fe42dad 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/NNExampleModelDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/NNExampleModelDetector.java
@@ -27,12 +27,10 @@ import java.io.InputStreamReader;
import java.net.URL;
import java.nio.file.Path;
import java.util.Objects;
-
+import org.apache.tika.mime.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.tika.mime.MediaType;
-
public class NNExampleModelDetector extends TrainedModelDetector {
private static final String EXAMPLE_NNMODEL_FILE = "tika-example.nnmodel";
@@ -68,16 +66,13 @@ public class NNExampleModelDetector extends TrainedModelDetector {
// add this model into map of trained models.
super.registerModels(nnBuilder.getType(), nnBuilder.build());
}
-
}
} catch (IOException e) {
throw new RuntimeException("Unable to read the default media type registry", e);
}
}
- /**
- * this method gets overwritten to register load neural network models
- */
+ /** this method gets overwritten to register load neural network models */
@Override
public void loadDefaultModels(ClassLoader classLoader) {
if (classLoader == null) {
@@ -91,22 +86,20 @@ public class NNExampleModelDetector extends TrainedModelDetector {
// Get the core URL, and all the extensions URLs
URL modelURL = classLoader.getResource(classPrefix + EXAMPLE_NNMODEL_FILE);
- Objects.requireNonNull(modelURL,
- "required resource " + classPrefix + EXAMPLE_NNMODEL_FILE + " not found");
+ Objects.requireNonNull(
+ modelURL, "required resource " + classPrefix + EXAMPLE_NNMODEL_FILE + " not found");
try (InputStream stream = modelURL.openStream()) {
loadDefaultModels(stream);
} catch (IOException e) {
throw new RuntimeException("Unable to read the default media type registry", e);
}
-
}
/**
- * read the comments where the model configuration is written, e.g the
- * number of inputs, hiddens and output please ensure the first char in the
- * given string is # In this example grb model file, there are 4 elements 1)
- * type 2) number of input units 3) number of hidden units. 4) number of
- * output units.
+ * read the comments where the model configuration is written, e.g the number of inputs, hiddens
+ * and output please ensure the first char in the given string is # In this example grb model
+ * file, there are 4 elements 1) type 2) number of input units 3) number of hidden units. 4)
+ * number of output units.
*/
private void readDescription(final NNTrainedModelBuilder builder, final String line) {
int numInputs;
@@ -130,8 +123,8 @@ public class NNExampleModelDetector extends TrainedModelDetector {
}
/**
- * Read the next line for the model parameters and populate the build which
- * later will be used to instantiate the instance of TrainedModel
+ * Read the next line for the model parameters and populate the build which later will be used
+ * to instantiate the instance of TrainedModel
*
* @param builder
* @param line
diff --git a/tika-core/src/main/java/org/apache/tika/detect/NNTrainedModel.java b/tika-core/src/main/java/org/apache/tika/detect/NNTrainedModel.java
index 73ee560db..c0f06e984 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/NNTrainedModel.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/NNTrainedModel.java
@@ -25,8 +25,8 @@ public class NNTrainedModel extends TrainedModel {
private final float[][] Theta1;
private final float[][] Theta2;
- public NNTrainedModel(final int nInput, final int nHidden, final int nOutput,
- final float[] nn_params) {
+ public NNTrainedModel(
+ final int nInput, final int nHidden, final int nOutput, final float[] nn_params) {
this.numOfInputs = nInput;
this.numOfHidden = nHidden;
this.numOfOutputs = nOutput;
@@ -64,8 +64,7 @@ public class NNTrainedModel extends TrainedModel {
}
/**
- * The given input vector of unseen is m=(256 + 1) * n= 1 this returns a
- * prediction probability
+ * The given input vector of unseen is m=(256 + 1) * n= 1 this returns a prediction probability
*/
@Override
public float predict(float[] unseen) {
@@ -74,7 +73,7 @@ public class NNTrainedModel extends TrainedModel {
int i, j;
int m = this.Theta1.length;
int n = this.Theta1[0].length;
- float[] hh = new float[m + 1];// hidden unit summation
+ float[] hh = new float[m + 1]; // hidden unit summation
hh[0] = 1;
for (i = 0; i < m; i++) {
double h = 0;
diff --git a/tika-core/src/main/java/org/apache/tika/detect/NNTrainedModelBuilder.java b/tika-core/src/main/java/org/apache/tika/detect/NNTrainedModelBuilder.java
index 9b4eab385..f710a9d5e 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/NNTrainedModelBuilder.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/NNTrainedModelBuilder.java
@@ -15,7 +15,6 @@
* limitations under the License.
*/
-
package org.apache.tika.detect;
import org.apache.tika.mime.MediaType;
diff --git a/tika-core/src/main/java/org/apache/tika/detect/NameDetector.java b/tika-core/src/main/java/org/apache/tika/detect/NameDetector.java
index 36d01e171..2f49ec31e 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/NameDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/NameDetector.java
@@ -23,37 +23,33 @@ import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.regex.Pattern;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.mime.MediaType;
/**
- * Content type detection based on the resource name. An instance of this
- * class contains a set of regular expression patterns that are matched
- * against the resource name potentially given as a part of the input metadata.
- * <p>
- * If a pattern matches the given name, then the media type associated with
- * that pattern is returned as the likely content type of the input document.
- * Otherwise the returned type is <code>application/octet-stream</code>.
- * <p>
- * See the {@link #detect(InputStream, Metadata)} method for more details
- * of the matching algorithm.
+ * Content type detection based on the resource name. An instance of this class contains a set of
+ * regular expression patterns that are matched against the resource name potentially given as a
+ * part of the input metadata.
+ *
+ * <p>If a pattern matches the given name, then the media type associated with that pattern is
+ * returned as the likely content type of the input document. Otherwise the returned type is <code>
+ * application/octet-stream</code>.
+ *
+ * <p>See the {@link #detect(InputStream, Metadata)} method for more details of the matching
+ * algorithm.
*
* @since Apache Tika 0.3
*/
public class NameDetector implements Detector {
- /**
- * The regular expression patterns used for type detection.
- */
+ /** The regular expression patterns used for type detection. */
private final Map<Pattern, MediaType> patterns;
/**
- * Creates a new content type detector based on the given name patterns.
- * The given pattern map is not copied, so the caller may update the
- * mappings even after this detector instance has been created. However,
- * the map <em>must not be concurrently modified</em> while this instance
+ * Creates a new content type detector based on the given name patterns. The given pattern map
+ * is not copied, so the caller may update the mappings even after this detector instance has
+ * been created. However, the map <em>must not be concurrently modified</em> while this instance
* is used for type detection.
*
* @param patterns map from name patterns to corresponding media types
@@ -63,34 +59,25 @@ public class NameDetector implements Detector {
}
/**
- * Detects the content type of an input document based on the document
- * name given in the input metadata. The RESOURCE_NAME_KEY attribute of
- * the given input metadata is expected to contain the name (normally
- * a file name or a URL) of the input document.
- * <p>
- * If a resource name is given, then it is first processed as follows.
+ * Detects the content type of an input document based on the document name given in the input
+ * metadata. The RESOURCE_NAME_KEY attribute of the given input metadata is expected to contain
+ * the name (normally a file name or a URL) of the input document.
+ *
+ * <p>If a resource name is given, then it is first processed as follows.
+ *
* <ol>
- * <li>
- * Potential URL query (?...) and fragment identifier (#...)
- * parts are removed from the end of the resource name.
- * </li>
- * <li>
- * Potential leading path elements (up to the last slash or backslash)
- * are removed from the beginning of the resource name.
- * </li>
- * <li>
- * Potential URL encodings (%nn, in UTF-8) are decoded.
- * </li>
- * <li>
- * Any leading and trailing whitespace is removed.
- * </li>
+ * <li>Potential URL query (?...) and fragment identifier (#...) parts are removed from the
+ * end of the resource name.
+ * <li>Potential leading path elements (up to the last slash or backslash) are removed from
+ * the beginning of the resource name.
+ * <li>Potential URL encodings (%nn, in UTF-8) are decoded.
+ * <li>Any leading and trailing whitespace is removed.
* </ol>
- * <p>
- * The resulting name string (if any) is then matched in sequence against
- * all the configured name patterns. If a match is found, then the (first)
- * matching media type is returned.
*
- * @param input ignored
+ * <p>The resulting name string (if any) is then matched in sequence against all the configured
+ * name patterns. If a match is found, then the (first) matching media type is returned.
+ *
+ * @param input ignored
* @param metadata input metadata, possibly with a RESOURCE_NAME_KEY value
* @return detected media type, or <code>application/octet-stream</code>
*/
@@ -147,5 +134,4 @@ public class NameDetector implements Detector {
return MediaType.OCTET_STREAM;
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/NonDetectingEncodingDetector.java b/tika-core/src/main/java/org/apache/tika/detect/NonDetectingEncodingDetector.java
index 896a79531..a473cffaf 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/NonDetectingEncodingDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/NonDetectingEncodingDetector.java
@@ -21,24 +21,17 @@ import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
-
import org.apache.tika.config.Field;
import org.apache.tika.metadata.Metadata;
-/**
- * Always returns the charset passed in via the initializer
- */
+/** Always returns the charset passed in via the initializer */
public class NonDetectingEncodingDetector implements EncodingDetector {
- //would have preferred final, but need mutability for
- //loading via TikaConfig
+ // would have preferred final, but need mutability for
+ // loading via TikaConfig
private Charset charset = StandardCharsets.UTF_8;
- /**
- * Sets charset to UTF-8.
- */
- public NonDetectingEncodingDetector() {
-
- }
+ /** Sets charset to UTF-8. */
+ public NonDetectingEncodingDetector() {}
public NonDetectingEncodingDetector(Charset charset) {
this.charset = charset;
diff --git a/tika-core/src/main/java/org/apache/tika/detect/OverrideDetector.java b/tika-core/src/main/java/org/apache/tika/detect/OverrideDetector.java
index b6c5a41f8..ee2944d22 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/OverrideDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/OverrideDetector.java
@@ -18,17 +18,16 @@ package org.apache.tika.detect;
import java.io.IOException;
import java.io.InputStream;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.mime.MediaType;
/**
- * Use this to force a content type detection via the
- * {@link TikaCoreProperties#CONTENT_TYPE_USER_OVERRIDE} key in the metadata object.
- * <p>
- * This is also required to override detection by some parsers
- * via {@link TikaCoreProperties#CONTENT_TYPE_PARSER_OVERRIDE}.
+ * Use this to force a content type detection via the {@link
+ * TikaCoreProperties#CONTENT_TYPE_USER_OVERRIDE} key in the metadata object.
+ *
+ * <p>This is also required to override detection by some parsers via {@link
+ * TikaCoreProperties#CONTENT_TYPE_PARSER_OVERRIDE}.
*
* @deprecated after 2.5.0 this functionality was moved to the CompositeDetector
*/
diff --git a/tika-core/src/main/java/org/apache/tika/detect/TextDetector.java b/tika-core/src/main/java/org/apache/tika/detect/TextDetector.java
index 96583be7c..8cfad3f56 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/TextDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/TextDetector.java
@@ -19,46 +19,39 @@ package org.apache.tika.detect;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
/**
- * Content type detection of plain text documents. This detector looks at the
- * beginning of the document input stream and considers the document to be
- * a text document if no ASCII (ISO-Latin-1, UTF-8, etc.) control bytes are
- * found. As a special case some control bytes (up to 2% of all characters)
- * are also allowed in a text document if it also contains no or just a few
- * (less than 10%) characters above the 7-bit ASCII range.
- * <p>
- * Note that text documents with a character encoding like UTF-16 are better
- * detected with {@link MagicDetector} and an appropriate magic byte pattern.
+ * Content type detection of plain text documents. This detector looks at the beginning of the
+ * document input stream and considers the document to be a text document if no ASCII (ISO-Latin-1,
+ * UTF-8, etc.) control bytes are found. As a special case some control bytes (up to 2% of all
+ * characters) are also allowed in a text document if it also contains no or just a few (less than
+ * 10%) characters above the 7-bit ASCII range.
+ *
+ * <p>Note that text documents with a character encoding like UTF-16 are better detected with {@link
+ * MagicDetector} and an appropriate magic byte pattern.
*
* @since Apache Tika 0.3
*/
public class TextDetector implements Detector {
- /**
- * Serial version UID
- */
+ /** Serial version UID */
private static final long serialVersionUID = 4774601079503507765L;
- /**
- * The number of bytes from the beginning of the document stream
- * to test for control bytes.
- */
+ /** The number of bytes from the beginning of the document stream to test for control bytes. */
private static final int DEFAULT_NUMBER_OF_BYTES_TO_TEST = 512;
/**
- * Lookup table for all the ASCII/ISO-Latin/UTF-8/etc. control bytes
- * in the range below 0x20 (the space character). If an entry in this
- * table is <code>true</code> then that byte is very unlikely to occur
- * in a plain text document.
- * <p>
- * The contents of this lookup table are based on the following definition
- * from section 4 of the "Content-Type Processing Model" Internet-draft
- * (<a href="http://webblaze.cs.berkeley.edu/2009/mime-sniff/mime-sniff.txt"
+ * Lookup table for all the ASCII/ISO-Latin/UTF-8/etc. control bytes in the range below 0x20
+ * (the space character). If an entry in this table is <code>true</code> then that byte is very
+ * unlikely to occur in a plain text document.
+ *
+ * <p>The contents of this lookup table are based on the following definition from section 4 of
+ * the "Content-Type Processing Model" Internet-draft (<a
+ * href="http://webblaze.cs.berkeley.edu/2009/mime-sniff/mime-sniff.txt"
* >draft-abarth-mime-sniff-01</a>).
+ *
* <pre>
* +-------------------------+
* | Binary data byte ranges |
@@ -86,29 +79,29 @@ public class TextDetector implements Detector {
private final int bytesToTest;
/**
- * Constructs a {@link TextDetector} which will look at the default number
- * of bytes from the beginning of the document.
+ * Constructs a {@link TextDetector} which will look at the default number of bytes from the
+ * beginning of the document.
*/
public TextDetector() {
this(DEFAULT_NUMBER_OF_BYTES_TO_TEST);
}
/**
- * Constructs a {@link TextDetector} which will look at a given number of
- * bytes from the beginning of the document.
+ * Constructs a {@link TextDetector} which will look at a given number of bytes from the
+ * beginning of the document.
*/
public TextDetector(int bytesToTest) {
this.bytesToTest = bytesToTest;
}
/**
- * Looks at the beginning of the document input stream to determine
- * whether the document is text or not.
+ * Looks at the beginning of the document input stream to determine whether the document is text
+ * or not.
*
- * @param input document input stream, or <code>null</code>
+ * @param input document input stream, or <code>null</code>
* @param metadata ignored
- * @return "text/plain" if the input stream suggest a text document,
- * "application/octet-stream" otherwise
+ * @return "text/plain" if the input stream suggest a text document, "application/octet-stream"
+ * otherwise
*/
public MediaType detect(InputStream input, Metadata metadata) throws IOException {
if (input == null) {
@@ -137,5 +130,4 @@ public class TextDetector implements Detector {
input.reset();
}
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/TextStatistics.java b/tika-core/src/main/java/org/apache/tika/detect/TextStatistics.java
index 50f8d790a..29252ccd6 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/TextStatistics.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/TextStatistics.java
@@ -35,11 +35,11 @@ public class TextStatistics {
}
/**
- * Checks whether at least one byte was seen and that the bytes that
- * were seen were mostly plain text (i.e. < 2% control, > 90% ASCII range).
+ * Checks whether at least one byte was seen and that the bytes that were seen were mostly plain
+ * text (i.e. < 2% control, > 90% ASCII range).
*
- * @return <code>true</code> if the seen bytes were mostly safe ASCII,
- * <code>false</code> otherwise
+ * @return <code>true</code> if the seen bytes were mostly safe ASCII, <code>false</code>
+ * otherwise
* @see <a href="https://issues.apache.org/jira/browse/TIKA-483">TIKA-483</a>
* @see <a href="https://issues.apache.org/jira/browse/TIKA-688">TIKA-688</a>
*/
@@ -53,8 +53,7 @@ public class TextStatistics {
/**
* Checks whether the observed byte stream looks like UTF-8 encoded text.
*
- * @return <code>true</code> if the seen bytes look like UTF-8,
- * <code>false</code> otherwise
+ * @return <code>true</code> if the seen bytes look like UTF-8, <code>false</code> otherwise
* @since Apache Tika 1.3
*/
public boolean looksLikeUTF8() {
@@ -63,16 +62,18 @@ public class TextStatistics {
int safe = countSafeControl();
int expectedContinuation = 0;
- int[] leading = new int[]{count(0xc0, 0xe0), count(0xe0, 0xf0), count(0xf0, 0xf8)};
+ int[] leading = new int[] {count(0xc0, 0xe0), count(0xe0, 0xf0), count(0xf0, 0xf8)};
for (int i = 0; i < leading.length; i++) {
utf8 += leading[i];
expectedContinuation += (i + 1) * leading[i];
}
int continuation = count(0x80, 0xc0);
- return utf8 > 0 && continuation <= expectedContinuation &&
- continuation >= expectedContinuation - 3 && count(0xf8, 0x100) == 0 &&
- (control - safe) * 100 < utf8 * 2;
+ return utf8 > 0
+ && continuation <= expectedContinuation
+ && continuation >= expectedContinuation - 3
+ && count(0xf8, 0x100) == 0
+ && (control - safe) * 100 < utf8 * 2;
}
/**
@@ -95,13 +96,13 @@ public class TextStatistics {
}
/**
- * Counts control characters (i.e. < 0x20, excluding tab, CR, LF,
- * page feed and escape).
- * <p>
- * This definition of control characters is based on section 4 of the
- * "Content-Type Processing Model" Internet-draft
- * (<a href="http://webblaze.cs.berkeley.edu/2009/mime-sniff/mime-sniff.txt"
+ * Counts control characters (i.e. < 0x20, excluding tab, CR, LF, page feed and escape).
+ *
+ * <p>This definition of control characters is based on section 4 of the "Content-Type
+ * Processing Model" Internet-draft (<a
+ * href="http://webblaze.cs.berkeley.edu/2009/mime-sniff/mime-sniff.txt"
* >draft-abarth-mime-sniff-01</a>).
+ *
* <pre>
* +-------------------------+
* | Binary data byte ranges |
@@ -149,8 +150,10 @@ public class TextStatistics {
}
private int countSafeControl() {
- return count('\t') + count('\n') + count('\r') // tab, LF, CR
- + count(0x0c) + count(0x1b); // new page, escape
+ return count('\t')
+ + count('\n')
+ + count('\r') // tab, LF, CR
+ + count(0x0c)
+ + count(0x1b); // new page, escape
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/TrainedModel.java b/tika-core/src/main/java/org/apache/tika/detect/TrainedModel.java
index 0111b233b..6d725ee80 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/TrainedModel.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/TrainedModel.java
@@ -16,7 +16,6 @@
*/
package org.apache.tika.detect;
-
public abstract class TrainedModel {
public abstract double predict(double[] input);
diff --git a/tika-core/src/main/java/org/apache/tika/detect/TrainedModelDetector.java b/tika-core/src/main/java/org/apache/tika/detect/TrainedModelDetector.java
index 25b9f085b..170ed0ba0 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/TrainedModelDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/TrainedModelDetector.java
@@ -31,7 +31,6 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.tika.io.TemporaryResources;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
diff --git a/tika-core/src/main/java/org/apache/tika/detect/TypeDetector.java b/tika-core/src/main/java/org/apache/tika/detect/TypeDetector.java
index 60d75c7b0..d10ef0024 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/TypeDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/TypeDetector.java
@@ -17,27 +17,25 @@
package org.apache.tika.detect;
import java.io.InputStream;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
/**
- * Content type detection based on a content type hint. This detector simply
- * trusts any valid content type hint given in the input metadata, and returns
- * that as the likely type of the input document.
+ * Content type detection based on a content type hint. This detector simply trusts any valid
+ * content type hint given in the input metadata, and returns that as the likely type of the input
+ * document.
*
* @since Apache Tika 0.3
*/
public class TypeDetector implements Detector {
/**
- * Detects the content type of an input document based on a type hint
- * given in the input metadata. The CONTENT_TYPE attribute of the given
- * input metadata is expected to contain the type of the input document.
- * If that attribute exists and contains a valid type name, then that
- * type is returned.
+ * Detects the content type of an input document based on a type hint given in the input
+ * metadata. The CONTENT_TYPE attribute of the given input metadata is expected to contain the
+ * type of the input document. If that attribute exists and contains a valid type name, then
+ * that type is returned.
*
- * @param input ignored
+ * @param input ignored
* @param metadata input metadata, possibly with a CONTENT_TYPE value
* @return detected media type, or <code>application/octet-stream</code>
*/
@@ -52,5 +50,4 @@ public class TypeDetector implements Detector {
}
return MediaType.OCTET_STREAM;
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/XmlRootExtractor.java b/tika-core/src/main/java/org/apache/tika/detect/XmlRootExtractor.java
index 94d853149..83f73e1ec 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/XmlRootExtractor.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/XmlRootExtractor.java
@@ -20,19 +20,17 @@ import java.io.CharConversionException;
import java.io.InputStream;
import java.util.Arrays;
import javax.xml.namespace.QName;
-
import org.apache.commons.io.input.CloseShieldInputStream;
import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream;
+import org.apache.tika.parser.ParseContext;
+import org.apache.tika.utils.XMLReaderUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
-import org.apache.tika.parser.ParseContext;
-import org.apache.tika.utils.XMLReaderUtils;
-
/**
- * Utility class that uses a {@link javax.xml.parsers.SAXParser} to determine
- * the namespace URI and local name of the root element of an XML file.
+ * Utility class that uses a {@link javax.xml.parsers.SAXParser} to determine the namespace URI and
+ * local name of the root element of an XML file.
*
* @since Apache Tika 0.4
*/
@@ -66,17 +64,17 @@ public class XmlRootExtractor {
public QName extractRootElement(InputStream stream) {
return extractRootElement(stream, false);
}
-
+
private QName extractRootElement(InputStream stream, boolean throwMalformed) {
ExtractorHandler handler = new ExtractorHandler();
try {
- XMLReaderUtils.parseSAX(CloseShieldInputStream.wrap(stream),
- handler, EMPTY_CONTEXT);
+ XMLReaderUtils.parseSAX(CloseShieldInputStream.wrap(stream), handler, EMPTY_CONTEXT);
} catch (SecurityException e) {
throw e;
} catch (Exception e) {
- if (throwMalformed && (e instanceof CharConversionException
- || e.getCause() instanceof CharConversionException)) {
+ if (throwMalformed
+ && (e instanceof CharConversionException
+ || e.getCause() instanceof CharConversionException)) {
throw new MalformedCharException(e);
}
}
@@ -93,7 +91,6 @@ public class XmlRootExtractor {
this.rootElement = new QName(uri, local);
throw new SAXException("Aborting: root element received");
}
-
}
private static class MalformedCharException extends RuntimeException {
@@ -101,7 +98,5 @@ public class XmlRootExtractor {
public MalformedCharException(Exception e) {
super(e);
}
-
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/detect/ZeroSizeFileDetector.java b/tika-core/src/main/java/org/apache/tika/detect/ZeroSizeFileDetector.java
index 5ce52681e..86f491725 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/ZeroSizeFileDetector.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/ZeroSizeFileDetector.java
@@ -18,13 +18,10 @@ package org.apache.tika.detect;
import java.io.IOException;
import java.io.InputStream;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
-/**
- * Detector to identify zero length files as application/x-zerovalue
- */
+/** Detector to identify zero length files as application/x-zerovalue */
public class ZeroSizeFileDetector implements Detector {
public MediaType detect(InputStream stream, Metadata metadata) throws IOException {
if (stream != null) {
diff --git a/tika-core/src/main/java/org/apache/tika/detect/package-info.java b/tika-core/src/main/java/org/apache/tika/detect/package-info.java
index dede49cfb..b04a9d1c9 100644
--- a/tika-core/src/main/java/org/apache/tika/detect/package-info.java
+++ b/tika-core/src/main/java/org/apache/tika/detect/package-info.java
@@ -15,8 +15,6 @@
* limitations under the License.
*/
-/**
- * Media type detection.
- */
+/** Media type detection. */
@aQute.bnd.annotation.Version("1.0.0")
package org.apache.tika.detect;
diff --git a/tika-core/src/main/java/org/apache/tika/embedder/Embedder.java b/tika-core/src/main/java/org/apache/tika/embedder/Embedder.java
index 2af59d326..d1bead9eb 100644
--- a/tika-core/src/main/java/org/apache/tika/embedder/Embedder.java
+++ b/tika-core/src/main/java/org/apache/tika/embedder/Embedder.java
@@ -21,7 +21,6 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Set;
-
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
@@ -36,11 +35,11 @@ import org.apache.tika.parser.Parser;
public interface Embedder extends Serializable {
/**
- * Returns the set of media types supported by this embedder when used with
- * the given parse context.
- * <p>
- * The name differs from the precedence of {@link Parser#getSupportedTypes(ParseContext)}
- * so that parser implementations may also choose to implement this interface.
+ * Returns the set of media types supported by this embedder when used with the given parse
+ * context.
+ *
+ * <p>The name differs from the precedence of {@link Parser#getSupportedTypes(ParseContext)} so
+ * that parser implementations may also choose to implement this interface.
*
* @param context parse context
* @return immutable set of media types
@@ -48,46 +47,45 @@ public interface Embedder extends Serializable {
Set<MediaType> getSupportedEmbedTypes(ParseContext context);
/**
- * Embeds related document metadata from the given metadata object into the
- * given output stream.
- * <p>
- * The given document stream is consumed but not closed by this method. The
- * responsibility to close the stream remains on the caller.
- * <p>
- * Information about the parsing context can be passed in the context
- * parameter. See the parser implementations for the kinds of context
- * information they expect.
- * <p>
- * In general implementations should favor preserving the source file's metadata
- * unless an update to a field is explicitly defined in the Metadata object.
- * More specifically:
+ * Embeds related document metadata from the given metadata object into the given output stream.
+ *
+ * <p>The given document stream is consumed but not closed by this method. The responsibility to
+ * close the stream remains on the caller.
+ *
+ * <p>Information about the parsing context can be passed in the context parameter. See the
+ * parser implementations for the kinds of context information they expect.
+ *
+ * <p>In general implementations should favor preserving the source file's metadata unless an
+ * update to a field is explicitly defined in the Metadata object. More specifically:
+ *
* <ul>
- * <li>Embedder implementations should only attempt to update metadata fields
- * present in the given Metadata object. Other fields should be left untouched.</li>
- * <li>Embedder implementations should set properties as empty when the
- * corresponding field in the Metadata object is an empty string, i.e. ""</li>
- * <li>Embedder implementations should nullify or delete properties
- * corresponding to fields with a null value in the given Metadata object.</li>
- * <li>Embedder implementations should set the property
- * corresponding to a particular field in the given Metadata object in all
- * metadata containers whenever possible and appropriate for the file format at the time.
- * If a particular metadata container falls out of use and/or is superseded by another
- * (such as IIC vs XMP for IPTC) it is up to the implementation to decide if and when
- * to cease embedding in the alternate container.</li>
- * <li>Embedder implementations should attempt to embed as much of the metadata
- * as accurately as possible. An implementation may choose a strict approach
- * and throw an exception if a value to be embedded exceeds the length allowed
- * or may choose to truncate the value.</li>
+ * <li>Embedder implementations should only attempt to update metadata fields present in the
+ * given Metadata object. Other fields should be left untouched.
+ * <li>Embedder implementations should set properties as empty when the corresponding field in
+ * the Metadata object is an empty string, i.e. ""
+ * <li>Embedder implementations should nullify or delete properties corresponding to fields
+ * with a null value in the given Metadata object.
+ * <li>Embedder implementations should set the property corresponding to a particular field in
+ * the given Metadata object in all metadata containers whenever possible and appropriate
+ * for the file format at the time. If a particular metadata container falls out of use
+ * and/or is superseded by another (such as IIC vs XMP for IPTC) it is up to the
+ * implementation to decide if and when to cease embedding in the alternate container.
+ * <li>Embedder implementations should attempt to embed as much of the metadata as accurately
+ * as possible. An implementation may choose a strict approach and throw an exception if a
+ * value to be embedded exceeds the length allowed or may choose to truncate the value.
* </ul>
*
- * @param metadata document metadata (input and output)
+ * @param metadata document metadata (input and output)
* @param originalStream the document stream (input)
- * @param outputStream the output stream to write the metadata embedded data to
- * @param context parse context
- * @throws IOException if the document stream could not be read
+ * @param outputStream the output stream to write the metadata embedded data to
+ * @param context parse context
+ * @throws IOException if the document stream could not be read
* @throws TikaException if the document could not be parsed
*/
- void embed(Metadata metadata, InputStream originalStream, OutputStream outputStream,
- ParseContext context) throws IOException, TikaException;
-
+ void embed(
+ Metadata metadata,
+ InputStream originalStream,
+ OutputStream outputStream,
+ ParseContext context)
+ throws IOException, TikaException;
}
diff --git a/tika-core/src/main/java/org/apache/tika/embedder/ExternalEmbedder.java b/tika-core/src/main/java/org/apache/tika/embedder/ExternalEmbedder.java
index b2411d7a8..a1b2cf65c 100644
--- a/tika-core/src/main/java/org/apache/tika/embedder/ExternalEmbedder.java
+++ b/tika-core/src/main/java/org/apache/tika/embedder/ExternalEmbedder.java
@@ -29,10 +29,8 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
-
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream;
-
import org.apache.tika.exception.TikaException;
import org.apache.tika.io.TemporaryResources;
import org.apache.tika.io.TikaInputStream;
@@ -43,50 +41,49 @@ import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.external.ExternalParser;
/**
- * Embedder that uses an external program (like sed or exiftool) to embed text
- * content and metadata into a given document.
+ * Embedder that uses an external program (like sed or exiftool) to embed text content and metadata
+ * into a given document.
*
* @since Apache Tika 1.3
*/
public class ExternalEmbedder implements Embedder {
- /**
- * Token to be replaced with a String array of metadata assignment command
- * arguments
- */
+ /** Token to be replaced with a String array of metadata assignment command arguments */
public static final String METADATA_COMMAND_ARGUMENTS_TOKEN = "${METADATA}";
- /**
- * Token to be replaced with a String array of metadata assignment command
- * arguments
- */
+
+ /** Token to be replaced with a String array of metadata assignment command arguments */
public static final String METADATA_COMMAND_ARGUMENTS_SERIALIZED_TOKEN =
"${METADATA_SERIALIZED}";
+
private static final long serialVersionUID = -2828829275642475697L;
private final TemporaryResources tmp = new TemporaryResources();
- /**
- * Media types supported by the external program.
- */
+
+ /** Media types supported by the external program. */
private Set<MediaType> supportedEmbedTypes = Collections.emptySet();
- /**
- * Mapping of Tika metadata to command line parameters.
- */
+
+ /** Mapping of Tika metadata to command line parameters. */
private Map<Property, String[]> metadataCommandArguments = null;
+
/**
* The external command to invoke.
*
* @see Runtime#exec(String[])
*/
private String[] command =
- new String[]{"sed", "-e", "$a\\\n" + METADATA_COMMAND_ARGUMENTS_SERIALIZED_TOKEN,
- ExternalParser.INPUT_FILE_TOKEN};
+ new String[] {
+ "sed",
+ "-e",
+ "$a\\\n" + METADATA_COMMAND_ARGUMENTS_SERIALIZED_TOKEN,
+ ExternalParser.INPUT_FILE_TOKEN
+ };
+
private String commandAssignmentOperator = "=";
private String commandAssignmentDelimeter = ", ";
private String commandAppendOperator = "=";
private boolean quoteAssignmentValues = false;
/**
- * Serializes a collection of metadata command line arguments into a single
- * string.
+ * Serializes a collection of metadata command line arguments into a single string.
*
* @param metadataCommandArguments
* @return the serialized metadata arguments string
@@ -99,30 +96,28 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Checks to see if the command can be run. Typically used with something
- * like "myapp --version" to check to see if "myapp" is installed and on the
- * path.
+ * Checks to see if the command can be run. Typically used with something like "myapp --version"
+ * to check to see if "myapp" is installed and on the path.
*
- * @param checkCmd the check command to run
+ * @param checkCmd the check command to run
* @param errorValue what is considered an error value?
* @return whether or not the check completed without error
*/
public static boolean check(String checkCmd, int... errorValue) {
- return check(new String[]{checkCmd}, errorValue);
+ return check(new String[] {checkCmd}, errorValue);
}
/**
- * Checks to see if the command can be run. Typically used with something
- * like "myapp --version" to check to see if "myapp" is installed and on the
- * path.
+ * Checks to see if the command can be run. Typically used with something like "myapp --version"
+ * to check to see if "myapp" is installed and on the path.
*
- * @param checkCmd the check command to run
+ * @param checkCmd the check command to run
* @param errorValue what is considered an error value?
* @return whether or not the check completed without error
*/
public static boolean check(String[] checkCmd, int... errorValue) {
if (errorValue.length == 0) {
- errorValue = new int[]{127};
+ errorValue = new int[] {127};
}
try {
@@ -155,14 +150,12 @@ public class ExternalEmbedder implements Embedder {
}
public void setSupportedEmbedTypes(Set<MediaType> supportedEmbedTypes) {
- this.supportedEmbedTypes =
- Collections.unmodifiableSet(new HashSet<>(supportedEmbedTypes));
+ this.supportedEmbedTypes = Collections.unmodifiableSet(new HashSet<>(supportedEmbedTypes));
}
/**
- * Gets the command to be run. This can include either of
- * {@link ExternalParser#INPUT_FILE_TOKEN} or
- * {@link ExternalParser#OUTPUT_FILE_TOKEN} if the command
+ * Gets the command to be run. This can include either of {@link
+ * ExternalParser#INPUT_FILE_TOKEN} or {@link ExternalParser#OUTPUT_FILE_TOKEN} if the command
* needs filenames.
*
* @return
@@ -172,9 +165,8 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Sets the command to be run. This can include either of
- * {@link ExternalParser#INPUT_FILE_TOKEN} or
- * {@link ExternalParser#OUTPUT_FILE_TOKEN} if the command
+ * Sets the command to be run. This can include either of {@link
+ * ExternalParser#INPUT_FILE_TOKEN} or {@link ExternalParser#OUTPUT_FILE_TOKEN} if the command
* needs filenames.
*
* @see Runtime#exec(String[])
@@ -202,8 +194,7 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Gets the delimiter for multiple assignments for the command line tool,
- * i.e. ", ".
+ * Gets the delimiter for multiple assignments for the command line tool, i.e. ", ".
*
* @return the assignment delimiter
*/
@@ -212,8 +203,7 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Sets the delimiter for multiple assignments for the command line tool,
- * i.e. ", ".
+ * Sets the delimiter for multiple assignments for the command line tool, i.e. ", ".
*
* @param commandAssignmentDelimeter
*/
@@ -222,8 +212,7 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Gets the operator to append rather than replace a value for the command
- * line tool, i.e. "+=".
+ * Gets the operator to append rather than replace a value for the command line tool, i.e. "+=".
*
* @return the append operator
*/
@@ -232,8 +221,7 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Sets the operator to append rather than replace a value for the command
- * line tool, i.e. "+=".
+ * Sets the operator to append rather than replace a value for the command line tool, i.e. "+=".
*
* @param commandAppendOperator
*/
@@ -242,8 +230,7 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Gets whether or not to quote assignment values, i.e. tag='value'. The
- * default is false.
+ * Gets whether or not to quote assignment values, i.e. tag='value'. The default is false.
*
* @return whether or not to quote assignment values
*/
@@ -270,8 +257,8 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Sets the map of Metadata keys to command line parameters. Set this to
- * null to disable Metadata embedding.
+ * Sets the map of Metadata keys to command line parameters. Set this to null to disable
+ * Metadata embedding.
*
* @param arguments
*/
@@ -280,8 +267,8 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Constructs a collection of command line arguments responsible for setting
- * individual metadata fields based on the given <code>metadata</code>.
+ * Constructs a collection of command line arguments responsible for setting individual metadata
+ * fields based on the given <code>metadata</code>.
*
* @param metadata the metadata to embed
* @return the metadata-related command line arguments
@@ -303,18 +290,20 @@ public class ExternalEmbedder implements Embedder {
if (quoteAssignmentValues) {
assignmentValue = "'" + assignmentValue + "'";
}
- commandMetadataSegments
- .add(metadataCommandArgument + commandAppendOperator +
- assignmentValue);
+ commandMetadataSegments.add(
+ metadataCommandArgument
+ + commandAppendOperator
+ + assignmentValue);
}
} else {
String assignmentValue = metadata.get(metadataName);
if (quoteAssignmentValues) {
assignmentValue = "'" + assignmentValue + "'";
}
- commandMetadataSegments
- .add(metadataCommandArgument + commandAssignmentOperator +
- assignmentValue);
+ commandMetadataSegments.add(
+ metadataCommandArgument
+ + commandAssignmentOperator
+ + assignmentValue);
}
}
}
@@ -325,13 +314,15 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Executes the configured external command and passes the given document
- * stream as a simple XHTML document to the given SAX content handler.
- * Metadata is only extracted if {@link #setMetadataCommandArguments(Map)}
- * has been called to set arguments.
+ * Executes the configured external command and passes the given document stream as a simple
+ * XHTML document to the given SAX content handler. Metadata is only extracted if {@link
+ * #setMetadataCommandArguments(Map)} has been called to set arguments.
*/
- public void embed(final Metadata metadata, final InputStream inputStream,
- final OutputStream outputStream, final ParseContext context)
+ public void embed(
+ final Metadata metadata,
+ final InputStream inputStream,
+ final OutputStream outputStream,
+ final ParseContext context)
throws IOException, TikaException {
boolean inputToStdIn = true;
@@ -354,14 +345,17 @@ public class ExternalEmbedder implements Embedder {
List<String> cmd = new ArrayList<>();
for (String commandSegment : origCmd) {
if (commandSegment.contains(ExternalParser.INPUT_FILE_TOKEN)) {
- commandSegment = commandSegment.replace(ExternalParser.INPUT_FILE_TOKEN,
- tikaInputStream.getFile().toString());
+ commandSegment =
+ commandSegment.replace(
+ ExternalParser.INPUT_FILE_TOKEN,
+ tikaInputStream.getFile().toString());
inputToStdIn = false;
}
if (commandSegment.contains(ExternalParser.OUTPUT_FILE_TOKEN)) {
tempOutputFile = tmp.createTemporaryFile();
- commandSegment = commandSegment
- .replace(ExternalParser.OUTPUT_FILE_TOKEN, tempOutputFile.toString());
+ commandSegment =
+ commandSegment.replace(
+ ExternalParser.OUTPUT_FILE_TOKEN, tempOutputFile.toString());
outputFromStdOut = false;
}
if (commandSegment.contains(METADATA_COMMAND_ARGUMENTS_SERIALIZED_TOKEN)) {
@@ -382,15 +376,16 @@ public class ExternalEmbedder implements Embedder {
int i = 0;
for (String commandSegment : cmd) {
if (commandSegment.contains(METADATA_COMMAND_ARGUMENTS_SERIALIZED_TOKEN)) {
- commandSegment = commandSegment
- .replace(METADATA_COMMAND_ARGUMENTS_SERIALIZED_TOKEN,
+ commandSegment =
+ commandSegment.replace(
+ METADATA_COMMAND_ARGUMENTS_SERIALIZED_TOKEN,
serializeMetadata(commandMetadataSegments));
cmd.set(i, commandSegment);
}
i++;
}
- } else if (!replacedMetadataCommandArgumentsToken &&
- !serializeMetadataCommandArgumentsToken) {
+ } else if (!replacedMetadataCommandArgumentsToken
+ && !serializeMetadataCommandArgumentsToken) {
// Tack metadata onto the end of the cmd as arguments
cmd.addAll(commandMetadataSegments);
}
@@ -399,12 +394,13 @@ public class ExternalEmbedder implements Embedder {
// Execute
Process process;
if (cmd.toArray().length == 1) {
- process = Runtime.getRuntime().exec(cmd.toArray(new String[]{})[0]);
+ process = Runtime.getRuntime().exec(cmd.toArray(new String[] {})[0]);
} else {
- process = Runtime.getRuntime().exec(cmd.toArray(new String[]{}));
+ process = Runtime.getRuntime().exec(cmd.toArray(new String[] {}));
}
- UnsynchronizedByteArrayOutputStream stdErrOutputStream = UnsynchronizedByteArrayOutputStream.builder().get();
+ UnsynchronizedByteArrayOutputStream stdErrOutputStream =
+ UnsynchronizedByteArrayOutputStream.builder().get();
try {
sendStdErrToOutputStream(process, stdErrOutputStream);
@@ -439,7 +435,7 @@ public class ExternalEmbedder implements Embedder {
// Clean up temp output files
tempOutputFile.delete();
} catch (Exception e) {
- //swallow
+ // swallow
}
}
if (!inputToStdIn) {
@@ -450,9 +446,12 @@ public class ExternalEmbedder implements Embedder {
IOUtils.closeQuietly(outputStream);
IOUtils.closeQuietly(stdErrOutputStream);
if (process.exitValue() != 0) {
- throw new TikaException("There was an error executing the command line" +
- "\nExecutable Command:\n\n" + cmd + "\nExecutable Error:\n\n" +
- stdErrOutputStream.toString(UTF_8.name()));
+ throw new TikaException(
+ "There was an error executing the command line"
+ + "\nExecutable Command:\n\n"
+ + cmd
+ + "\nExecutable Error:\n\n"
+ + stdErrOutputStream.toString(UTF_8.name()));
}
}
}
@@ -460,28 +459,29 @@ public class ExternalEmbedder implements Embedder {
/**
* Creates a new thread for copying a given input stream to a given output stream.
*
- * @param inputStream the source input stream
+ * @param inputStream the source input stream
* @param outputStream the target output stream
*/
- private void multiThreadedStreamCopy(final InputStream inputStream,
- final OutputStream outputStream) {
- new Thread(() -> {
- try {
- IOUtils.copy(inputStream, outputStream);
- } catch (IOException e) {
- System.out.println("ERROR: " + e.getMessage());
- }
- }).start();
+ private void multiThreadedStreamCopy(
+ final InputStream inputStream, final OutputStream outputStream) {
+ new Thread(
+ () -> {
+ try {
+ IOUtils.copy(inputStream, outputStream);
+ } catch (IOException e) {
+ System.out.println("ERROR: " + e.getMessage());
+ }
+ })
+ .start();
}
/**
- * Sends the contents of the given input stream to the
- * standard input of the given process. Potential exceptions are
- * ignored.
- * <p>
- * Note that the given input stream is <em>not</em> closed by this method.
+ * Sends the contents of the given input stream to the standard input of the given process.
+ * Potential exceptions are ignored.
*
- * @param process the process
+ * <p>Note that the given input stream is <em>not</em> closed by this method.
+ *
+ * @param process the process
* @param inputStream the input stream to send to standard input of the process
*/
private void sendInputStreamToStdIn(final InputStream inputStream, final Process process) {
@@ -489,13 +489,12 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Sends the standard output of the given
- * process to the given output stream. Potential exceptions are
- * ignored.
- * <p>
- * Note that the given output stream is <em>not</em> closed by this method.
+ * Sends the standard output of the given process to the given output stream. Potential
+ * exceptions are ignored.
+ *
+ * <p>Note that the given output stream is <em>not</em> closed by this method.
*
- * @param process the process
+ * @param process the process
* @param outputStream the putput stream to send to standard input of the process
*/
private void sendStdOutToOutputStream(final Process process, final OutputStream outputStream) {
@@ -507,12 +506,11 @@ public class ExternalEmbedder implements Embedder {
}
/**
- * Starts a thread that reads and discards the contents of the standard
- * stream of the given process. Potential exceptions are ignored, and the
- * stream is closed once fully processed.
+ * Starts a thread that reads and discards the contents of the standard stream of the given
+ * process. Potential exceptions are ignored, and the stream is closed once fully processed.
*
- * @param process the process
- * param outputStream the output stream to send to standard error of the process
+ * @param process the process param outputStream the output stream to send to standard error of
+ * the process
*/
private void sendStdErrToOutputStream(final Process process, final OutputStream outputStream) {
multiThreadedStreamCopy(process.getErrorStream(), outputStream);
diff --git a/tika-core/src/main/java/org/apache/tika/exception/AccessPermissionException.java b/tika-core/src/main/java/org/apache/tika/exception/AccessPermissionException.java
index b5f2136ea..9042868c3 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/AccessPermissionException.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/AccessPermissionException.java
@@ -17,9 +17,8 @@
package org.apache.tika.exception;
/**
- * Exception to be thrown when a document does not allow content extraction.
- * As of this writing, PDF documents are the only type of document that might
- * cause this type of exception.
+ * Exception to be thrown when a document does not allow content extraction. As of this writing, PDF
+ * documents are the only type of document that might cause this type of exception.
*/
public class AccessPermissionException extends TikaException {
public AccessPermissionException() {
diff --git a/tika-core/src/main/java/org/apache/tika/exception/CorruptedFileException.java b/tika-core/src/main/java/org/apache/tika/exception/CorruptedFileException.java
index 5ebad6d3a..ede9da571 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/CorruptedFileException.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/CorruptedFileException.java
@@ -17,8 +17,8 @@
package org.apache.tika.exception;
/**
- * This exception should be thrown when the parse absolutely, positively has to stop.
- * This exception must not be caught and swallowed if an embedded parser throws it.
+ * This exception should be thrown when the parse absolutely, positively has to stop. This exception
+ * must not be caught and swallowed if an embedded parser throws it.
*/
public class CorruptedFileException extends TikaException {
public CorruptedFileException(String msg) {
diff --git a/tika-core/src/main/java/org/apache/tika/exception/FileTooLongException.java b/tika-core/src/main/java/org/apache/tika/exception/FileTooLongException.java
index 3ec3294b3..97ebb60eb 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/FileTooLongException.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/FileTooLongException.java
@@ -34,8 +34,11 @@ public class FileTooLongException extends IOException {
}
private static String msg(long length, long maxLength) {
- return "File is " + length + " bytes, but " + maxLength +
- " is the maximum length allowed. You can modify maxLength via " +
- "the setter on the fetcher.";
+ return "File is "
+ + length
+ + " bytes, but "
+ + maxLength
+ + " is the maximum length allowed. You can modify maxLength via "
+ + "the setter on the fetcher.";
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/exception/RuntimeSAXException.java b/tika-core/src/main/java/org/apache/tika/exception/RuntimeSAXException.java
index 4e0bc4308..853dfc958 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/RuntimeSAXException.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/RuntimeSAXException.java
@@ -18,13 +18,10 @@ package org.apache.tika.exception;
import org.xml.sax.SAXException;
-/**
- * Use this to throw a SAXException in subclassed methods that don't throw SAXExceptions
- */
+/** Use this to throw a SAXException in subclassed methods that don't throw SAXExceptions */
public class RuntimeSAXException extends RuntimeException {
public RuntimeSAXException(SAXException t) {
super(t);
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/exception/TikaConfigException.java b/tika-core/src/main/java/org/apache/tika/exception/TikaConfigException.java
index 1dcd3275f..3c6855354 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/TikaConfigException.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/TikaConfigException.java
@@ -17,9 +17,8 @@
package org.apache.tika.exception;
/**
- * Tika Config Exception is an exception to occur when there is an error
- * in Tika config file and/or one or more of the parsers failed to initialize
- * from that erroneous config.
+ * Tika Config Exception is an exception to occur when there is an error in Tika config file and/or
+ * one or more of the parsers failed to initialize from that erroneous config.
*
* @since Apache Tika 1.14
*/
diff --git a/tika-core/src/main/java/org/apache/tika/exception/TikaException.java b/tika-core/src/main/java/org/apache/tika/exception/TikaException.java
index ceac19d6a..a2bfc87cb 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/TikaException.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/TikaException.java
@@ -16,9 +16,7 @@
*/
package org.apache.tika.exception;
-/**
- * Tika exception
- */
+/** Tika exception */
public class TikaException extends Exception {
public TikaException(String msg) {
@@ -28,5 +26,4 @@ public class TikaException extends Exception {
public TikaException(String msg, Throwable cause) {
super(msg, cause);
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/exception/TikaMemoryLimitException.java b/tika-core/src/main/java/org/apache/tika/exception/TikaMemoryLimitException.java
index fbc1a9552..9730f54d7 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/TikaMemoryLimitException.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/TikaMemoryLimitException.java
@@ -33,8 +33,11 @@ public class TikaMemoryLimitException extends TikaException {
}
private static String msg(long triedToAllocate, long maxAllowable) {
- return "Tried to allocate " + triedToAllocate + " bytes, but " + maxAllowable +
- " is the maximum allowed. Please open an issue https://issues.apache.org/jira/projects/TIKA" +
- " if you believe this file is not corrupt.";
+ return "Tried to allocate "
+ + triedToAllocate
+ + " bytes, but "
+ + maxAllowable
+ + " is the maximum allowed. Please open an issue https://issues.apache.org/jira/projects/TIKA"
+ + " if you believe this file is not corrupt.";
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/exception/TikaTimeoutException.java b/tika-core/src/main/java/org/apache/tika/exception/TikaTimeoutException.java
index a53dbd6a3..97bfebed8 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/TikaTimeoutException.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/TikaTimeoutException.java
@@ -16,9 +16,7 @@
*/
package org.apache.tika.exception;
-/**
- * Runtime/unchecked version of {@link java.util.concurrent.TimeoutException}
- */
+/** Runtime/unchecked version of {@link java.util.concurrent.TimeoutException} */
public class TikaTimeoutException extends RuntimeException {
public TikaTimeoutException(String message) {
super(message);
diff --git a/tika-core/src/main/java/org/apache/tika/exception/UnsupportedFormatException.java b/tika-core/src/main/java/org/apache/tika/exception/UnsupportedFormatException.java
index 4322e64f9..76844ac56 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/UnsupportedFormatException.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/UnsupportedFormatException.java
@@ -18,18 +18,15 @@
package org.apache.tika.exception;
/**
- * Parsers should throw this exception when they encounter
- * a file format that they do not support. This should only happen
- * when we're not able to differentiate versions by the mime. For example,
- * At the time of this writing, "application/wordperfect" covers all versions
- * of the wordperfect format; however, the parser only handles 6.x.
- * <p/>
- * Whenever possible/convenient, it is better to distinguish file formats by mime
- * so that unsupported formats will be handled by the
- * {@link org.apache.tika.parser.EmptyParser}.
- * However, if we can't differentiate by mime or we need to rely on the parser
- * to distinguish the versions (in the case that magic can't distinguish),
- * this exception should be thrown.
+ * Parsers should throw this exception when they encounter a file format that they do not support.
+ * This should only happen when we're not able to differentiate versions by the mime. For example,
+ * At the time of this writing, "application/wordperfect" covers all versions of the wordperfect
+ * format; however, the parser only handles 6.x.
+ *
+ * <p>Whenever possible/convenient, it is better to distinguish file formats by mime so that
+ * unsupported formats will be handled by the {@link org.apache.tika.parser.EmptyParser}. However,
+ * if we can't differentiate by mime or we need to rely on the parser to distinguish the versions
+ * (in the case that magic can't distinguish), this exception should be thrown.
*/
public class UnsupportedFormatException extends TikaException {
diff --git a/tika-core/src/main/java/org/apache/tika/exception/WriteLimitReachedException.java b/tika-core/src/main/java/org/apache/tika/exception/WriteLimitReachedException.java
index 3e661ada5..b4559a69a 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/WriteLimitReachedException.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/WriteLimitReachedException.java
@@ -20,29 +20,31 @@ import org.xml.sax.SAXException;
public class WriteLimitReachedException extends SAXException {
- //in case of (hopefully impossible) cyclic exception
- private final static int MAX_DEPTH = 100;
+ // in case of (hopefully impossible) cyclic exception
+ private static final int MAX_DEPTH = 100;
private final int writeLimit;
+
public WriteLimitReachedException(int writeLimit) {
this.writeLimit = writeLimit;
}
@Override
public String getMessage() {
- return "Your document contained more than " + writeLimit
+ return "Your document contained more than "
+ + writeLimit
+ " characters, and so your requested limit has been"
+ " reached. To receive the full text of the document,"
+ " increase your limit. (Text up to the limit is"
+ " however available).";
}
+
/**
- * Checks whether the given exception (or any of it's root causes) was
- * thrown by this handler as a signal of reaching the write limit.
+ * Checks whether the given exception (or any of it's root causes) was thrown by this handler as
+ * a signal of reaching the write limit.
*
* @param t throwable
- * @return <code>true</code> if the write limit was reached,
- * <code>false</code> otherwise
+ * @return <code>true</code> if the write limit was reached, <code>false</code> otherwise
* @since Apache Tika 2.0
*/
public static boolean isWriteLimitReached(Throwable t) {
diff --git a/tika-core/src/main/java/org/apache/tika/exception/ZeroByteFileException.java b/tika-core/src/main/java/org/apache/tika/exception/ZeroByteFileException.java
index 125bc21b9..9adcf5bd0 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/ZeroByteFileException.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/ZeroByteFileException.java
@@ -17,28 +17,24 @@
package org.apache.tika.exception;
-/**
- * Exception thrown by the AutoDetectParser when a file contains zero-bytes.
- */
+/** Exception thrown by the AutoDetectParser when a file contains zero-bytes. */
public class ZeroByteFileException extends TikaException {
-
/**
- * If this is in the {@link org.apache.tika.parser.ParseContext}, the
- * {@link org.apache.tika.parser.AutoDetectParser} and the
- * {@link org.apache.tika.parser.RecursiveParserWrapper} will
- * ignore embedded files with zero-byte length inputstreams
+ * If this is in the {@link org.apache.tika.parser.ParseContext}, the {@link
+ * org.apache.tika.parser.AutoDetectParser} and the {@link
+ * org.apache.tika.parser.RecursiveParserWrapper} will ignore embedded files with zero-byte
+ * length inputstreams
*/
public static IgnoreZeroByteFileException IGNORE_ZERO_BYTE_FILE_EXCEPTION =
new IgnoreZeroByteFileException();
- //If this is in the parse context, the AutoDetectParser and the
- //RecursiveParserWrapper should ignore zero byte files
- //and not throw a Zero}
+ // If this is in the parse context, the AutoDetectParser and the
+ // RecursiveParserWrapper should ignore zero byte files
+ // and not throw a Zero}
public ZeroByteFileException(String msg) {
super(msg);
}
- public static class IgnoreZeroByteFileException {
- }
+ public static class IgnoreZeroByteFileException {}
}
diff --git a/tika-core/src/main/java/org/apache/tika/exception/package-info.java b/tika-core/src/main/java/org/apache/tika/exception/package-info.java
index 80ab12581..af490fba5 100644
--- a/tika-core/src/main/java/org/apache/tika/exception/package-info.java
+++ b/tika-core/src/main/java/org/apache/tika/exception/package-info.java
@@ -15,8 +15,6 @@
* limitations under the License.
*/
-/**
- * Tika exception.
- */
+/** Tika exception. */
@aQute.bnd.annotation.Version("1.0.0")
package org.apache.tika.exception;
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/AbstractEmbeddedDocumentBytesHandler.java b/tika-core/src/main/java/org/apache/tika/extractor/AbstractEmbeddedDocumentBytesHandler.java
index 3f2f38f94..ca74e99a1 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/AbstractEmbeddedDocumentBytesHandler.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/AbstractEmbeddedDocumentBytesHandler.java
@@ -21,7 +21,6 @@ import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
-
import org.apache.tika.io.FilenameUtils;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
@@ -32,23 +31,29 @@ public abstract class AbstractEmbeddedDocumentBytesHandler implements EmbeddedDo
List<Integer> ids = new ArrayList<>();
- public String getEmitKey(String containerEmitKey, int embeddedId,
- EmbeddedDocumentBytesConfig embeddedDocumentBytesConfig,
- Metadata metadata) {
- String embeddedIdString = embeddedDocumentBytesConfig.getZeroPadName() > 0 ?
- StringUtils.leftPad(Integer.toString(embeddedId),
- embeddedDocumentBytesConfig.getZeroPadName(), "0") :
- Integer.toString(embeddedId);
-
+ public String getEmitKey(
+ String containerEmitKey,
+ int embeddedId,
+ EmbeddedDocumentBytesConfig embeddedDocumentBytesConfig,
+ Metadata metadata) {
+ String embeddedIdString =
+ embeddedDocumentBytesConfig.getZeroPadName() > 0
+ ? StringUtils.leftPad(
+ Integer.toString(embeddedId),
+ embeddedDocumentBytesConfig.getZeroPadName(),
+ "0")
+ : Integer.toString(embeddedId);
- StringBuilder emitKey = new StringBuilder(containerEmitKey)
- .append("/")
- .append(FilenameUtils.getName(containerEmitKey))
- .append(embeddedDocumentBytesConfig.getEmbeddedIdPrefix())
- .append(embeddedIdString);
+ StringBuilder emitKey =
+ new StringBuilder(containerEmitKey)
+ .append("/")
+ .append(FilenameUtils.getName(containerEmitKey))
+ .append(embeddedDocumentBytesConfig.getEmbeddedIdPrefix())
+ .append(embeddedIdString);
- if (embeddedDocumentBytesConfig.getSuffixStrategy().equals(
- EmbeddedDocumentBytesConfig.SUFFIX_STRATEGY.EXISTING)) {
+ if (embeddedDocumentBytesConfig
+ .getSuffixStrategy()
+ .equals(EmbeddedDocumentBytesConfig.SUFFIX_STRATEGY.EXISTING)) {
String fName = metadata.get(TikaCoreProperties.RESOURCE_NAME_KEY);
String suffix = FilenameUtils.getSuffixFromPath(fName);
suffix = suffix.toLowerCase(Locale.US);
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/BasicEmbeddedBytesSelector.java b/tika-core/src/main/java/org/apache/tika/extractor/BasicEmbeddedBytesSelector.java
index 1d5a239db..c86613979 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/BasicEmbeddedBytesSelector.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/BasicEmbeddedBytesSelector.java
@@ -17,7 +17,6 @@
package org.apache.tika.extractor;
import java.util.Set;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.mime.MediaType;
@@ -25,17 +24,17 @@ import org.apache.tika.utils.StringUtils;
public class BasicEmbeddedBytesSelector implements EmbeddedBytesSelector {
-
-
private final Set<String> includeMimes;
private final Set<String> excludeMimes;
private final Set<String> includeEmbeddedResourceTypes;
private final Set<String> excludeEmbeddedResourceTypes;
- public BasicEmbeddedBytesSelector(Set<String> includeMimes, Set<String> excludeMimes,
- Set<String> includeEmbeddedResourceTypes,
- Set<String> excludeEmbeddedResourceTypes) {
+ public BasicEmbeddedBytesSelector(
+ Set<String> includeMimes,
+ Set<String> excludeMimes,
+ Set<String> includeEmbeddedResourceTypes,
+ Set<String> excludeEmbeddedResourceTypes) {
this.includeMimes = includeMimes;
this.excludeMimes = excludeMimes;
this.includeEmbeddedResourceTypes = includeEmbeddedResourceTypes;
@@ -47,7 +46,7 @@ public class BasicEmbeddedBytesSelector implements EmbeddedBytesSelector {
if (mime == null) {
mime = "";
} else {
- //if mime matters at all, make sure to get the mime without parameters
+ // if mime matters at all, make sure to get the mime without parameters
if (includeMimes.size() > 0 || excludeMimes.size() > 0) {
MediaType mt = MediaType.parse(mime);
if (mt != null) {
@@ -58,18 +57,19 @@ public class BasicEmbeddedBytesSelector implements EmbeddedBytesSelector {
if (excludeMimes.contains(mime)) {
return false;
}
- if (includeMimes.size() > 0 && ! includeMimes.contains(mime)) {
+ if (includeMimes.size() > 0 && !includeMimes.contains(mime)) {
return false;
}
String embeddedResourceType = metadata.get(TikaCoreProperties.EMBEDDED_RESOURCE_TYPE);
- //if a parser doesn't specify the type, treat it as ATTACHMENT
- embeddedResourceType = StringUtils.isBlank(embeddedResourceType) ? "ATTACHMENT" :
- embeddedResourceType;
+ // if a parser doesn't specify the type, treat it as ATTACHMENT
+ embeddedResourceType =
+ StringUtils.isBlank(embeddedResourceType) ? "ATTACHMENT" : embeddedResourceType;
if (excludeEmbeddedResourceTypes.contains(embeddedResourceType)) {
return false;
}
- if (includeEmbeddedResourceTypes.size() > 0 && includeEmbeddedResourceTypes.contains(embeddedResourceType)) {
+ if (includeEmbeddedResourceTypes.size() > 0
+ && includeEmbeddedResourceTypes.contains(embeddedResourceType)) {
return true;
}
return false;
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/BasicEmbeddedDocumentBytesHandler.java b/tika-core/src/main/java/org/apache/tika/extractor/BasicEmbeddedDocumentBytesHandler.java
index cf6441b4f..7221c9cfe 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/BasicEmbeddedDocumentBytesHandler.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/BasicEmbeddedDocumentBytesHandler.java
@@ -20,27 +20,28 @@ import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
-
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.UnsynchronizedBufferedInputStream;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.pipes.extractor.EmbeddedDocumentBytesConfig;
/**
- * For now, this is an in-memory EmbeddedDocumentBytesHandler that stores
- * all the bytes in memory. Users can retrieve the documents with {@link #getDocument(int)}.
+ * For now, this is an in-memory EmbeddedDocumentBytesHandler that stores all the bytes in memory.
+ * Users can retrieve the documents with {@link #getDocument(int)}.
*
- * We'll need to make this cache to disk at some point if there are many bytes of
- * embedded documents.
+ * <p>We'll need to make this cache to disk at some point if there are many bytes of embedded
+ * documents.
*/
public class BasicEmbeddedDocumentBytesHandler extends AbstractEmbeddedDocumentBytesHandler {
private final EmbeddedDocumentBytesConfig config;
+
public BasicEmbeddedDocumentBytesHandler(EmbeddedDocumentBytesConfig config) {
this.config = config;
}
- //this won't scale, but let's start fully in memory for now;
+
+ // this won't scale, but let's start fully in memory for now;
Map<Integer, byte[]> docBytes = new HashMap<>();
+
@Override
public void add(int id, Metadata metadata, InputStream is) throws IOException {
super.add(id, metadata, is);
@@ -53,6 +54,6 @@ public class BasicEmbeddedDocumentBytesHandler extends AbstractEmbeddedDocumentB
@Override
public void close() throws IOException {
- //delete tmp dir or whatever here
+ // delete tmp dir or whatever here
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/ContainerExtractor.java b/tika-core/src/main/java/org/apache/tika/extractor/ContainerExtractor.java
index cfc70b5f3..485891162 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/ContainerExtractor.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/ContainerExtractor.java
@@ -18,47 +18,44 @@ package org.apache.tika.extractor;
import java.io.IOException;
import java.io.Serializable;
-
import org.apache.tika.exception.TikaException;
import org.apache.tika.io.TikaInputStream;
/**
- * Tika container extractor interface.
- * Container Extractors provide access to the embedded
- * resources within container formats such as .zip and .doc
+ * Tika container extractor interface. Container Extractors provide access to the embedded resources
+ * within container formats such as .zip and .doc
*/
public interface ContainerExtractor extends Serializable {
/**
- * Is this Container Extractor able to process the
- * supplied container?
+ * Is this Container Extractor able to process the supplied container?
*
* @since Apache Tika 0.8
*/
boolean isSupported(TikaInputStream input) throws IOException;
/**
- * Processes a container file, and extracts all the embedded
- * resources from within it.
- * <p>
- * The {@link EmbeddedResourceHandler} you supply will
- * be called for each embedded resource in the container. It is
- * up to you whether you process the contents of the resource or not.
- * <p>
- * The given document stream is consumed but not closed by this method.
- * The responsibility to close the stream remains on the caller.
- * <p>
- * If required, nested containers (such as a .docx within a .zip)
- * can automatically be recursed into, and processed inline. If
- * no recurseExtractor is given, the nested containers will be
- * treated as with any other embedded resources.
+ * Processes a container file, and extracts all the embedded resources from within it.
+ *
+ * <p>The {@link EmbeddedResourceHandler} you supply will be called for each embedded resource
+ * in the container. It is up to you whether you process the contents of the resource or not.
+ *
+ * <p>The given document stream is consumed but not closed by this method. The responsibility to
+ * close the stream remains on the caller.
+ *
+ * <p>If required, nested containers (such as a .docx within a .zip) can automatically be
+ * recursed into, and processed inline. If no recurseExtractor is given, the nested containers
+ * will be treated as with any other embedded resources.
*
- * @param stream the document stream (input)
+ * @param stream the document stream (input)
* @param recurseExtractor the extractor to use on any embedded containers
- * @param handler handler for the embedded files (output)
- * @throws IOException if the document stream could not be read
+ * @param handler handler for the embedded files (output)
+ * @throws IOException if the document stream could not be read
* @throws TikaException if the container could not be parsed
* @since Apache Tika 0.8
*/
- void extract(TikaInputStream stream, ContainerExtractor recurseExtractor,
- EmbeddedResourceHandler handler) throws IOException, TikaException;
+ void extract(
+ TikaInputStream stream,
+ ContainerExtractor recurseExtractor,
+ EmbeddedResourceHandler handler)
+ throws IOException, TikaException;
}
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/DefaultEmbeddedStreamTranslator.java b/tika-core/src/main/java/org/apache/tika/extractor/DefaultEmbeddedStreamTranslator.java
index 537c5ffa1..d8d4acada 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/DefaultEmbeddedStreamTranslator.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/DefaultEmbeddedStreamTranslator.java
@@ -19,24 +19,22 @@ package org.apache.tika.extractor;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
-
import org.apache.tika.config.ServiceLoader;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.utils.ServiceLoaderUtils;
/**
- * Loads EmbeddedStreamTranslators via service loading. Tries to run each
- * in turn and returns the first non-null value. If no translation has occurred,
- * this returns the original InputStream. If a translation has occurred, the
- * translator will consume the InputStream but not close it.
+ * Loads EmbeddedStreamTranslators via service loading. Tries to run each in turn and returns the
+ * first non-null value. If no translation has occurred, this returns the original InputStream. If a
+ * translation has occurred, the translator will consume the InputStream but not close it.
*/
public class DefaultEmbeddedStreamTranslator implements EmbeddedStreamTranslator {
final List<EmbeddedStreamTranslator> translators;
private static List<EmbeddedStreamTranslator> getDefaultFilters(ServiceLoader loader) {
- List<EmbeddedStreamTranslator> embeddedStreamTranslators
- = loader.loadServiceProviders(EmbeddedStreamTranslator.class);
+ List<EmbeddedStreamTranslator> embeddedStreamTranslators =
+ loader.loadServiceProviders(EmbeddedStreamTranslator.class);
ServiceLoaderUtils.sortLoadedClasses(embeddedStreamTranslators);
return embeddedStreamTranslators;
}
@@ -50,8 +48,9 @@ public class DefaultEmbeddedStreamTranslator implements EmbeddedStreamTranslator
}
/**
- * This should sniff the stream to determine if it needs to be translated.
- * The translator is responsible for resetting the stream if any bytes have been read.
+ * This should sniff the stream to determine if it needs to be translated. The translator is
+ * responsible for resetting the stream if any bytes have been read.
+ *
* @param inputStream
* @param metadata
* @return
@@ -69,6 +68,7 @@ public class DefaultEmbeddedStreamTranslator implements EmbeddedStreamTranslator
/**
* This will consume the InputStream and return a new stream of translated bytes.
+ *
* @param inputStream
* @param metadata
* @return
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/DocumentSelector.java b/tika-core/src/main/java/org/apache/tika/extractor/DocumentSelector.java
index aa34aa12b..4976fe443 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/DocumentSelector.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/DocumentSelector.java
@@ -19,24 +19,21 @@ package org.apache.tika.extractor;
import org.apache.tika.metadata.Metadata;
/**
- * Interface for different document selection strategies for purposes like
- * embedded document extraction by a {@link ContainerExtractor} instance.
- * An implementation of this interface defines some specific selection
- * criteria to be applied against the document metadata passed to the
- * {@link #select(Metadata)} method.
+ * Interface for different document selection strategies for purposes like embedded document
+ * extraction by a {@link ContainerExtractor} instance. An implementation of this interface defines
+ * some specific selection criteria to be applied against the document metadata passed to the {@link
+ * #select(Metadata)} method.
*
* @since Apache Tika 0.8
*/
public interface DocumentSelector {
/**
- * Checks if a document with the given metadata matches the specified
- * selection criteria.
+ * Checks if a document with the given metadata matches the specified selection criteria.
*
* @param metadata document metadata
- * @return <code>true</code> if the document matches the selection criteria,
- * <code>false</code> otherwise
+ * @return <code>true</code> if the document matches the selection criteria, <code>false</code>
+ * otherwise
*/
boolean select(Metadata metadata);
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedBytesSelector.java b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedBytesSelector.java
index 2ec7df667..1e8473159 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedBytesSelector.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedBytesSelector.java
@@ -26,6 +26,7 @@ public interface EmbeddedBytesSelector {
return true;
}
}
+
EmbeddedBytesSelector ACCEPT_ALL = new AcceptAll();
boolean select(Metadata metadata);
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentByteStoreExtractorFactory.java b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentByteStoreExtractorFactory.java
index f7237bd6a..15acaac88 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentByteStoreExtractorFactory.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentByteStoreExtractorFactory.java
@@ -16,18 +16,15 @@
*/
package org.apache.tika.extractor;
-
/**
- * This factory creates EmbeddedDocumentExtractors that require an
- * {@link EmbeddedDocumentBytesHandler} in the
- * {@link org.apache.tika.parser.ParseContext} should extend this.
+ * This factory creates EmbeddedDocumentExtractors that require an {@link
+ * EmbeddedDocumentBytesHandler} in the {@link org.apache.tika.parser.ParseContext} should extend
+ * this.
*
- * This is a shim interface to signal to {@link org.apache.tika.pipes.PipesServer}
- * to use the {@link @RUnpackExtractor} if the user doesn't configure a custom
- * EmbeddedDocumentExtractor.
+ * <p>This is a shim interface to signal to {@link org.apache.tika.pipes.PipesServer} to use the
+ * {@link @RUnpackExtractor} if the user doesn't configure a custom EmbeddedDocumentExtractor.
*
- * TODO: Figure out how to simplify this and allow for emitting of the source document.
+ * <p>TODO: Figure out how to simplify this and allow for emitting of the source document.
*/
-public interface EmbeddedDocumentByteStoreExtractorFactory extends EmbeddedDocumentExtractorFactory {
-
-}
+public interface EmbeddedDocumentByteStoreExtractorFactory
+ extends EmbeddedDocumentExtractorFactory {}
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentBytesHandler.java b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentBytesHandler.java
index 12357a718..e665a87a7 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentBytesHandler.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentBytesHandler.java
@@ -20,11 +20,10 @@ import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
-
import org.apache.tika.metadata.Metadata;
public interface EmbeddedDocumentBytesHandler extends Closeable {
- //we need metadata for the emitter store...can we get away without it?
+ // we need metadata for the emitter store...can we get away without it?
void add(int id, Metadata metadata, InputStream inputStream) throws IOException;
List<Integer> getIds();
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentExtractor.java b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentExtractor.java
index f80420868..f4b3cbc20 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentExtractor.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentExtractor.java
@@ -19,18 +19,17 @@ package org.apache.tika.extractor;
import java.io.IOException;
import java.io.InputStream;
-
+import org.apache.tika.metadata.Metadata;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
-import org.apache.tika.metadata.Metadata;
-
public interface EmbeddedDocumentExtractor {
boolean shouldParseEmbedded(Metadata metadata);
/**
- * Processes the supplied embedded resource, calling the delegating
- * parser with the appropriate details.
+ * Processes the supplied embedded resource, calling the delegating parser with the appropriate
+ * details.
+ *
* @param stream The embedded resource
* @param handler The handler to use
* @param metadata The metadata for the embedded resource
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentExtractorFactory.java b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentExtractorFactory.java
index 4a55052aa..3c795a893 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentExtractorFactory.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentExtractorFactory.java
@@ -18,7 +18,6 @@
package org.apache.tika.extractor;
import java.io.Serializable;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentUtil.java b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentUtil.java
index d6e2c28a8..da7ebf685 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentUtil.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedDocumentUtil.java
@@ -16,14 +16,9 @@
*/
package org.apache.tika.extractor;
-
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-
import org.apache.tika.config.TikaConfig;
import org.apache.tika.detect.Detector;
import org.apache.tika.io.TikaInputStream;
@@ -41,21 +36,22 @@ import org.apache.tika.parser.ParserDecorator;
import org.apache.tika.parser.PasswordProvider;
import org.apache.tika.parser.StatefulParser;
import org.apache.tika.utils.ExceptionUtils;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
/**
* Utility class to handle common issues with embedded documents.
- * <p/>
- * Use statically if all that is needed is getting the EmbeddedDocumentExtractor.
- * Otherwise, instantiate an instance.
- * <p/>
- * Note: This is not thread safe. Make sure to instantiate one per thread.
+ *
+ * <p>Use statically if all that is needed is getting the EmbeddedDocumentExtractor. Otherwise,
+ * instantiate an instance.
+ *
+ * <p>Note: This is not thread safe. Make sure to instantiate one per thread.
*/
public class EmbeddedDocumentUtil implements Serializable {
-
private final ParseContext context;
private final EmbeddedDocumentExtractor embeddedDocumentExtractor;
- //these are lazily initialized and can be null
+ // these are lazily initialized and can be null
private TikaConfig tikaConfig;
private MimeTypes mimeTypes;
private Detector detector;
@@ -66,12 +62,12 @@ public class EmbeddedDocumentUtil implements Serializable {
}
/**
- * This offers a uniform way to get an EmbeddedDocumentExtractor from a ParseContext.
- * As of Tika 1.15, an AutoDetectParser will automatically be added to parse
- * embedded documents if no Parser.class is specified in the ParseContext.
- * <p/>
- * If you'd prefer not to parse embedded documents, set Parser.class
- * to {@link org.apache.tika.parser.EmptyParser} in the ParseContext.
+ * This offers a uniform way to get an EmbeddedDocumentExtractor from a ParseContext. As of Tika
+ * 1.15, an AutoDetectParser will automatically be added to parse embedded documents if no
+ * Parser.class is specified in the ParseContext.
+ *
+ * <p>If you'd prefer not to parse embedded documents, set Parser.class to {@link
+ * org.apache.tika.parser.EmptyParser} in the ParseContext.
*
* @param context
* @return EmbeddedDocumentExtractor
@@ -81,8 +77,8 @@ public class EmbeddedDocumentUtil implements Serializable {
if (extractor != null) {
return extractor;
}
- //ensure that an AutoDetectParser is
- //available for parsing embedded docs TIKA-2096
+ // ensure that an AutoDetectParser is
+ // available for parsing embedded docs TIKA-2096
Parser embeddedParser = context.get(Parser.class);
if (embeddedParser == null) {
TikaConfig tikaConfig = context.get(TikaConfig.class);
@@ -98,11 +94,10 @@ public class EmbeddedDocumentUtil implements Serializable {
}
/**
- * Utility function to get the Parser that was sent in to the
- * ParseContext to handle embedded documents. If it is stateful,
- * unwrap it to get its stateless delegating parser.
- * <p>
- * If there is no Parser in the parser context, this will return null.
+ * Utility function to get the Parser that was sent in to the ParseContext to handle embedded
+ * documents. If it is stateful, unwrap it to get its stateless delegating parser.
+ *
+ * <p>If there is no Parser in the parser context, this will return null.
*
* @param context
* @return
@@ -123,7 +118,7 @@ public class EmbeddedDocumentUtil implements Serializable {
}
public Detector getDetector() {
- //be as lazy as possible and cache
+ // be as lazy as possible and cache
Detector localDetector = context.get(Detector.class);
if (localDetector != null) {
return localDetector;
@@ -138,7 +133,7 @@ public class EmbeddedDocumentUtil implements Serializable {
public MimeTypes getMimeTypes() {
MimeTypes localMimeTypes = context.get(MimeTypes.class);
- //be as lazy as possible and cache the mimeTypes
+ // be as lazy as possible and cache the mimeTypes
if (localMimeTypes != null) {
return localMimeTypes;
}
@@ -150,13 +145,13 @@ public class EmbeddedDocumentUtil implements Serializable {
}
/**
- * @return Returns a {@link TikaConfig} -- trying to find it first in the ParseContext
- * that was included during initialization, and then creating a new one from
- * via {@link TikaConfig#getDefaultConfig()} if it can't find one in the
- * ParseContext. This caches the default config so that it only has to be created once.
+ * @return Returns a {@link TikaConfig} -- trying to find it first in the ParseContext that was
+ * included during initialization, and then creating a new one from via {@link
+ * TikaConfig#getDefaultConfig()} if it can't find one in the ParseContext. This caches the
+ * default config so that it only has to be created once.
*/
public TikaConfig getTikaConfig() {
- //be as lazy as possible and cache the TikaConfig
+ // be as lazy as possible and cache the TikaConfig
if (tikaConfig == null) {
tikaConfig = context.get(TikaConfig.class);
if (tikaConfig == null) {
@@ -169,7 +164,7 @@ public class EmbeddedDocumentUtil implements Serializable {
public String getExtension(TikaInputStream is, Metadata metadata) {
String mimeString = metadata.get(Metadata.CONTENT_TYPE);
- //use the buffered mimetypes as default
+ // use the buffered mimetypes as default
MimeTypes localMimeTypes = getMimeTypes();
MimeType mimeType = null;
@@ -178,7 +173,7 @@ public class EmbeddedDocumentUtil implements Serializable {
try {
mimeType = localMimeTypes.forName(mimeString);
} catch (MimeTypeException e) {
- //swallow
+ // swallow
}
}
if (mimeType == null) {
@@ -188,12 +183,12 @@ public class EmbeddedDocumentUtil implements Serializable {
detected = true;
is.reset();
} catch (IOException | MimeTypeException e) {
- //swallow
+ // swallow
}
}
if (mimeType != null) {
if (detected) {
- //set or correct the mime type
+ // set or correct the mime type
metadata.set(Metadata.CONTENT_TYPE, mimeType.toString());
}
return mimeType.getExtension();
@@ -219,21 +214,21 @@ public class EmbeddedDocumentUtil implements Serializable {
return embeddedDocumentExtractor;
}
- public void parseEmbedded(InputStream inputStream, ContentHandler handler, Metadata metadata,
- boolean outputHtml) throws IOException, SAXException {
+ public void parseEmbedded(
+ InputStream inputStream, ContentHandler handler, Metadata metadata, boolean outputHtml)
+ throws IOException, SAXException {
embeddedDocumentExtractor.parseEmbedded(inputStream, handler, metadata, outputHtml);
}
/**
- * Tries to find an existing parser within the ParseContext.
- * It looks inside of CompositeParsers and ParserDecorators.
- * The use case is when a parser needs to parse an internal stream
- * that is _part_ of the document, e.g. rtf body inside an msg.
- * <p/>
- * Can return <code>null</code> if the context contains no parser or
- * the correct parser can't be found.
+ * Tries to find an existing parser within the ParseContext. It looks inside of CompositeParsers
+ * and ParserDecorators. The use case is when a parser needs to parse an internal stream that is
+ * _part_ of the document, e.g. rtf body inside an msg.
+ *
+ * <p>Can return <code>null</code> if the context contains no parser or the correct parser can't
+ * be found.
*
- * @param clazz parser class to search for
+ * @param clazz parser class to search for
* @param context
* @return
*/
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedResourceHandler.java b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedResourceHandler.java
index 23d00635d..de20ae4c7 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedResourceHandler.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedResourceHandler.java
@@ -17,21 +17,18 @@
package org.apache.tika.extractor;
import java.io.InputStream;
-
import org.apache.tika.mime.MediaType;
/**
- * Tika container extractor callback interface.
- * To work with a {@link ContainerExtractor}, your code needs
- * to implement this interface.
+ * Tika container extractor callback interface. To work with a {@link ContainerExtractor}, your code
+ * needs to implement this interface.
*/
public interface EmbeddedResourceHandler {
/**
- * Called to process an embedded resource within the container.
- * This will be called once per embedded resource within the
- * container, along with whatever details are available on
- * the embedded resource.
- *
+ * Called to process an embedded resource within the container. This will be called once per
+ * embedded resource within the container, along with whatever details are available on the
+ * embedded resource.
+ *
* @since Apache Tika 0.8
* @param filename The filename of the embedded resource, if known
* @param mediaType The media type of the embedded resource, if known
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedStreamTranslator.java b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedStreamTranslator.java
index b2ce05db4..4ea2c77d9 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedStreamTranslator.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/EmbeddedStreamTranslator.java
@@ -18,13 +18,11 @@ package org.apache.tika.extractor;
import java.io.IOException;
import java.io.InputStream;
-
import org.apache.tika.metadata.Metadata;
/**
- * Interface for different filtering of embedded streams.
- * Specifically, unravel OLE streams in tika-server unpack,
- * and/or handle open containers in TikaInputStream
+ * Interface for different filtering of embedded streams. Specifically, unravel OLE streams in
+ * tika-server unpack, and/or handle open containers in TikaInputStream
*
* @since Apache Tika 2.0.0
*/
@@ -32,7 +30,5 @@ public interface EmbeddedStreamTranslator {
boolean shouldTranslate(InputStream inputStream, Metadata metadata) throws IOException;
- InputStream translate(InputStream inputStream,
- Metadata metadata) throws IOException;
-
+ InputStream translate(InputStream inputStream, Metadata metadata) throws IOException;
}
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/ParserContainerExtractor.java b/tika-core/src/main/java/org/apache/tika/extractor/ParserContainerExtractor.java
index b2e9cd169..e9bf87461 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/ParserContainerExtractor.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/ParserContainerExtractor.java
@@ -20,11 +20,6 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
import org.apache.tika.config.TikaConfig;
import org.apache.tika.detect.DefaultDetector;
import org.apache.tika.detect.Detector;
@@ -38,13 +33,15 @@ import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.parser.StatefulParser;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
/**
- * An implementation of {@link ContainerExtractor} powered by the regular
- * {@link Parser} API. This allows you to easily extract out all the
- * embedded resources from within container files supported by normal Tika
- * parsers. By default the {@link AutoDetectParser} will be used, to allow
- * extraction from the widest range of containers.
+ * An implementation of {@link ContainerExtractor} powered by the regular {@link Parser} API. This
+ * allows you to easily extract out all the embedded resources from within container files supported
+ * by normal Tika parsers. By default the {@link AutoDetectParser} will be used, to allow extraction
+ * from the widest range of containers.
*/
public class ParserContainerExtractor implements ContainerExtractor {
@@ -60,8 +57,7 @@ public class ParserContainerExtractor implements ContainerExtractor {
}
public ParserContainerExtractor(TikaConfig config) {
- this(new AutoDetectParser(config),
- new DefaultDetector(config.getMimeRepository()));
+ this(new AutoDetectParser(config), new DefaultDetector(config.getMimeRepository()));
}
public ParserContainerExtractor(Parser parser, Detector detector) {
@@ -75,7 +71,8 @@ public class ParserContainerExtractor implements ContainerExtractor {
}
public void extract(
- TikaInputStream stream, ContainerExtractor recurseExtractor,
+ TikaInputStream stream,
+ ContainerExtractor recurseExtractor,
EmbeddedResourceHandler handler)
throws IOException, TikaException {
ParseContext context = new ParseContext();
@@ -93,7 +90,8 @@ public class ParserContainerExtractor implements ContainerExtractor {
private final EmbeddedResourceHandler handler;
- private RecursiveParser(Parser statelessParser,
+ private RecursiveParser(
+ Parser statelessParser,
ContainerExtractor extractor,
EmbeddedResourceHandler handler) {
super(statelessParser);
@@ -106,8 +104,7 @@ public class ParserContainerExtractor implements ContainerExtractor {
}
public void parse(
- InputStream stream, ContentHandler ignored,
- Metadata metadata, ParseContext context)
+ InputStream stream, ContentHandler ignored, Metadata metadata, ParseContext context)
throws IOException, SAXException, TikaException {
TemporaryResources tmp = new TemporaryResources();
try {
@@ -118,7 +115,7 @@ public class ParserContainerExtractor implements ContainerExtractor {
MediaType type = detector.detect(tis, metadata);
if (extractor == null) {
- // Let the handler process the embedded resource
+ // Let the handler process the embedded resource
handler.handle(filename, type, tis);
} else {
// Use a temporary file to process the stream twice
@@ -136,7 +133,5 @@ public class ParserContainerExtractor implements ContainerExtractor {
tmp.dispose();
}
}
-
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/ParsingEmbeddedDocumentExtractor.java b/tika-core/src/main/java/org/apache/tika/extractor/ParsingEmbeddedDocumentExtractor.java
index edcb78ff1..28f2d8670 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/ParsingEmbeddedDocumentExtractor.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/ParsingEmbeddedDocumentExtractor.java
@@ -22,12 +22,7 @@ import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
-
import org.apache.commons.io.input.CloseShieldInputStream;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.AttributesImpl;
-
import org.apache.tika.exception.CorruptedFileException;
import org.apache.tika.exception.EncryptedDocumentException;
import org.apache.tika.exception.TikaException;
@@ -41,10 +36,13 @@ import org.apache.tika.parser.ParseRecord;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.sax.EmbeddedContentHandler;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
/**
- * Helper class for parsers of package archives or other compound document
- * formats that support embedded or attached component documents.
+ * Helper class for parsers of package archives or other compound document formats that support
+ * embedded or attached component documents.
*
* @since Apache Tika 0.8
*/
@@ -106,13 +104,16 @@ public class ParsingEmbeddedDocumentExtractor implements EmbeddedDocumentExtract
newStream.setOpenContainer(container);
}
}
- DELEGATING_PARSER.parse(newStream, new EmbeddedContentHandler(new BodyContentHandler(handler)),
- metadata, context);
+ DELEGATING_PARSER.parse(
+ newStream,
+ new EmbeddedContentHandler(new BodyContentHandler(handler)),
+ metadata,
+ context);
} catch (EncryptedDocumentException ede) {
recordException(ede, context);
} catch (CorruptedFileException e) {
- //necessary to stop the parse to avoid infinite loops
- //on corrupt sqlite3 files
+ // necessary to stop the parse to avoid infinite loops
+ // on corrupt sqlite3 files
throw new IOException(e);
} catch (TikaException e) {
recordException(e, context);
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/ParsingEmbeddedDocumentExtractorFactory.java b/tika-core/src/main/java/org/apache/tika/extractor/ParsingEmbeddedDocumentExtractorFactory.java
index 9136228c4..f6a3611e5 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/ParsingEmbeddedDocumentExtractorFactory.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/ParsingEmbeddedDocumentExtractorFactory.java
@@ -20,8 +20,7 @@ import org.apache.tika.config.Field;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.ParseContext;
-public class ParsingEmbeddedDocumentExtractorFactory
- implements EmbeddedDocumentExtractorFactory {
+public class ParsingEmbeddedDocumentExtractorFactory implements EmbeddedDocumentExtractorFactory {
private boolean writeFileNameToContent = true;
@@ -32,8 +31,7 @@ public class ParsingEmbeddedDocumentExtractorFactory
@Override
public EmbeddedDocumentExtractor newInstance(Metadata metadata, ParseContext parseContext) {
- ParsingEmbeddedDocumentExtractor ex =
- new ParsingEmbeddedDocumentExtractor(parseContext);
+ ParsingEmbeddedDocumentExtractor ex = new ParsingEmbeddedDocumentExtractor(parseContext);
ex.setWriteFileNameToContent(writeFileNameToContent);
return ex;
}
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/RUnpackExtractor.java b/tika-core/src/main/java/org/apache/tika/extractor/RUnpackExtractor.java
index 76b297dd7..7f12f6312 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/RUnpackExtractor.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/RUnpackExtractor.java
@@ -23,14 +23,7 @@ import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
-
import org.apache.commons.io.input.CloseShieldInputStream;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.AttributesImpl;
-
import org.apache.tika.exception.CorruptedFileException;
import org.apache.tika.exception.EncryptedDocumentException;
import org.apache.tika.exception.TikaException;
@@ -42,6 +35,11 @@ import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;
import org.apache.tika.sax.EmbeddedContentHandler;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.AttributesImpl;
/**
* Recursive Unpacker and text and metadata extractor.
@@ -65,7 +63,6 @@ public class RUnpackExtractor extends ParsingEmbeddedDocumentExtractor {
this.maxEmbeddedBytesForExtraction = maxEmbeddedBytesForExtraction;
}
-
@Override
public void parseEmbedded(
InputStream stream, ContentHandler handler, Metadata metadata, boolean outputHtml)
@@ -94,7 +91,8 @@ public class RUnpackExtractor extends ParsingEmbeddedDocumentExtractor {
newStream.setOpenContainer(container);
}
}
- EmbeddedDocumentBytesHandler bytesHandler = context.get(EmbeddedDocumentBytesHandler.class);
+ EmbeddedDocumentBytesHandler bytesHandler =
+ context.get(EmbeddedDocumentBytesHandler.class);
if (bytesHandler != null) {
parseWithBytes(newStream, handler, metadata);
} else {
@@ -103,8 +101,8 @@ public class RUnpackExtractor extends ParsingEmbeddedDocumentExtractor {
} catch (EncryptedDocumentException ede) {
recordException(ede, context);
} catch (CorruptedFileException e) {
- //necessary to stop the parse to avoid infinite loops
- //on corrupt sqlite3 files
+ // necessary to stop the parse to avoid infinite loops
+ // on corrupt sqlite3 files
throw new IOException(e);
} catch (TikaException e) {
recordException(e, context);
@@ -117,8 +115,8 @@ public class RUnpackExtractor extends ParsingEmbeddedDocumentExtractor {
private void parseWithBytes(TikaInputStream stream, ContentHandler handler, Metadata metadata)
throws TikaException, IOException, SAXException {
- //TODO -- improve the efficiency of this so that we're not
- //literally writing out a file per request
+ // TODO -- improve the efficiency of this so that we're not
+ // literally writing out a file per request
Path p = stream.getPath();
try {
parse(stream, handler, metadata);
@@ -129,15 +127,19 @@ public class RUnpackExtractor extends ParsingEmbeddedDocumentExtractor {
private void parse(TikaInputStream stream, ContentHandler handler, Metadata metadata)
throws TikaException, IOException, SAXException {
- getDelegatingParser().parse(stream,
- new EmbeddedContentHandler(new BodyContentHandler(handler)),
- metadata, context);
+ getDelegatingParser()
+ .parse(
+ stream,
+ new EmbeddedContentHandler(new BodyContentHandler(handler)),
+ metadata,
+ context);
}
private void storeEmbeddedBytes(Path p, Metadata metadata) {
- if (! embeddedBytesSelector.select(metadata)) {
+ if (!embeddedBytesSelector.select(metadata)) {
if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("skipping embedded bytes {} <-> {}",
+ LOGGER.debug(
+ "skipping embedded bytes {} <-> {}",
metadata.get(Metadata.CONTENT_TYPE),
metadata.get(TikaCoreProperties.EMBEDDED_RESOURCE_TYPE));
}
@@ -148,8 +150,12 @@ public class RUnpackExtractor extends ParsingEmbeddedDocumentExtractor {
int id = metadata.getInt(TikaCoreProperties.EMBEDDED_ID);
try (InputStream is = Files.newInputStream(p)) {
if (bytesExtracted >= maxEmbeddedBytesForExtraction) {
- throw new IOException("Bytes extracted (" + bytesExtracted +
- ") >= max allowed (" + maxEmbeddedBytesForExtraction + ")");
+ throw new IOException(
+ "Bytes extracted ("
+ + bytesExtracted
+ + ") >= max allowed ("
+ + maxEmbeddedBytesForExtraction
+ + ")");
}
long maxToRead = maxEmbeddedBytesForExtraction - bytesExtracted;
@@ -157,19 +163,23 @@ public class RUnpackExtractor extends ParsingEmbeddedDocumentExtractor {
embeddedDocumentBytesHandler.add(id, metadata, boundedIs);
bytesExtracted += boundedIs.getPos();
if (boundedIs.hasHitBound()) {
- throw new IOException("Bytes extracted (" + bytesExtracted +
- ") >= max allowed (" + maxEmbeddedBytesForExtraction + "). Truncated " +
- "bytes");
+ throw new IOException(
+ "Bytes extracted ("
+ + bytesExtracted
+ + ") >= max allowed ("
+ + maxEmbeddedBytesForExtraction
+ + "). Truncated "
+ + "bytes");
}
}
} catch (IOException e) {
LOGGER.warn("problem writing out embedded bytes", e);
- //info in metadata doesn't actually make it back to the metadata list
- //because we're filtering and cloning the metadata at the end of the parse
- //which happens before we try to copy out the files.
- //TODO fix this
- //metadata.set(TikaCoreProperties.EMBEDDED_BYTES_EXCEPTION,
- // ExceptionUtils.getStackTrace(e));
+ // info in metadata doesn't actually make it back to the metadata list
+ // because we're filtering and cloning the metadata at the end of the parse
+ // which happens before we try to copy out the files.
+ // TODO fix this
+ // metadata.set(TikaCoreProperties.EMBEDDED_BYTES_EXCEPTION,
+ // ExceptionUtils.getStackTrace(e));
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/RUnpackExtractorFactory.java b/tika-core/src/main/java/org/apache/tika/extractor/RUnpackExtractorFactory.java
index a715ed25f..f70ebe0cd 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/RUnpackExtractorFactory.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/RUnpackExtractorFactory.java
@@ -20,7 +20,6 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-
import org.apache.tika.config.Field;
import org.apache.tika.exception.TikaConfigException;
import org.apache.tika.metadata.Metadata;
@@ -37,6 +36,7 @@ public class RUnpackExtractorFactory implements EmbeddedDocumentByteStoreExtract
private Set<String> embeddedBytesExcludeEmbeddedResourceTypes = Collections.EMPTY_SET;
private long maxEmbeddedBytesForExtraction = DEFAULT_MAX_EMBEDDED_BYTES_FOR_EXTRACTION;
+
@Field
public void setWriteFileNameToContent(boolean writeFileNameToContent) {
this.writeFileNameToContent = writeFileNameToContent;
@@ -52,34 +52,32 @@ public class RUnpackExtractorFactory implements EmbeddedDocumentByteStoreExtract
public void setEmbeddedBytesExcludeMimeTypes(List<String> excludeMimeTypes) {
embeddedBytesExcludeMimeTypes = new HashSet<>();
embeddedBytesExcludeMimeTypes.addAll(excludeMimeTypes);
-
}
@Field
public void setEmbeddedBytesIncludeEmbeddedResourceTypes(List<String> includeAttachmentTypes) {
embeddedBytesIncludeEmbeddedResourceTypes = new HashSet<>();
embeddedBytesIncludeEmbeddedResourceTypes.addAll(includeAttachmentTypes);
-
}
@Field
public void setEmbeddedBytesExcludeEmbeddedResourceTypes(List<String> excludeAttachmentTypes) {
embeddedBytesExcludeEmbeddedResourceTypes = new HashSet<>();
embeddedBytesExcludeEmbeddedResourceTypes.addAll(excludeAttachmentTypes);
-
}
/**
- * Total number of bytes to write out. A good zip bomb may contain petabytes
- * compressed into a few kb. Make sure that you can't fill up a disk!
+ * Total number of bytes to write out. A good zip bomb may contain petabytes compressed into a
+ * few kb. Make sure that you can't fill up a disk!
*
- * This does not include the container file in the count of bytes written out.
- * This only counts the lengths of the embedded files.
+ * <p>This does not include the container file in the count of bytes written out. This only
+ * counts the lengths of the embedded files.
*
* @param maxEmbeddedBytesForExtraction
*/
@Field
- public void setMaxEmbeddedBytesForExtraction(long maxEmbeddedBytesForExtraction) throws TikaConfigException {
+ public void setMaxEmbeddedBytesForExtraction(long maxEmbeddedBytesForExtraction)
+ throws TikaConfigException {
if (maxEmbeddedBytesForExtraction < 0) {
throw new TikaConfigException("maxEmbeddedBytesForExtraction must be >= 0");
}
@@ -88,24 +86,23 @@ public class RUnpackExtractorFactory implements EmbeddedDocumentByteStoreExtract
@Override
public EmbeddedDocumentExtractor newInstance(Metadata metadata, ParseContext parseContext) {
- RUnpackExtractor ex =
- new RUnpackExtractor(parseContext,
- maxEmbeddedBytesForExtraction);
+ RUnpackExtractor ex = new RUnpackExtractor(parseContext, maxEmbeddedBytesForExtraction);
ex.setWriteFileNameToContent(writeFileNameToContent);
ex.setEmbeddedBytesSelector(createEmbeddedBytesSelector());
return ex;
}
-
private EmbeddedBytesSelector createEmbeddedBytesSelector() {
- if (embeddedBytesIncludeMimeTypes.size() == 0 &&
- embeddedBytesExcludeMimeTypes.size() == 0 &&
- embeddedBytesIncludeEmbeddedResourceTypes.size() == 0 &&
- embeddedBytesExcludeEmbeddedResourceTypes.size() == 0) {
+ if (embeddedBytesIncludeMimeTypes.size() == 0
+ && embeddedBytesExcludeMimeTypes.size() == 0
+ && embeddedBytesIncludeEmbeddedResourceTypes.size() == 0
+ && embeddedBytesExcludeEmbeddedResourceTypes.size() == 0) {
return EmbeddedBytesSelector.ACCEPT_ALL;
}
- return new BasicEmbeddedBytesSelector(embeddedBytesIncludeMimeTypes,
- embeddedBytesExcludeMimeTypes, embeddedBytesIncludeEmbeddedResourceTypes,
+ return new BasicEmbeddedBytesSelector(
+ embeddedBytesIncludeMimeTypes,
+ embeddedBytesExcludeMimeTypes,
+ embeddedBytesIncludeEmbeddedResourceTypes,
embeddedBytesExcludeEmbeddedResourceTypes);
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/extractor/package-info.java b/tika-core/src/main/java/org/apache/tika/extractor/package-info.java
index 3d3e92b52..5917177c9 100644
--- a/tika-core/src/main/java/org/apache/tika/extractor/package-info.java
+++ b/tika-core/src/main/java/org/apache/tika/extractor/package-info.java
@@ -15,8 +15,6 @@
* limitations under the License.
*/
-/**
- * Extraction of component documents.
- */
+/** Extraction of component documents. */
@aQute.bnd.annotation.Version("1.0.0")
package org.apache.tika.extractor;
diff --git a/tika-core/src/main/java/org/apache/tika/fork/ClassLoaderProxy.java b/tika-core/src/main/java/org/apache/tika/fork/ClassLoaderProxy.java
index 51b1beeff..91707ebcd 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/ClassLoaderProxy.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/ClassLoaderProxy.java
@@ -30,15 +30,13 @@ import java.util.Set;
class ClassLoaderProxy extends ClassLoader implements ForkProxy {
- /**
- * Serial version UID
- */
+ /** Serial version UID */
private static final long serialVersionUID = -7303109260448540420L;
/**
- * Names of resources that could not be found. Used to avoid repeated
- * lookup of commonly accessed, but often not present, resources like
- * <code>META-INF/services/javax.xml.parsers.SAXParserFactory</code>.
+ * Names of resources that could not be found. Used to avoid repeated lookup of commonly
+ * accessed, but often not present, resources like <code>
+ * META-INF/services/javax.xml.parsers.SAXParserFactory</code>.
*/
private final Set<String> notFound = new HashSet<>();
@@ -149,5 +147,4 @@ class ClassLoaderProxy extends ClassLoader implements ForkProxy {
return stream.toByteArray();
}
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/ClassLoaderResource.java b/tika-core/src/main/java/org/apache/tika/fork/ClassLoaderResource.java
index 7af85ada5..dc7e71818 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/ClassLoaderResource.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/ClassLoaderResource.java
@@ -32,11 +32,10 @@ class ClassLoaderResource implements ForkResource {
}
/**
- * Processes a request for one (code 1) or many (code 2) class loader
- * resources. The requested resources are sent preceded with a boolean
- * <code>true</code> value. If the resource was not found (code 1) or
- * when the last resource has been sent (code 2), a boolean
- * <code>false</code> value is sent instead.
+ * Processes a request for one (code 1) or many (code 2) class loader resources. The requested
+ * resources are sent preceded with a boolean <code>true</code> value. If the resource was not
+ * found (code 1) or when the last resource has been sent (code 2), a boolean <code>false</code>
+ * value is sent instead.
*
* @param name resource name
* @throws IOException if the resource could not be sent
@@ -66,14 +65,12 @@ class ClassLoaderResource implements ForkResource {
}
/**
- * Sends the contents of the given input stream to the given output.
- * The stream is sent in chunks of less than 64kB, each preceded by
- * a 16-bit integer value that indicates the length of the following
- * chunk. A zero short value is sent at the end to signify the end of
- * the stream.
- * <p>
- * The stream is guaranteed to be closed by this method, regardless of
- * the way it returns.
+ * Sends the contents of the given input stream to the given output. The stream is sent in
+ * chunks of less than 64kB, each preceded by a 16-bit integer value that indicates the length
+ * of the following chunk. A zero short value is sent at the end to signify the end of the
+ * stream.
+ *
+ * <p>The stream is guaranteed to be closed by this method, regardless of the way it returns.
*
* @param stream the stream to be sent
* @throws IOException if the stream could not be sent
@@ -92,5 +89,4 @@ class ClassLoaderResource implements ForkResource {
stream.close();
}
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/ContentHandlerProxy.java b/tika-core/src/main/java/org/apache/tika/fork/ContentHandlerProxy.java
index 371dd05c5..d9430ed49 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/ContentHandlerProxy.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/ContentHandlerProxy.java
@@ -19,7 +19,6 @@ package org.apache.tika.fork;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
-
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
@@ -38,9 +37,7 @@ class ContentHandlerProxy implements ContentHandler, ForkProxy {
public static final int PROCESSING_INSTRUCTION = 9;
public static final int SKIPPED_ENTITY = 10;
- /**
- * Serial version UID
- */
+ /** Serial version UID */
private static final long serialVersionUID = 737511106054617524L;
private final int resource;
@@ -79,8 +76,8 @@ class ContentHandlerProxy implements ContentHandler, ForkProxy {
}
/**
- * Breaks the string in 21,845 size chunks to not
- * throw UTFDataFormatException at least in Oracle JDK 8.
+ * Breaks the string in 21,845 size chunks to not throw UTFDataFormatException at least in
+ * Oracle JDK 8.
*/
private void writeString(String string) throws IOException {
int max = 65535 / 3;
@@ -195,5 +192,4 @@ class ContentHandlerProxy implements ContentHandler, ForkProxy {
sendString(name);
doneSending();
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/ContentHandlerResource.java b/tika-core/src/main/java/org/apache/tika/fork/ContentHandlerResource.java
index f8971b9a6..6d3e8303d 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/ContentHandlerResource.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/ContentHandlerResource.java
@@ -19,7 +19,6 @@ package org.apache.tika.fork;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
-
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
@@ -60,8 +59,12 @@ class ContentHandlerResource implements ForkResource {
if (n >= 0) {
atts = new AttributesImpl();
for (int i = 0; i < n; i++) {
- atts.addAttribute(readString(input), readString(input), readString(input),
- readString(input), readString(input));
+ atts.addAttribute(
+ readString(input),
+ readString(input),
+ readString(input),
+ readString(input),
+ readString(input));
}
}
handler.startElement(uri, localName, qName, atts);
@@ -103,5 +106,4 @@ class ContentHandlerResource implements ForkResource {
}
return sb.toString();
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/ForkClient.java b/tika-core/src/main/java/org/apache/tika/fork/ForkClient.java
index f1a47206d..a49a53edf 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/ForkClient.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/ForkClient.java
@@ -33,14 +33,12 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import java.util.zip.ZipEntry;
-
import org.apache.commons.io.IOUtils;
-import org.xml.sax.ContentHandler;
-
import org.apache.tika.exception.TikaException;
import org.apache.tika.sax.AbstractRecursiveParserWrapperHandler;
import org.apache.tika.sax.RecursiveParserWrapperHandler;
import org.apache.tika.utils.ProcessUtils;
+import org.xml.sax.ContentHandler;
class ForkClient {
private static final AtomicInteger CLIENT_COUNTER = new AtomicInteger(0);
@@ -57,29 +55,35 @@ class ForkClient {
private final DataInputStream input;
- //this is used for debugging/smoke testing
+ // this is used for debugging/smoke testing
private final int id = CLIENT_COUNTER.incrementAndGet();
private volatile int filesProcessed = 0;
- public ForkClient(Path tikaDir, ParserFactoryFactory parserFactoryFactory, List<String> java,
- TimeoutLimits timeoutLimits) throws IOException, TikaException {
+ public ForkClient(
+ Path tikaDir,
+ ParserFactoryFactory parserFactoryFactory,
+ List<String> java,
+ TimeoutLimits timeoutLimits)
+ throws IOException, TikaException {
this(tikaDir, parserFactoryFactory, null, java, timeoutLimits);
}
/**
- * @param tikaDir directory containing jars from which to start
- * the child server and load the Parser
- * @param parserFactoryFactory factory to send to forked process to build parser
- * upon arrival
- * @param classLoader class loader to use for non-parser resource
- * (content-handler, etc.)
- * @param java java commandline to use for the commandline server
+ * @param tikaDir directory containing jars from which to start the child server and load the
+ * Parser
+ * @param parserFactoryFactory factory to send to forked process to build parser upon arrival
+ * @param classLoader class loader to use for non-parser resource (content-handler, etc.)
+ * @param java java commandline to use for the commandline server
* @throws IOException
* @throws TikaException
*/
- public ForkClient(Path tikaDir, ParserFactoryFactory parserFactoryFactory,
- ClassLoader classLoader, List<String> java, TimeoutLimits timeoutLimits)
+ public ForkClient(
+ Path tikaDir,
+ ParserFactoryFactory parserFactoryFactory,
+ ClassLoader classLoader,
+ List<String> java,
+ TimeoutLimits timeoutLimits)
throws IOException, TikaException {
jar = null;
loader = null;
@@ -130,9 +134,9 @@ class ForkClient {
}
}
-
- public ForkClient(ClassLoader loader, Object object, List<String> java,
- TimeoutLimits timeoutLimits) throws IOException, TikaException {
+ public ForkClient(
+ ClassLoader loader, Object object, List<String> java, TimeoutLimits timeoutLimits)
+ throws IOException, TikaException {
boolean ok = false;
try {
this.loader = loader;
@@ -168,8 +172,8 @@ class ForkClient {
}
/**
- * Creates a temporary jar file that can be used to bootstrap the forked
- * server process. Remember to remove the file when no longer used.
+ * Creates a temporary jar file that can be used to bootstrap the forked server process.
+ * Remember to remove the file when no longer used.
*
* @return the created jar file
* @throws IOException if the bootstrap archive could not be created
@@ -189,9 +193,9 @@ class ForkClient {
}
/**
- * Fills in the jar file used to bootstrap the forked server process.
- * All the required <code>.class</code> files and a manifest with a
- * <code>Main-Class</code> entry are written into the archive.
+ * Fills in the jar file used to bootstrap the forked server process. All the required <code>
+ * .class</code> files and a manifest with a <code>Main-Class</code> entry are written into the
+ * archive.
*
* @param file file to hold the bootstrap archive
* @throws IOException if the bootstrap archive could not be created
@@ -202,10 +206,17 @@ class ForkClient {
jar.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF"));
jar.write(manifest.getBytes(UTF_8));
- Class<?>[] bootstrap = {ForkServer.class, ForkObjectInputStream.class, ForkProxy.class,
- ClassLoaderProxy.class, MemoryURLConnection.class, MemoryURLStreamHandler.class,
- MemoryURLStreamHandlerFactory.class, MemoryURLStreamRecord.class,
- TikaException.class};
+ Class<?>[] bootstrap = {
+ ForkServer.class,
+ ForkObjectInputStream.class,
+ ForkProxy.class,
+ ClassLoaderProxy.class,
+ MemoryURLConnection.class,
+ MemoryURLStreamHandler.class,
+ MemoryURLStreamHandlerFactory.class,
+ MemoryURLStreamRecord.class,
+ TikaException.class
+ };
ClassLoader loader = ForkServer.class.getClassLoader();
for (Class<?> klass : bootstrap) {
String path = klass.getName().replace('.', '/') + ".class";
@@ -227,10 +238,11 @@ class ForkClient {
} else if (type == -1) {
throw new IOException("EOF while waiting for start beacon");
} else {
- //can't do this because of
+ // can't do this because of
// ForkParserIntegrationTest
// #testAttachingADebuggerOnTheForkedParserShouldWork
-// throw new IOException("Unexpected byte while waiting for start beacon: "+type);
+ // throw new IOException("Unexpected byte while waiting for start
+ // beacon: "+type);
}
}
}
@@ -265,10 +277,10 @@ class ForkClient {
}
/**
- * Serializes the object first into an in-memory buffer and then
- * writes it to the output stream with a preceding size integer.
+ * Serializes the object first into an in-memory buffer and then writes it to the output stream
+ * with a preceding size integer.
*
- * @param object object to be serialized
+ * @param object object to be serialized
* @param resources list of fork resources, used when adding proxies
* @throws IOException if the object could not be serialized
*/
@@ -279,12 +291,14 @@ class ForkClient {
resources.add(new InputStreamResource((InputStream) object));
object = new InputStreamProxy(n);
} else if (object instanceof RecursiveParserWrapperHandler) {
- resources.add(new RecursiveMetadataContentHandlerResource(
- (RecursiveParserWrapperHandler) object));
- object = new RecursiveMetadataContentHandlerProxy(n,
- ((RecursiveParserWrapperHandler) object).getContentHandlerFactory());
- } else if (object instanceof ContentHandler &&
- !(object instanceof AbstractRecursiveParserWrapperHandler)) {
+ resources.add(
+ new RecursiveMetadataContentHandlerResource(
+ (RecursiveParserWrapperHandler) object));
+ object =
+ new RecursiveMetadataContentHandlerProxy(
+ n, ((RecursiveParserWrapperHandler) object).getContentHandlerFactory());
+ } else if (object instanceof ContentHandler
+ && !(object instanceof AbstractRecursiveParserWrapperHandler)) {
resources.add(new ContentHandlerResource((ContentHandler) object));
object = new ContentHandlerProxy(n);
} else if (object instanceof ClassLoader) {
@@ -296,8 +310,11 @@ class ForkClient {
ForkObjectInputStream.sendObject(object, output);
} catch (NotSerializableException nse) {
// Build a more friendly error message for this
- throw new TikaException("Unable to serialize " + object.getClass().getSimpleName() +
- " to pass to the Forked Parser", nse);
+ throw new TikaException(
+ "Unable to serialize "
+ + object.getClass().getSimpleName()
+ + " to pass to the Forked Parser",
+ nse);
}
waitForResponse(resources);
@@ -316,10 +333,10 @@ class ForkClient {
if (process != null) {
process.destroyForcibly();
try {
- //TIKA-1933
+ // TIKA-1933
process.waitFor();
} catch (InterruptedException e) {
- //swallow
+ // swallow
}
}
if (jar != null) {
diff --git a/tika-core/src/main/java/org/apache/tika/fork/ForkObjectInputStream.java b/tika-core/src/main/java/org/apache/tika/fork/ForkObjectInputStream.java
index 61e2dae48..2e7b6d36b 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/ForkObjectInputStream.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/ForkObjectInputStream.java
@@ -27,28 +27,24 @@ import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
/**
- * An object input stream that uses a given class loader when deserializing
- * objects.
- * <p>
- * Note that this functionality could easily be implemented as a simple
- * anonymous {@link ObjectInputStream} subclass, but since the
- * functionality is needed during the somewhat complicated bootstrapping
- * of the stdin/out communication channel of a forked server process,
- * it's better if class has a stable name that can be referenced at
- * compile-time by the {@link ForkClient} class.
+ * An object input stream that uses a given class loader when deserializing objects.
+ *
+ * <p>Note that this functionality could easily be implemented as a simple anonymous {@link
+ * ObjectInputStream} subclass, but since the functionality is needed during the somewhat
+ * complicated bootstrapping of the stdin/out communication channel of a forked server process, it's
+ * better if class has a stable name that can be referenced at compile-time by the {@link
+ * ForkClient} class.
*/
class ForkObjectInputStream extends ObjectInputStream {
- /**
- * The class loader used when deserializing objects.
- */
+ /** The class loader used when deserializing objects. */
private final ClassLoader loader;
/**
- * Creates a new object input stream that uses the given class loader
- * when deserializing objects.
+ * Creates a new object input stream that uses the given class loader when deserializing
+ * objects.
*
- * @param input underlying input stream
+ * @param input underlying input stream
* @param loader class loader used when deserializing objects
* @throws IOException if this stream could not be initiated
*/
@@ -58,8 +54,8 @@ class ForkObjectInputStream extends ObjectInputStream {
}
/**
- * Serializes the object first into an in-memory buffer and then
- * writes it to the output stream with a preceding size integer.
+ * Serializes the object first into an in-memory buffer and then writes it to the output stream
+ * with a preceding size integer.
*
* @param object object to be serialized
* @param output output stream
@@ -77,13 +73,13 @@ class ForkObjectInputStream extends ObjectInputStream {
}
/**
- * Deserializes an object from the given stream. The serialized object
- * is expected to be preceded by a size integer, that is used for reading
- * the entire serialization into a memory before deserializing it.
+ * Deserializes an object from the given stream. The serialized object is expected to be
+ * preceded by a size integer, that is used for reading the entire serialization into a memory
+ * before deserializing it.
*
- * @param input input stream from which the serialized object is read
+ * @param input input stream from which the serialized object is read
* @param loader class loader to be used for loading referenced classes
- * @throws IOException if the object could not be deserialized
+ * @throws IOException if the object could not be deserialized
* @throws ClassNotFoundException if a referenced class is not found
*/
public static Object readObject(DataInputStream input, ClassLoader loader)
@@ -108,5 +104,4 @@ class ForkObjectInputStream extends ObjectInputStream {
protected Class<?> resolveClass(ObjectStreamClass desc) throws ClassNotFoundException {
return Class.forName(desc.getName(), false, loader);
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/ForkParser.java b/tika-core/src/main/java/org/apache/tika/fork/ForkParser.java
index 84d1156e2..2b1c9dfc2 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/ForkParser.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/ForkParser.java
@@ -27,10 +27,6 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-
import org.apache.tika.config.Field;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
@@ -41,54 +37,46 @@ import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.AbstractRecursiveParserWrapperHandler;
import org.apache.tika.sax.TeeContentHandler;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
public class ForkParser implements Parser, Closeable {
- /**
- * Serial version UID
- */
+ /** Serial version UID */
private static final long serialVersionUID = -4962742892274663950L;
- //these are used by the legacy usage
+ // these are used by the legacy usage
private final ClassLoader loader;
private final Parser parser;
- //these are used when the server builds a parser via a directory
- //of jars, not via legacy bootstrap etc.
+ // these are used when the server builds a parser via a directory
+ // of jars, not via legacy bootstrap etc.
private final Path tikaBin;
private final ParserFactoryFactory parserFactoryFactory;
private final Queue<ForkClient> pool = new LinkedList<>();
- /**
- * Java command line
- */
+
+ /** Java command line */
private List<String> java = Arrays.asList("java", "-Xmx32m", "-Djava.awt.headless=true");
- /**
- * Process pool size
- */
- @Field
- private int poolSize = 5;
+
+ /** Process pool size */
+ @Field private int poolSize = 5;
+
private int currentlyInUse = 0;
- @Field
- private long serverPulseMillis = 1000;
+ @Field private long serverPulseMillis = 1000;
- @Field
- private long serverParseTimeoutMillis = 60000;
+ @Field private long serverParseTimeoutMillis = 60000;
- @Field
- private long serverWaitTimeoutMillis = 60000;
+ @Field private long serverWaitTimeoutMillis = 60000;
- @Field
- private int maxFilesProcessedPerClient = -1;
+ @Field private int maxFilesProcessedPerClient = -1;
/**
- * If you have a directory with, say, tike-app.jar and you want the
- * forked process/server to build a parser
- * and run it from that -- so that you can keep all of those dependencies out of
+ * If you have a directory with, say, tike-app.jar and you want the forked process/server to
+ * build a parser and run it from that -- so that you can keep all of those dependencies out of
* your client code, use this initializer.
*
- * @param tikaBin directory containing the tika-app.jar or similar --
- * full jar including tika-core and all
- * desired parsers and dependencies
+ * @param tikaBin directory containing the tika-app.jar or similar -- full jar including
+ * tika-core and all desired parsers and dependencies
* @param factoryFactory
*/
public ForkParser(Path tikaBin, ParserFactoryFactory factoryFactory) {
@@ -101,16 +89,14 @@ public class ForkParser implements Parser, Closeable {
/**
* <b>EXPERT</b>
*
- * @param tikaBin directory containing the tika-app.jar or similar
- * -- full jar including tika-core and all
- * desired parsers and dependencies
- * @param parserFactoryFactory -- the factory to use to generate the parser factory
- * in the forked process/server
- * @param classLoader to use for all classes besides the parser in the
- * forked process/server
+ * @param tikaBin directory containing the tika-app.jar or similar -- full jar including
+ * tika-core and all desired parsers and dependencies
+ * @param parserFactoryFactory -- the factory to use to generate the parser factory in the
+ * forked process/server
+ * @param classLoader to use for all classes besides the parser in the forked process/server
*/
- public ForkParser(Path tikaBin, ParserFactoryFactory parserFactoryFactory,
- ClassLoader classLoader) {
+ public ForkParser(
+ Path tikaBin, ParserFactoryFactory parserFactoryFactory, ClassLoader classLoader) {
parser = null;
loader = classLoader;
this.tikaBin = tikaBin;
@@ -124,8 +110,8 @@ public class ForkParser implements Parser, Closeable {
public ForkParser(ClassLoader loader, Parser parser) {
if (parser instanceof ForkParser) {
throw new IllegalArgumentException(
- "The underlying parser of a ForkParser should not be a ForkParser, " +
- "but a specific implementation.");
+ "The underlying parser of a ForkParser should not be a ForkParser, "
+ + "but a specific implementation.");
}
this.tikaBin = null;
this.parserFactoryFactory = null;
@@ -160,13 +146,11 @@ public class ForkParser implements Parser, Closeable {
}
/**
- * Sets the command used to start the forked server process.
- * The arguments "-jar" and "/path/to/bootstrap.jar"
- * or "-cp" and "/path/to/tika_bin" are
- * appended to the given command when starting the process.
- * The default setting is {"java", "-Xmx32m"}.
- * <p/>
- * Creates a defensive copy.
+ * Sets the command used to start the forked server process. The arguments "-jar" and
+ * "/path/to/bootstrap.jar" or "-cp" and "/path/to/tika_bin" are appended to the given command
+ * when starting the process. The default setting is {"java", "-Xmx32m"}.
+ *
+ * <p>Creates a defensive copy.
*
* @param java java command line
*/
@@ -176,8 +160,8 @@ public class ForkParser implements Parser, Closeable {
/**
* Returns the command used to start the forked server process.
- * <p/>
- * Returned list is unmodifiable.
+ *
+ * <p>Returned list is unmodifiable.
*
* @return java command line args
*/
@@ -190,51 +174,45 @@ public class ForkParser implements Parser, Closeable {
}
/**
- * This sends the objects to the server for parsing, and the server via
- * the proxies acts on the handler as if it were updating it directly.
- * <p>
- * If using a {@link org.apache.tika.parser.RecursiveParserWrapper}, there are two options:
- * </p>
- * <p>
- * <ol>
- * <li>Send in a class that extends
- * {@link org.apache.tika.sax.RecursiveParserWrapperHandler},
- * and the server will proxy back the data as best it can[0].</li>
- * <li>Send in a class that extends {@link AbstractRecursiveParserWrapperHandler}
- * and the server will act on the class but not proxy back the data. This
- * can be used, for example, if all you want to do is write to disc, extend
- * {@link AbstractRecursiveParserWrapperHandler} to write to disc when
- * {@link AbstractRecursiveParserWrapperHandler#endDocument(ContentHandler,
- * Metadata)}
- * is called, and the server will take care of the writing via the handler.</li>
- * </ol>
- * </p>
+ * This sends the objects to the server for parsing, and the server via the proxies acts on the
+ * handler as if it were updating it directly.
+ *
+ * <p>If using a {@link org.apache.tika.parser.RecursiveParserWrapper}, there are two options:
+ *
* <p>
- * <b>NOTE:</b>[0] "the server will proxy back the data as best it can".
- * If the handler implements Serializable and is actually serializable, the
- * server will send it and the
- * {@link Metadata} back upon
- * {@link org.apache.tika.sax.RecursiveParserWrapperHandler#
- * endEmbeddedDocument(ContentHandler, Metadata)}
- * or {@link org.apache.tika.sax.RecursiveParserWrapperHandler#
- * endEmbeddedDocument(ContentHandler, Metadata)}.
- * If the handler does not implement {@link java.io.Serializable} or if there is a
- * {@link java.io.NotSerializableException} thrown during serialization, the server will
- * call {@link ContentHandler#toString()} on the ContentHandler and set that value with the
- * {@link TikaCoreProperties#TIKA_CONTENT} key and then
- * serialize and proxy that data back.
- * </p>
*
- * @param stream the document stream (input)
- * @param handler handler for the XHTML SAX events (output)
+ * <ol>
+ * <li>Send in a class that extends {@link org.apache.tika.sax.RecursiveParserWrapperHandler},
+ * and the server will proxy back the data as best it can[0].
+ * <li>Send in a class that extends {@link AbstractRecursiveParserWrapperHandler} and the
+ * server will act on the class but not proxy back the data. This can be used, for
+ * example, if all you want to do is write to disc, extend {@link
+ * AbstractRecursiveParserWrapperHandler} to write to disc when {@link
+ * AbstractRecursiveParserWrapperHandler#endDocument(ContentHandler, Metadata)} is called,
+ * and the server will take care of the writing via the handler.
+ * </ol>
+ *
+ * <p><b>NOTE:</b>[0] "the server will proxy back the data as best it can". If the
+ * handler implements Serializable and is actually serializable, the server will send it and the
+ * {@link Metadata} back upon {@link org.apache.tika.sax.RecursiveParserWrapperHandler#
+ * endEmbeddedDocument(ContentHandler, Metadata)} or {@link
+ * org.apache.tika.sax.RecursiveParserWrapperHandler# endEmbeddedDocument(ContentHandler,
+ * Metadata)}. If the handler does not implement {@link java.io.Serializable} or if there is a
+ * {@link java.io.NotSerializableException} thrown during serialization, the server will call
+ * {@link ContentHandler#toString()} on the ContentHandler and set that value with the {@link
+ * TikaCoreProperties#TIKA_CONTENT} key and then serialize and proxy that data back.
+ *
+ * @param stream the document stream (input)
+ * @param handler handler for the XHTML SAX events (output)
* @param metadata document metadata (input and output)
- * @param context parse context
+ * @param context parse context
* @throws IOException
* @throws SAXException
* @throws TikaException
*/
- public void parse(InputStream stream, ContentHandler handler, Metadata metadata,
- ParseContext context) throws IOException, SAXException, TikaException {
+ public void parse(
+ InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context)
+ throws IOException, SAXException, TikaException {
if (stream == null) {
throw new NullPointerException("null stream");
}
@@ -245,8 +223,9 @@ public class ForkParser implements Parser, Closeable {
ForkClient client = acquireClient();
try {
ContentHandler tee =
- (handler instanceof AbstractRecursiveParserWrapperHandler) ? handler :
- new TeeContentHandler(handler, new MetadataContentHandler(metadata));
+ (handler instanceof AbstractRecursiveParserWrapperHandler)
+ ? handler
+ : new TeeContentHandler(handler, new MetadataContentHandler(metadata));
t = client.call("parse", stream, tee, metadata, context);
alive = true;
@@ -256,10 +235,12 @@ public class ForkParser implements Parser, Closeable {
throw te;
} catch (IOException e) {
// Problem occurred on the other side
- throw new TikaException("Failed to communicate with a forked parser process." +
- " The process has most likely crashed due to some error" +
- " like running out of memory. A new process will be" +
- " started for the next parsing request.", e);
+ throw new TikaException(
+ "Failed to communicate with a forked parser process."
+ + " The process has most likely crashed due to some error"
+ + " like running out of memory. A new process will be"
+ + " started for the next parsing request.",
+ e);
} finally {
releaseClient(client, alive);
}
@@ -312,18 +293,23 @@ public class ForkParser implements Parser, Closeable {
}
private ForkClient newClient() throws IOException, TikaException {
- TimeoutLimits timeoutLimits = new TimeoutLimits(serverPulseMillis, serverParseTimeoutMillis,
- serverWaitTimeoutMillis);
+ TimeoutLimits timeoutLimits =
+ new TimeoutLimits(
+ serverPulseMillis, serverParseTimeoutMillis, serverWaitTimeoutMillis);
if (loader == null && parser == null && tikaBin != null && parserFactoryFactory != null) {
return new ForkClient(tikaBin, parserFactoryFactory, java, timeoutLimits);
- } else if (loader != null && parser != null && tikaBin == null &&
- parserFactoryFactory == null) {
+ } else if (loader != null
+ && parser != null
+ && tikaBin == null
+ && parserFactoryFactory == null) {
return new ForkClient(loader, parser, java, timeoutLimits);
- } else if (loader != null && parser == null && tikaBin != null &&
- parserFactoryFactory != null) {
+ } else if (loader != null
+ && parser == null
+ && tikaBin != null
+ && parserFactoryFactory != null) {
return new ForkClient(tikaBin, parserFactoryFactory, loader, java, timeoutLimits);
} else {
- //TODO: make this more useful
+ // TODO: make this more useful
throw new IllegalStateException("Unexpected combination of state items");
}
}
@@ -331,8 +317,8 @@ public class ForkParser implements Parser, Closeable {
private synchronized void releaseClient(ForkClient client, boolean alive) {
currentlyInUse--;
if (currentlyInUse + pool.size() < poolSize && alive) {
- if (maxFilesProcessedPerClient > 0 &&
- client.getFilesProcessed() >= maxFilesProcessedPerClient) {
+ if (maxFilesProcessedPerClient > 0
+ && client.getFilesProcessed() >= maxFilesProcessedPerClient) {
client.close();
} else {
pool.offer(client);
@@ -344,10 +330,8 @@ public class ForkParser implements Parser, Closeable {
}
/**
- * The amount of time in milliseconds that the server
- * should wait before checking to see if the parse has timed out
- * or if the wait has timed out
- * The default is 5 seconds.
+ * The amount of time in milliseconds that the server should wait before checking to see if the
+ * parse has timed out or if the wait has timed out The default is 5 seconds.
*
* @param serverPulseMillis milliseconds to sleep before checking if there has been any activity
*/
@@ -356,9 +340,8 @@ public class ForkParser implements Parser, Closeable {
}
/**
- * The maximum amount of time allowed for the server to try to parse a file.
- * If more than this time elapses, the server shuts down, and the ForkParser
- * throws an exception.
+ * The maximum amount of time allowed for the server to try to parse a file. If more than this
+ * time elapses, the server shuts down, and the ForkParser throws an exception.
*
* @param serverParseTimeoutMillis
*/
@@ -367,9 +350,9 @@ public class ForkParser implements Parser, Closeable {
}
/**
- * The maximum amount of time allowed for the server to wait for a new request to parse
- * a file. The server will shutdown after this amount of time, and a new server will have
- * to be started by a new client.
+ * The maximum amount of time allowed for the server to wait for a new request to parse a file.
+ * The server will shutdown after this amount of time, and a new server will have to be started
+ * by a new client.
*
* @param serverWaitTimeoutMillis
*/
@@ -378,17 +361,15 @@ public class ForkParser implements Parser, Closeable {
}
/**
- * If there is a slowly building memory leak in one of the parsers,
- * it is useful to set a limit on the number of files processed
- * by a server before it is shutdown and restarted. Default value is -1.
+ * If there is a slowly building memory leak in one of the parsers, it is useful to set a limit
+ * on the number of files processed by a server before it is shutdown and restarted. Default
+ * value is -1.
*
- * @param maxFilesProcessedPerClient maximum number of files that a server can handle
- * before the parser shuts down a client and creates
- * a new process. If set to -1, the server is never restarted
- * because of the number of files handled.
+ * @param maxFilesProcessedPerClient maximum number of files that a server can handle before the
+ * parser shuts down a client and creates a new process. If set to -1, the server is never
+ * restarted because of the number of files handled.
*/
public void setMaxFilesProcessedPerServer(int maxFilesProcessedPerClient) {
this.maxFilesProcessedPerClient = maxFilesProcessedPerClient;
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/ForkProxy.java b/tika-core/src/main/java/org/apache/tika/fork/ForkProxy.java
index b10eac8de..01aefc5b5 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/ForkProxy.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/ForkProxy.java
@@ -23,5 +23,4 @@ import java.io.Serializable;
public interface ForkProxy extends Serializable {
void init(DataInputStream input, DataOutputStream output);
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/ForkResource.java b/tika-core/src/main/java/org/apache/tika/fork/ForkResource.java
index 9bbd82bdd..89dc93289 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/ForkResource.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/ForkResource.java
@@ -23,5 +23,4 @@ import java.io.IOException;
public interface ForkResource {
Throwable process(DataInputStream input, DataOutputStream output) throws IOException;
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/ForkServer.java b/tika-core/src/main/java/org/apache/tika/fork/ForkServer.java
index c3249c1d1..21002d12f 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/ForkServer.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/ForkServer.java
@@ -26,11 +26,9 @@ import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
-
-import org.xml.sax.SAXException;
-
import org.apache.tika.exception.TikaException;
import org.apache.tika.parser.ParserFactory;
+import org.xml.sax.SAXException;
class ForkServer implements Runnable {
@@ -52,36 +50,39 @@ class ForkServer implements Runnable {
public static final byte INIT_LOADER_PARSER = 7;
public static final byte INIT_PARSER_FACTORY_FACTORY_LOADER = 8;
private final Object[] lock = new Object[0];
- /**
- * Input stream for reading from the parent process
- */
+
+ /** Input stream for reading from the parent process */
private final DataInputStream input;
- /**
- * Output stream for writing to the parent process
- */
+
+ /** Output stream for writing to the parent process */
private final DataOutputStream output;
+
private final boolean active = true;
- //milliseconds to sleep before checking to see if there has been any reading/writing
- //If no reading or writing in this time, shutdown the server.
+ // milliseconds to sleep before checking to see if there has been any reading/writing
+ // If no reading or writing in this time, shutdown the server.
private long serverPulseMillis = 5000;
private long serverParserTimeoutMillis = 60000;
private long serverWaitTimeoutMillis = 60000;
- //can't be class Parser because then you'd
- //have to include that in bootstrap jar (legacy mode)
+ // can't be class Parser because then you'd
+ // have to include that in bootstrap jar (legacy mode)
private Object parser;
private ClassLoader classLoader;
private boolean parsing = false;
private long since;
+
/**
- * Sets up a forked server instance using the given stdin/out
- * communication channel.
+ * Sets up a forked server instance using the given stdin/out communication channel.
*
- * @param input input stream for reading from the parent process
+ * @param input input stream for reading from the parent process
* @param output output stream for writing to the parent process
* @throws IOException if the server instance could not be created
*/
- public ForkServer(InputStream input, OutputStream output, long serverPulseMillis,
- long serverParserTimeoutMillis, long serverWaitTimeoutMillis)
+ public ForkServer(
+ InputStream input,
+ OutputStream output,
+ long serverPulseMillis,
+ long serverParserTimeoutMillis,
+ long serverWaitTimeoutMillis)
throws IOException {
this.input = new DataInputStream(input);
this.output = new DataOutputStream(output);
@@ -93,10 +94,9 @@ class ForkServer implements Runnable {
}
/**
- * Starts a forked server process using the standard input and output
- * streams for communication with the parent process. Any attempts by
- * stray code to read from standard input or write to standard output
- * is redirected to avoid interfering with the communication channel.
+ * Starts a forked server process using the standard input and output streams for communication
+ * with the parent process. Any attempts by stray code to read from standard input or write to
+ * standard output is redirected to avoid interfering with the communication channel.
*
* @param args command line arguments, ignored
* @throws Exception if the server could not be started
@@ -109,7 +109,11 @@ class ForkServer implements Runnable {
URL.setURLStreamHandlerFactory(new MemoryURLStreamHandlerFactory());
ForkServer server =
- new ForkServer(System.in, System.out, serverPulseMillis, serverParseTimeoutMillis,
+ new ForkServer(
+ System.in,
+ System.out,
+ serverPulseMillis,
+ serverParseTimeoutMillis,
serverWaitTimeoutMillis);
System.setIn(new ByteArrayInputStream(new byte[0]));
System.setOut(System.err);
@@ -128,8 +132,9 @@ class ForkServer implements Runnable {
long elapsed = System.currentTimeMillis() - since;
if (parsing && elapsed > serverParserTimeoutMillis) {
break;
- } else if (!parsing && serverWaitTimeoutMillis > 0 &&
- elapsed > serverWaitTimeoutMillis) {
+ } else if (!parsing
+ && serverWaitTimeoutMillis > 0
+ && elapsed > serverWaitTimeoutMillis) {
break;
}
}
@@ -137,12 +142,12 @@ class ForkServer implements Runnable {
}
System.exit(0);
} catch (InterruptedException e) {
- //swallow
+ // swallow
}
}
public void processRequests() {
- //initialize
+ // initialize
try {
initializeParserAndLoader();
} catch (Throwable t) {
@@ -157,7 +162,7 @@ class ForkServer implements Runnable {
}
return;
}
- //main loop
+ // main loop
try {
while (true) {
int request = input.read();
@@ -192,7 +197,7 @@ class ForkServer implements Runnable {
switch (configIndex) {
case INIT_PARSER_FACTORY_FACTORY:
if (firstObject instanceof ParserFactoryFactory) {
- //the user has submitted a parser factory, but no class loader
+ // the user has submitted a parser factory, but no class loader
classLoader = ForkServer.class.getClassLoader();
ParserFactory parserFactory = ((ParserFactoryFactory) firstObject).build();
parser = parserFactory.build();
@@ -205,7 +210,7 @@ class ForkServer implements Runnable {
if (firstObject instanceof ClassLoader) {
classLoader = (ClassLoader) firstObject;
Thread.currentThread().setContextClassLoader(classLoader);
- //parser from parent process
+ // parser from parent process
parser = readObject(classLoader);
} else {
throw new IllegalArgumentException(
@@ -214,7 +219,7 @@ class ForkServer implements Runnable {
break;
case INIT_PARSER_FACTORY_FACTORY_LOADER:
if (firstObject instanceof ParserFactoryFactory) {
- //the user has submitted a parser factory and a class loader
+ // the user has submitted a parser factory and a class loader
ParserFactory parserFactory = ((ParserFactoryFactory) firstObject).build();
parser = parserFactory.build();
classLoader = (ClassLoader) readObject(ForkServer.class.getClassLoader());
@@ -255,7 +260,6 @@ class ForkServer implements Runnable {
te.setStackTrace(toSend.getStackTrace());
ForkObjectInputStream.sendObject(te, output);
}
-
}
} finally {
synchronized (lock) {
@@ -281,12 +285,12 @@ class ForkServer implements Runnable {
}
/**
- * Deserializes an object from the given stream. The serialized object
- * is expected to be preceded by a size integer, that is used for reading
- * the entire serialization into a memory before deserializing it.
+ * Deserializes an object from the given stream. The serialized object is expected to be
+ * preceded by a size integer, that is used for reading the entire serialization into a memory
+ * before deserializing it.
*
* @param loader class loader to be used for loading referenced classes
- * @throws IOException if the object could not be deserialized
+ * @throws IOException if the object could not be deserialized
* @throws ClassNotFoundException if a referenced class is not found
*/
private Object readObject(ClassLoader loader) throws IOException, ClassNotFoundException {
diff --git a/tika-core/src/main/java/org/apache/tika/fork/InputStreamProxy.java b/tika-core/src/main/java/org/apache/tika/fork/InputStreamProxy.java
index cca9b7471..d6b9ed5d4 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/InputStreamProxy.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/InputStreamProxy.java
@@ -23,9 +23,7 @@ import java.io.InputStream;
class InputStreamProxy extends InputStream implements ForkProxy {
- /**
- * Serial version UID
- */
+ /** Serial version UID */
private static final long serialVersionUID = 4350939227765568438L;
private final int resource;
@@ -69,5 +67,4 @@ class InputStreamProxy extends InputStream implements ForkProxy {
}
return n;
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/InputStreamResource.java b/tika-core/src/main/java/org/apache/tika/fork/InputStreamResource.java
index 04ba93cdc..2fd768e2c 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/InputStreamResource.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/InputStreamResource.java
@@ -48,5 +48,4 @@ class InputStreamResource implements ForkResource {
output.flush();
return null;
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/MemoryURLConnection.java b/tika-core/src/main/java/org/apache/tika/fork/MemoryURLConnection.java
index 74a16878d..8afea7cc3 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/MemoryURLConnection.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/MemoryURLConnection.java
@@ -31,12 +31,10 @@ class MemoryURLConnection extends URLConnection {
}
@Override
- public void connect() {
- }
+ public void connect() {}
@Override
public InputStream getInputStream() {
return new ByteArrayInputStream(data);
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamHandler.java b/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamHandler.java
index bfbb886c2..23a5270bd 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamHandler.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamHandler.java
@@ -31,8 +31,7 @@ class MemoryURLStreamHandler extends URLStreamHandler {
private static final AtomicInteger counter = new AtomicInteger();
- private static final List<MemoryURLStreamRecord> records =
- new LinkedList<>();
+ private static final List<MemoryURLStreamRecord> records = new LinkedList<>();
public static URL createURL(byte[] data) {
try {
@@ -64,5 +63,4 @@ class MemoryURLStreamHandler extends URLStreamHandler {
}
throw new IOException("Unknown URL: " + u);
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamHandlerFactory.java b/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamHandlerFactory.java
index 5f3d818d9..4e0775956 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamHandlerFactory.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamHandlerFactory.java
@@ -28,5 +28,4 @@ class MemoryURLStreamHandlerFactory implements URLStreamHandlerFactory {
return null;
}
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamRecord.java b/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamRecord.java
index 8a72035fd..52a55e4df 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamRecord.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/MemoryURLStreamRecord.java
@@ -23,5 +23,4 @@ class MemoryURLStreamRecord {
public WeakReference<URL> url;
public byte[] data;
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/MetadataContentHandler.java b/tika-core/src/main/java/org/apache/tika/fork/MetadataContentHandler.java
index c1f1f5612..1c99900fa 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/MetadataContentHandler.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/MetadataContentHandler.java
@@ -16,12 +16,11 @@
*/
package org.apache.tika.fork;
+import org.apache.tika.metadata.Metadata;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
-import org.apache.tika.metadata.Metadata;
-
class MetadataContentHandler extends DefaultHandler {
private final Metadata metadata;
@@ -38,5 +37,4 @@ class MetadataContentHandler extends DefaultHandler {
metadata.add(aname, content);
}
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/ParserFactoryFactory.java b/tika-core/src/main/java/org/apache/tika/fork/ParserFactoryFactory.java
index 580b1ef43..4e0449886 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/ParserFactoryFactory.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/ParserFactoryFactory.java
@@ -17,23 +17,19 @@
package org.apache.tika.fork;
-
import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.util.Map;
-
import org.apache.tika.exception.TikaException;
import org.apache.tika.parser.ParserFactory;
/**
- * Lightweight, easily serializable class that contains enough information
- * to build a {@link ParserFactory}
+ * Lightweight, easily serializable class that contains enough information to build a {@link
+ * ParserFactory}
*/
public class ParserFactoryFactory implements Serializable {
- /**
- * Serial version UID
- */
+ /** Serial version UID */
private static final long serialVersionUID = 4710974869988895410L;
private final String className;
@@ -53,5 +49,4 @@ public class ParserFactoryFactory implements Serializable {
throw new TikaException("Couldn't create factory", e);
}
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/RecursiveMetadataContentHandlerProxy.java b/tika-core/src/main/java/org/apache/tika/fork/RecursiveMetadataContentHandlerProxy.java
index 348c33d92..05ecd93a0 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/RecursiveMetadataContentHandlerProxy.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/RecursiveMetadataContentHandlerProxy.java
@@ -23,22 +23,18 @@ import java.io.IOException;
import java.io.NotSerializableException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.sax.ContentHandlerFactory;
import org.apache.tika.sax.RecursiveParserWrapperHandler;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
/**
- * <p>This class calls #toString() on the ContentHandler, inserts it into the Metadata object
- * and serializes the Metadata object.
- * </p>
- * Ideally, this would serialize the ContentHandler and the Metadata object as separate objects,
- * but we can't guarantee that the ContentHandler is Serializable (e.g. the StringWriter in
- * the WriteOutContentHandler).
+ * This class calls #toString() on the ContentHandler, inserts it into the Metadata object and
+ * serializes the Metadata object. Ideally, this would serialize the ContentHandler and the Metadata
+ * object as separate objects, but we can't guarantee that the ContentHandler is Serializable (e.g.
+ * the StringWriter in the WriteOutContentHandler).
*/
class RecursiveMetadataContentHandlerProxy extends RecursiveParserWrapperHandler
implements ForkProxy {
@@ -49,17 +45,15 @@ class RecursiveMetadataContentHandlerProxy extends RecursiveParserWrapperHandler
public static final byte METADATA_ONLY = 4;
public static final byte COMPLETE = 5;
- /**
- * Serial version UID
- */
+ /** Serial version UID */
private static final long serialVersionUID = 737511106054617524L;
private final int resource;
private transient DataOutputStream output;
- public RecursiveMetadataContentHandlerProxy(int resource,
- ContentHandlerFactory contentHandlerFactory) {
+ public RecursiveMetadataContentHandlerProxy(
+ int resource, ContentHandlerFactory contentHandlerFactory) {
super(contentHandlerFactory);
this.resource = resource;
}
@@ -82,8 +76,9 @@ class RecursiveMetadataContentHandlerProxy extends RecursiveParserWrapperHandler
proxyBackToClient(MAIN_DOCUMENT, contentHandler, metadata);
}
- private void proxyBackToClient(int embeddedOrMainDocument, ContentHandler contentHandler,
- Metadata metadata) throws SAXException {
+ private void proxyBackToClient(
+ int embeddedOrMainDocument, ContentHandler contentHandler, Metadata metadata)
+ throws SAXException {
try {
output.write(ForkServer.RESOURCE);
output.writeByte(resource);
@@ -95,7 +90,7 @@ class RecursiveMetadataContentHandlerProxy extends RecursiveParserWrapperHandler
bytes = serialize(contentHandler);
success = true;
} catch (NotSerializableException e) {
- //object lied
+ // object lied
}
if (success) {
@@ -106,9 +101,9 @@ class RecursiveMetadataContentHandlerProxy extends RecursiveParserWrapperHandler
return;
}
}
- //if contenthandler is not allegedly or actually Serializable
- //fall back to adding contentHandler.toString() to the metadata object
- //and send that.
+ // if contenthandler is not allegedly or actually Serializable
+ // fall back to adding contentHandler.toString() to the metadata object
+ // and send that.
metadata.set(TikaCoreProperties.TIKA_CONTENT, contentHandler.toString());
output.writeByte(METADATA_ONLY);
send(metadata);
@@ -132,16 +127,15 @@ class RecursiveMetadataContentHandlerProxy extends RecursiveParserWrapperHandler
}
private byte[] serialize(Object object) throws IOException {
- //can't figure out why I'm getting an IllegalAccessException
- //when I try to use ForkedObjectInputStream, but
- //not when I do this manually ?!
+ // can't figure out why I'm getting an IllegalAccessException
+ // when I try to use ForkedObjectInputStream, but
+ // not when I do this manually ?!
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(object);
oos.flush();
}
return bos.toByteArray();
-
}
private void doneSending() throws SAXException {
diff --git a/tika-core/src/main/java/org/apache/tika/fork/RecursiveMetadataContentHandlerResource.java b/tika-core/src/main/java/org/apache/tika/fork/RecursiveMetadataContentHandlerResource.java
index 638e24daa..77fcc5a09 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/RecursiveMetadataContentHandlerResource.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/RecursiveMetadataContentHandlerResource.java
@@ -19,14 +19,12 @@ package org.apache.tika.fork;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
-
-import org.xml.sax.ContentHandler;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.sax.AbstractRecursiveParserWrapperHandler;
import org.apache.tika.sax.RecursiveParserWrapperHandler;
+import org.xml.sax.ContentHandler;
+import org.xml.sax.SAXException;
+import org.xml.sax.helpers.DefaultHandler;
class RecursiveMetadataContentHandlerResource implements ForkResource {
@@ -51,14 +49,14 @@ class RecursiveMetadataContentHandlerResource implements ForkResource {
byte handlerAndMetadataOrMetadataOnly = input.readByte();
ContentHandler localContentHandler = DEFAULT_HANDLER;
- if (handlerAndMetadataOrMetadataOnly ==
- RecursiveMetadataContentHandlerProxy.HANDLER_AND_METADATA) {
+ if (handlerAndMetadataOrMetadataOnly
+ == RecursiveMetadataContentHandlerProxy.HANDLER_AND_METADATA) {
localContentHandler = (ContentHandler) readObject(input);
- } else if (handlerAndMetadataOrMetadataOnly !=
- RecursiveMetadataContentHandlerProxy.METADATA_ONLY) {
+ } else if (handlerAndMetadataOrMetadataOnly
+ != RecursiveMetadataContentHandlerProxy.METADATA_ONLY) {
throw new IllegalArgumentException(
- "Expected HANDLER_AND_METADATA or METADATA_ONLY, but got:" +
- handlerAndMetadataOrMetadataOnly);
+ "Expected HANDLER_AND_METADATA or METADATA_ONLY, but got:"
+ + handlerAndMetadataOrMetadataOnly);
}
Metadata metadata = (Metadata) readObject(input);
@@ -82,6 +80,5 @@ class RecursiveMetadataContentHandlerResource implements ForkResource {
} catch (ClassNotFoundException e) {
throw new IOException(e);
}
-
}
}
diff --git a/tika-core/src/main/java/org/apache/tika/fork/TimeoutLimits.java b/tika-core/src/main/java/org/apache/tika/fork/TimeoutLimits.java
index 6610437c8..254783a19 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/TimeoutLimits.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/TimeoutLimits.java
@@ -22,7 +22,6 @@ class TimeoutLimits {
private final long parseTimeoutMS;
private final long waitTimeoutMS;
-
TimeoutLimits(long pulseMS, long parseTimeoutMS, long waitTimeoutMS) {
this.pulseMS = pulseMS;
this.parseTimeoutMS = parseTimeoutMS;
diff --git a/tika-core/src/main/java/org/apache/tika/fork/package-info.java b/tika-core/src/main/java/org/apache/tika/fork/package-info.java
index 74cdd062d..f03be88c3 100644
--- a/tika-core/src/main/java/org/apache/tika/fork/package-info.java
+++ b/tika-core/src/main/java/org/apache/tika/fork/package-info.java
@@ -15,8 +15,6 @@
* limitations under the License.
*/
-/**
- * Forked parser.
- */
+/** Forked parser. */
@aQute.bnd.annotation.Version("1.0.0")
package org.apache.tika.fork;
diff --git a/tika-core/src/main/java/org/apache/tika/io/BoundedInputStream.java b/tika-core/src/main/java/org/apache/tika/io/BoundedInputStream.java
index 31290cc1a..5d2a4aaee 100644
--- a/tika-core/src/main/java/org/apache/tika/io/BoundedInputStream.java
+++ b/tika-core/src/main/java/org/apache/tika/io/BoundedInputStream.java
@@ -21,16 +21,14 @@ import java.io.InputStream;
import java.io.OutputStream;
/**
- * Very slight modification of Commons' BoundedInputStream
- * so that we can figure out if this hit the bound or not.
- * <p>
- * This relies on IOUtils' skip and read to try to fully
- * read/skip inputstream.
+ * Very slight modification of Commons' BoundedInputStream so that we can figure out if this hit the
+ * bound or not.
+ *
+ * <p>This relies on IOUtils' skip and read to try to fully read/skip inputstream.
*/
public class BoundedInputStream extends InputStream {
-
- private final static int EOF = -1;
+ private static final int EOF = -1;
private final long max;
private final InputStream in;
private long pos;
@@ -54,8 +52,7 @@ public class BoundedInputStream extends InputStream {
* Invokes the delegate's <code>read(byte[])</code> method.
*
* @param b the buffer to read the bytes into
- * @return the number of bytes read or -1 if the end of stream or
- * the limit has been reached.
+ * @return the number of bytes read or -1 if the end of stream or the limit has been reached.
* @throws IOException if an I/O error occurs
*/
@Override
@@ -65,14 +62,13 @@ public class BoundedInputStream extends InputStream {
/**
* Invokes the delegate's <code>read(byte[], int, int)</code> method.
- * <p>
- * This does not have the same guarantees as IOUtil's readFully()...be careful.
*
- * @param b the buffer to read the bytes into
+ * <p>This does not have the same guarantees as IOUtil's readFully()...be careful.
+ *
+ * @param b the buffer to read the bytes into
* @param off The start offset
* @param len The number of bytes to read
- * @return the number of bytes read or -1 if the end of stream or
- * the limit has been reached.
+ * @return the number of bytes read or -1 if the end of stream or the limit has been reached.
* @throws IOException if an I/O error occurs
*/
@Override
@@ -92,9 +88,8 @@ public class BoundedInputStream extends InputStream {
}
/**
- * Invokes the delegate's <code>skip(long)</code> method.
- * As with InputStream generally, this does not guarantee reading n bytes.
- * Use IOUtils' skipFully for that functionality.
+ * Invokes the delegate's <code>skip(long)</code> method. As with InputStream generally, this
+ * does not guarantee reading n bytes. Use IOUtils' skipFully for that functionality.
*
* @param n the number of bytes to skip
* @return the actual number of bytes skipped
diff --git a/tika-core/src/main/java/org/apache/tika/io/EndianUtils.java b/tika-core/src/main/java/org/apache/tika/io/EndianUtils.java
index 242dd8c74..14d859ba1 100644
--- a/tika-core/src/main/java/org/apache/tika/io/EndianUtils.java
+++ b/tika-core/src/main/java/org/apache/tika/io/EndianUtils.java
@@ -18,16 +18,15 @@ package org.apache.tika.io;
import java.io.IOException;
import java.io.InputStream;
-
import org.apache.tika.exception.TikaException;
/**
* General Endian Related Utilties.
- * <p>
- * This class provides static utility methods for input/output operations
- * on numbers in Big and Little Endian formats.
- * <p>
- * Origin of code: Based on the version in POI
+ *
+ * <p>This class provides static utility methods for input/output operations on numbers in Big and
+ * Little Endian formats.
+ *
+ * <p>Origin of code: Based on the version in POI
*/
public class EndianUtils {
private static final int LONG_SIZE = 8;
@@ -37,7 +36,7 @@ public class EndianUtils {
*
* @param stream the InputStream from which the short is to be read
* @return the short (16-bit) value
- * @throws IOException will be propagated back to the caller
+ * @throws IOException will be propagated back to the caller
* @throws BufferUnderrunException if the stream cannot provide enough bytes
*/
public static short readShortLE(InputStream stream)
@@ -50,7 +49,7 @@ public class EndianUtils {
*
* @param stream the InputStream from which the short is to be read
* @return the short (16-bit) value
- * @throws IOException will be propagated back to the caller
+ * @throws IOException will be propagated back to the caller
* @throws BufferUnderrunException if the stream cannot provide enough bytes
*/
public static short readShortBE(InputStream stream)
@@ -81,7 +80,7 @@ public class EndianUtils {
*
* @param stream the InputStream from which the int is to be read
* @return the int (32-bit) value
- * @throws IOException will be propagated back to the caller
+ * @throws IOException will be propagated back to the caller
* @throws BufferUnderrunException if the stream cannot provide enough bytes
*/
public static long readUIntLE(InputStream stream) throws IOException, BufferUnderrunException {
@@ -100,7 +99,7 @@ public class EndianUtils {
*
* @param stream the InputStream from which the int is to be read
* @return the int (32-bit) value
- * @throws IOException will be propagated back to the caller
+ * @throws IOException will be propagated back to the caller
* @throws BufferUnderrunException if the stream cannot provide enough bytes
*/
public static long readUIntBE(InputStream stream) throws IOException, BufferUnderrunException {
@@ -119,7 +118,7 @@ public class EndianUtils {
*
* @param stream the InputStream from which the int is to be read
* @return the int (32-bit) value
- * @throws IOException will be propagated back to the caller
+ * @throws IOException will be propagated back to the caller
* @throws BufferUnderrunException if the stream cannot provide enough bytes
*/
public static int readIntLE(InputStream stream) throws IOException, BufferUnderrunException {
@@ -138,7 +137,7 @@ public class EndianUtils {
*
* @param stream the InputStream from which the int is to be read
* @return the int (32-bit) value
- * @throws IOException will be propagated back to the caller
+ * @throws IOException will be propagated back to the caller
* @throws BufferUnderrunException if the stream cannot provide enough bytes
*/
public static int readIntBE(InputStream stream) throws IOException, BufferUnderrunException {
@@ -157,7 +156,7 @@ public class EndianUtils {
*
* @param stream the InputStream from which the int is to be read
* @return the int (32-bit) value
- * @throws IOException will be propagated back to the caller
+ * @throws IOException will be propagated back to the caller
* @throws BufferUnderrunException if the stream cannot provide enough bytes
*/
public static int readIntME(InputStream stream) throws IOException, BufferUnderrunException {
@@ -176,7 +175,7 @@ public class EndianUtils {
*
* @param stream the InputStream from which the long is to be read
* @return the long (64-bit) value
- * @throws IOException will be propagated back to the caller
+ * @throws IOException will be propagated back to the caller
* @throws BufferUnderrunException if the stream cannot provide enough bytes
*/
public static long readLongLE(InputStream stream) throws IOException, BufferUnderrunException {
@@ -192,9 +191,15 @@ public class EndianUtils {
throw new BufferUnderrunException();
}
- return ((long) ch8 << 56) + ((long) ch7 << 48) + ((long) ch6 << 40) + ((long) ch5 << 32) +
- ((long) ch4 << 24) + // cast to long to preserve bit 31 (sign bit for ints)
- (ch3 << 16) + (ch2 << 8) + (ch1);
+ return ((long) ch8 << 56)
+ + ((long) ch7 << 48)
+ + ((long) ch6 << 40)
+ + ((long) ch5 << 32)
+ + ((long) ch4 << 24)
+ + // cast to long to preserve bit 31 (sign bit for ints)
+ (ch3 << 16)
+ + (ch2 << 8)
+ + (ch1);
}
/**
@@ -202,7 +207,7 @@ public class EndianUtils {
*
* @param stream the InputStream from which the long is to be read
* @return the long (64-bit) value
- * @throws IOException will be propagated back to the caller
+ * @throws IOException will be propagated back to the caller
* @throws BufferUnderrunException if the stream cannot provide enough bytes
*/
public static long readLongBE(InputStream stream) throws IOException, BufferUnderrunException {
@@ -218,14 +223,20 @@ public class EndianUtils {
throw new BufferUnderrunException();
}
- return ((long) ch1 << 56) + ((long) ch2 << 48) + ((long) ch3 << 40) + ((long) ch4 << 32) +
- ((long) ch5 << 24) + // cast to long to preserve bit 31 (sign bit for ints)
- (ch6 << 16) + (ch7 << 8) + (ch8);
+ return ((long) ch1 << 56)
+ + ((long) ch2 << 48)
+ + ((long) ch3 << 40)
+ + ((long) ch4 << 32)
+ + ((long) ch5 << 24)
+ + // cast to long to preserve bit 31 (sign bit for ints)
+ (ch6 << 16)
+ + (ch7 << 8)
+ + (ch8);
}
/**
- * Gets the integer value that is stored in UTF-8 like fashion, in Big Endian
- * but with the high bit on each number indicating if it continues or not
+ * Gets the integer value that is stored in UTF-8 like fashion, in Big Endian but with the high
+ * bit on each number indicating if it continues or not
*/
public static long readUE7(InputStream stream) throws IOException {
int i;
@@ -262,7 +273,7 @@ public class EndianUtils {
/**
* Get a LE short value from a byte array
*
- * @param data the byte array
+ * @param data the byte array
* @param offset a starting offset into the byte array
* @return the short (16-bit) value
*/
@@ -283,7 +294,7 @@ public class EndianUtils {
/**
* Get a LE unsigned short value from a byte array
*
- * @param data the byte array
+ * @param data the byte array
* @param offset a starting offset into the byte array
* @return the unsigned short (16-bit) value in an integer
*/
@@ -306,7 +317,7 @@ public class EndianUtils {
/**
* Get a BE short value from a byte array
*
- * @param data the byte array
+ * @param data the byte array
* @param offset a starting offset into the byte array
* @return the short (16-bit) value
*/
@@ -327,7 +338,7 @@ public class EndianUtils {
/**
* Get a BE unsigned short value from a byte array
*
- * @param data the byte array
+ * @param data the byte array
* @param offset a starting offset into the byte array
* @return the unsigned short (16-bit) value in an integer
*/
@@ -350,7 +361,7 @@ public class EndianUtils {
/**
* Get a LE int value from a byte array
*
- * @param data the byte array
+ * @param data the byte array
* @param offset a starting offset into the byte array
* @return the int (32-bit) value
*/
@@ -376,7 +387,7 @@ public class EndianUtils {
/**
* Get a BE int value from a byte array
*
- * @param data the byte array
+ * @param data the byte array
* @param offset a starting offset into the byte array
* @return the int (32-bit) value
*/
@@ -402,7 +413,7 @@ public class EndianUtils {
/**
* Get a LE unsigned int value from a byte array
*
- * @param data the byte array
+ * @param data the byte array
* @param offset a starting offset into the byte array
* @return the unsigned int (32-bit) value in a long
*/
@@ -424,7 +435,7 @@ public class EndianUtils {
/**
* Get a BE unsigned int value from a byte array
*
- * @param data the byte array
+ * @param data the byte array
* @param offset a starting offset into the byte array
* @return the unsigned int (32-bit) value in a long
*/
@@ -436,7 +447,7 @@ public class EndianUtils {
/**
* Get a LE long value from a byte array
*
- * @param data the byte array
+ * @param data the byte array
* @param offset a starting offset into the byte array
* @return the long (64-bit) value
*/
@@ -451,8 +462,7 @@ public class EndianUtils {
}
/**
- * Convert an 'unsigned' byte to an integer. ie, don't carry across the
- * sign.
+ * Convert an 'unsigned' byte to an integer. ie, don't carry across the sign.
*
* @param b Description of the Parameter
* @return Description of the Return Value
@@ -464,7 +474,7 @@ public class EndianUtils {
/**
* get the unsigned value of a byte.
*
- * @param data the byte array.
+ * @param data the byte array.
* @param offset a starting offset into the byte array.
* @return the unsigned value of the byte as a 16 bit short
*/
@@ -472,7 +482,6 @@ public class EndianUtils {
return (short) (data[offset] & 0xFF);
}
-
public static class BufferUnderrunException extends TikaException {
private static final long serialVersionUID = 8358288231138076276L;
diff --git a/tika-core/src/main/java/org/apache/tika/io/FilenameUtils.java b/tika-core/src/main/java/org/apache/tika/io/FilenameUtils.java
index 17bc9e920..fccf0c971 100644
--- a/tika-core/src/main/java/org/apache/tika/io/FilenameUtils.java
+++ b/tika-core/src/main/java/org/apache/tika/io/FilenameUtils.java
@@ -18,23 +18,18 @@ package org.apache.tika.io;
import java.util.HashSet;
import java.util.Locale;
-
import org.apache.tika.utils.StringUtils;
-
public class FilenameUtils {
+ /** Reserved characters */
+ public static final char[] RESERVED_FILENAME_CHARACTERS = {
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,
+ 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,
+ 0x1E, 0x1F, '?', ':', '*', '<', '>', '|'
+ };
- /**
- * Reserved characters
- */
- public final static char[] RESERVED_FILENAME_CHARACTERS =
- {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D,
- 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A,
- 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, '?', ':', '*', '<', '>', '|'};
-
- private final static HashSet<Character> RESERVED = new HashSet<>(38);
-
+ private static final HashSet<Character> RESERVED = new HashSet<>(38);
static {
for (char reservedFilenameCharacter : RESERVED_FILENAME_CHARACTERS) {
@@ -42,13 +37,12 @@ public class FilenameUtils {
}
}
-
/**
- * Scans the given file name for reserved characters on different OSs and
- * file systems and returns a sanitized version of the name with the
- * reserved chars replaced by their hexadecimal value.
- * <p>
- * For example <code>why?.zip</code> will be converted into <code>why%3F.zip</code>
+ * Scans the given file name for reserved characters on different OSs and file systems and
+ * returns a sanitized version of the name with the reserved chars replaced by their hexadecimal
+ * value.
+ *
+ * <p>For example <code>why?.zip</code> will be converted into <code>why%3F.zip</code>
*
* @param name the file name to be normalized - NOT NULL
* @return the normalized file name
@@ -63,7 +57,8 @@ public class FilenameUtils {
for (char c : name.toCharArray()) {
if (RESERVED.contains(c)) {
- sb.append('%').append((c < 16) ? "0" : "")
+ sb.append('%')
+ .append((c < 16) ? "0" : "")
.append(Integer.toHexString(c).toUpperCase(Locale.ROOT));
} else {
sb.append(c);
@@ -74,20 +69,17 @@ public class FilenameUtils {
}
/**
- * This is a duplication of the algorithm and functionality
- * available in commons io FilenameUtils. If Java's File were
- * able handle Windows file paths correctly in linux,
- * we wouldn't need this.
- * <p>
- * The goal of this is to get a filename from a path.
- * The package parsers and some other embedded doc
- * extractors could put anything into TikaCoreProperties.RESOURCE_NAME_KEY.
- * <p>
- * If a careless client used that filename as if it were a
- * filename and not a path when writing embedded files,
- * bad things could happen. Consider: "../../../my_ppt.ppt".
- * <p>
- * Consider using this in combination with {@link #normalize(String)}.
+ * This is a duplication of the algorithm and functionality available in commons io
+ * FilenameUtils. If Java's File were able handle Windows file paths correctly in linux, we
+ * wouldn't need this.
+ *
+ * <p>The goal of this is to get a filename from a path. The package parsers and some other
+ * embedded doc extractors could put anything into TikaCoreProperties.RESOURCE_NAME_KEY.
+ *
+ * <p>If a careless client used that filename as if it were a filename and not a path when
+ * writing embedded files, bad things could happen. Consider: "../../../my_ppt.ppt".
+ *
+ * <p>Consider using this in combination with {@link #normalize(String)}.
*
* @param path path to strip
* @return empty string or a filename, never null
@@ -99,8 +91,8 @@ public class FilenameUtils {
}
int unix = path.lastIndexOf("/");
int windows = path.lastIndexOf("\\");
- //some macintosh file names are stored with : as the delimiter
- //also necessary to properly handle C:somefilename
+ // some macintosh file names are stored with : as the delimiter
+ // also necessary to properly handle C:somefilename
int colon = path.lastIndexOf(":");
String cand = path.substring(Math.max(colon, Math.max(unix, windows)) + 1);
if (cand.equals("..") || cand.equals(".")) {
@@ -111,13 +103,14 @@ public class FilenameUtils {
/**
* This includes the period, e.g. ".pdf"
+ *
* @param path
* @return the suffix or an empty string if one could not be found
*/
public static String getSuffixFromPath(String path) {
String n = getName(path);
int i = n.lastIndexOf(".");
- //arbitrarily sets max extension length
+ // arbitrarily sets max extension length
if (i > -1 && n.length() - i < 6) {
return n.substring(i);
}
diff --git a/tika-core/src/main/java/org/apache/tika/io/IOUtils.java b/tika-core/src/main/java/org/apache/tika/io/IOUtils.java
index 247705b0d..f96935e1d 100644
--- a/tika-core/src/main/java/org/apache/tika/io/IOUtils.java
+++ b/tika-core/src/main/java/org/apache/tika/io/IOUtils.java
@@ -36,7 +36,8 @@ public class IOUtils {
*/
long remain = toSkip;
while (remain > 0) {
- // See https://issues.apache.org/jira/browse/IO-203 for why we use read() rather than delegating to skip()
+ // See https://issues.apache.org/jira/browse/IO-203 for why we use read() rather than
+ // delegating to skip()
final long n = input.read(buffer, 0, (int) Math.min(remain, buffer.length));
if (n < 0) { // EOF
break;
diff --git a/tika-core/src/main/java/org/apache/tika/io/InputStreamFactory.java b/tika-core/src/main/java/org/apache/tika/io/InputStreamFactory.java
index 17e416a57..6ca0e30a5 100644
--- a/tika-core/src/main/java/org/apache/tika/io/InputStreamFactory.java
+++ b/tika-core/src/main/java/org/apache/tika/io/InputStreamFactory.java
@@ -20,14 +20,13 @@ import java.io.IOException;
import java.io.InputStream;
/**
- * <p>A factory which returns a fresh {@link InputStream} for the <em>same</em>
- * resource each time.</p>
- * <p>This is typically desired where it is easier / quicker / simpler to
- * fetch a fresh {@link InputStream} to re-read a given resource, rather
- * than do any kind of buffering.</p>
- * <p>It is typically used with {@link TikaInputStream#get(InputStreamFactory)}
- * when combined with a Parser which needs to read the resource's stream
- * multiple times when processing.</p>
+ * A factory which returns a fresh {@link InputStream} for the <em>same</em> resource each time.
+ *
+ * <p>This is typically desired where it is easier / quicker / simpler to fetch a fresh {@link
+ * InputStream} to re-read a given resource, rather than do any kind of buffering.
+ *
+ * <p>It is typically used with {@link TikaInputStream#get(InputStreamFactory)} when combined with a
+ * Parser which needs to read the resource's stream multiple times when processing.
*/
public interface InputStreamFactory {
InputStream getInputStream() throws IOException;
diff --git a/tika-core/src/main/java/org/apache/tika/io/LookaheadInputStream.java b/tika-core/src/main/java/org/apache/tika/io/LookaheadInputStream.java
index 32e671e78..146d83008 100644
--- a/tika-core/src/main/java/org/apache/tika/io/LookaheadInputStream.java
+++ b/tika-core/src/main/java/org/apache/tika/io/LookaheadInputStream.java
@@ -20,24 +20,23 @@ import java.io.IOException;
import java.io.InputStream;
/**
- * Stream wrapper that make it easy to read up to n bytes ahead from
- * a stream that supports the mark feature. This class insulates the
- * underlying stream from things like possible mark(), reset() and close()
- * calls by external components that might otherwise invalidate the marked
- * state of a stream.
- * <p>
- * The recommended usage pattern of this class is:
+ * Stream wrapper that make it easy to read up to n bytes ahead from a stream that supports the mark
+ * feature. This class insulates the underlying stream from things like possible mark(), reset() and
+ * close() calls by external components that might otherwise invalidate the marked state of a
+ * stream.
+ *
+ * <p>The recommended usage pattern of this class is:
+ *
* <pre>
* try (InputStream lookahead = new LookaheadInputStream(stream, n)) {
* processStream(lookahead);
* }
* </pre>
- * <p>
- * This usage pattern guarantees that only up to n bytes from the original
- * stream can ever be read, and that the stream will have been marked and
- * then reset to its original state once the above code block exits. No
- * code in the fictional processStream() method can affect the the state of
- * the original stream.
+ *
+ * <p>This usage pattern guarantees that only up to n bytes from the original stream can ever be
+ * read, and that the stream will have been marked and then reset to its original state once the
+ * above code block exits. No code in the fictional processStream() method can affect the the state
+ * of the original stream.
*
* @since Apache Tika 0.10
*/
@@ -52,14 +51,13 @@ public class LookaheadInputStream extends InputStream {
private int mark = 0;
/**
- * Creates a lookahead wrapper for the given input stream.
- * The given input stream should support the mark feature,
- * as otherwise the state of that stream will be undefined
- * after the lookahead wrapper has been closed. As a special
- * case a <code>null</code> stream is treated as an empty stream.
+ * Creates a lookahead wrapper for the given input stream. The given input stream should support
+ * the mark feature, as otherwise the state of that stream will be undefined after the lookahead
+ * wrapper has been closed. As a special case a <code>null</code> stream is treated as an empty
+ * stream.
*
* @param stream input stream, can be <code>null</code>
- * @param n maximum number of bytes to look ahead
+ * @param n maximum number of bytes to look ahead
*/
public LookaheadInputStream(InputStream stream, int n) {
this.stream = stream;
@@ -138,5 +136,4 @@ public class LookaheadInputStream extends InputStream {
public synchronized void reset() {
position = mark;
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/io/TailStream.java b/tika-core/src/main/java/org/apache/tika/io/TailStream.java
index a1621c20b..5f335b3ba 100644
--- a/tika-core/src/main/java/org/apache/tika/io/TailStream.java
+++ b/tika-core/src/main/java/org/apache/tika/io/TailStream.java
@@ -21,66 +21,46 @@ import java.io.IOException;
import java.io.InputStream;
/**
- * <p>
- * A specialized input stream implementation which records the last portion read
- * from an underlying stream.
- * </p>
- * <p>
- * This stream implementation is useful to deal with information which is known
- * to be located at the end of a stream (e.g. ID3 v1 tags). While reading bytes
- * from the underlying stream, a given number of bytes is kept in an internal
- * buffer. This buffer can then be queried after the whole stream was read. It
- * contains the last bytes read from the original input stream.
- * </p>
+ * A specialized input stream implementation which records the last portion read from an underlying
+ * stream.
*
- * @param in the underlying input stream
+ * <p>This stream implementation is useful to deal with information which is known to be located at
+ * the end of a stream (e.g. ID3 v1 tags). While reading bytes from the underlying stream, a given
+ * number of bytes is kept in an internal buffer. This buffer can then be queried after the whole
+ * stream was read. It contains the last bytes read from the original input stream.
+ *
+ * @param in the underlying input stream
* @param tailSize the size of the tail buffer
*/
public class TailStream extends FilterInputStream {
- /**
- * Constant for the default skip buffer size.
- */
+ /** Constant for the default skip buffer size. */
private static final int SKIP_SIZE = 4096;
- /**
- * The buffer in which the tail data is stored.
- */
+ /** The buffer in which the tail data is stored. */
private final byte[] tailBuffer;
- /**
- * The size of the internal tail buffer.
- */
+ /** The size of the internal tail buffer. */
private final int tailSize;
- /**
- * A copy of the internal tail buffer used for mark() operations.
- */
+ /** A copy of the internal tail buffer used for mark() operations. */
private byte[] markBuffer;
- /**
- * The number of bytes that have been read so far.
- */
+ /** The number of bytes that have been read so far. */
private long bytesRead;
- /**
- * The number of bytes read at the last mark() operation.
- */
+ /** The number of bytes read at the last mark() operation. */
private long markBytesRead;
- /**
- * The current index into the tail buffer.
- */
+ /** The current index into the tail buffer. */
private int currentIndex;
- /**
- * A copy of the current index used for mark() operations.
- */
+ /** A copy of the current index used for mark() operations. */
private int markIndex;
/**
* Creates a new instance of {@code TailStream}.
*
- * @param in the underlying input stream
+ * @param in the underlying input stream
* @param size the size of the tail buffer
*/
public TailStream(InputStream in, int size) {
@@ -89,10 +69,7 @@ public class TailStream extends FilterInputStream {
tailBuffer = new byte[size];
}
- /**
- * {@inheritDoc} This implementation adds the read byte to the internal tail
- * buffer.
- */
+ /** {@inheritDoc} This implementation adds the read byte to the internal tail buffer. */
@Override
public int read() throws IOException {
int c = super.read();
@@ -103,9 +80,8 @@ public class TailStream extends FilterInputStream {
}
/**
- * {@inheritDoc} This implementation delegates to the underlying stream and
- * then adds the correct portion of the read buffer to the internal tail
- * buffer.
+ * {@inheritDoc} This implementation delegates to the underlying stream and then adds the
+ * correct portion of the read buffer to the internal tail buffer.
*/
@Override
public int read(byte[] buf) throws IOException {
@@ -117,9 +93,8 @@ public class TailStream extends FilterInputStream {
}
/**
- * {@inheritDoc} This implementation delegates to the underlying stream and
- * then adds the correct portion of the read buffer to the internal tail
- * buffer.
+ * {@inheritDoc} This implementation delegates to the underlying stream and then adds the
+ * correct portion of the read buffer to the internal tail buffer.
*/
@Override
public int read(byte[] buf, int ofs, int length) throws IOException {
@@ -131,8 +106,8 @@ public class TailStream extends FilterInputStream {
}
/**
- * {@inheritDoc} This implementation delegates to the {@code read()} method
- * to ensure that the tail buffer is also filled if data is skipped.
+ * {@inheritDoc} This implementation delegates to the {@code read()} method to ensure that the
+ * tail buffer is also filled if data is skipped.
*/
@Override
public long skip(long n) throws IOException {
@@ -153,9 +128,8 @@ public class TailStream extends FilterInputStream {
}
/**
- * {@inheritDoc} This implementation saves the internal state including the
- * content of the tail buffer so that it can be restored when ''reset()'' is
- * called later.
+ * {@inheritDoc} This implementation saves the internal state including the content of the tail
+ * buffer so that it can be restored when ''reset()'' is called later.
*/
@Override
public void mark(int limit) {
@@ -166,9 +140,9 @@ public class TailStream extends FilterInputStream {
}
/**
- * {@inheritDoc} This implementation restores this stream's state to the
- * state when ''mark()'' was called the last time. If ''mark()'' has not
- * been called before, this method has no effect.
+ * {@inheritDoc} This implementation restores this stream's state to the state when ''mark()''
+ * was called the last time. If ''mark()'' has not been called before, this method has no
+ * effect.
*/
@Override
public void reset() {
@@ -180,10 +154,9 @@ public class TailStream extends FilterInputStream {
}
/**
- * Returns an array with the last data read from the underlying stream. If
- * the underlying stream contained more data than the ''tailSize''
- * constructor argument, the returned array has a length of ''tailSize''.
- * Otherwise, its length equals the number of bytes read.
+ * Returns an array with the last data read from the underlying stream. If the underlying stream
+ * contained more data than the ''tailSize'' constructor argument, the returned array has a
+ * length of ''tailSize''. Otherwise, its length equals the number of bytes read.
*
* @return an array with the last data read from the underlying stream
*/
@@ -211,8 +184,8 @@ public class TailStream extends FilterInputStream {
/**
* Adds the content of the given buffer to the internal tail buffer.
*
- * @param buf the buffer
- * @param ofs the start offset in the buffer
+ * @param buf the buffer
+ * @param ofs the start offset in the buffer
* @param length the number of bytes to be copied
*/
private void appendBuf(byte[] buf, int ofs, int length) {
@@ -226,12 +199,12 @@ public class TailStream extends FilterInputStream {
}
/**
- * Replaces the content of the internal tail buffer by the last portion of
- * the given buffer. This method is called if a buffer was read from the
- * underlying stream whose length is larger than the tail buffer.
+ * Replaces the content of the internal tail buffer by the last portion of the given buffer.
+ * This method is called if a buffer was read from the underlying stream whose length is larger
+ * than the tail buffer.
*
- * @param buf the buffer
- * @param ofs the start offset in the buffer
+ * @param buf the buffer
+ * @param ofs the start offset in the buffer
* @param length the number of bytes to be copied
*/
private void replaceTailBuffer(byte[] buf, int ofs, int length) {
@@ -240,13 +213,12 @@ public class TailStream extends FilterInputStream {
}
/**
- * Copies the given buffer into the internal tail buffer at the current
- * position. This method is called if a buffer is read from the underlying
- * stream whose length is smaller than the tail buffer. In this case the
- * tail buffer is only partly overwritten.
+ * Copies the given buffer into the internal tail buffer at the current position. This method is
+ * called if a buffer is read from the underlying stream whose length is smaller than the tail
+ * buffer. In this case the tail buffer is only partly overwritten.
*
- * @param buf the buffer
- * @param ofs the start offset in the buffer
+ * @param buf the buffer
+ * @param ofs the start offset in the buffer
* @param length the number of bytes to be copied
*/
private void copyToTailBuffer(byte[] buf, int ofs, int length) {
diff --git a/tika-core/src/main/java/org/apache/tika/io/TemporaryResources.java b/tika-core/src/main/java/org/apache/tika/io/TemporaryResources.java
index c1565ab86..284ba3dee 100644
--- a/tika-core/src/main/java/org/apache/tika/io/TemporaryResources.java
+++ b/tika-core/src/main/java/org/apache/tika/io/TemporaryResources.java
@@ -22,20 +22,18 @@ import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedList;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.utils.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * Utility class for tracking and ultimately closing or otherwise disposing
- * a collection of temporary resources.
- * <p>
- * Note that this class is not thread-safe.
+ * Utility class for tracking and ultimately closing or otherwise disposing a collection of
+ * temporary resources.
+ *
+ * <p>Note that this class is not thread-safe.
*
* @since Apache Tika 0.10
*/
@@ -43,33 +41,27 @@ public class TemporaryResources implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(TemporaryResources.class);
- /**
- * Tracked resources in LIFO order.
- */
+ /** Tracked resources in LIFO order. */
private final LinkedList<Closeable> resources = new LinkedList<>();
- /**
- * Directory for temporary files, <code>null</code> for the system default.
- */
+ /** Directory for temporary files, <code>null</code> for the system default. */
private Path tempFileDir = null;
/**
- * Sets the directory to be used for the temporary files created by
- * the {@link #createTempFile(String)} method.
+ * Sets the directory to be used for the temporary files created by the {@link
+ * #createTempFile(String)} method.
*
- * @param tempFileDir temporary file directory,
- * or <code>null</code> for the system default
+ * @param tempFileDir temporary file directory, or <code>null</code> for the system default
*/
public void setTemporaryFileDirectory(Path tempFileDir) {
this.tempFileDir = tempFileDir;
}
/**
- * Sets the directory to be used for the temporary files created by
- * the {@link #createTempFile(String)} method.
+ * Sets the directory to be used for the temporary files created by the {@link
+ * #createTempFile(String)} method.
*
- * @param tempFileDir temporary file directory,
- * or <code>null</code> for the system default
+ * @param tempFileDir temporary file directory, or <code>null</code> for the system default
* @see #setTemporaryFileDirectory(Path)
*/
public void setTemporaryFileDirectory(File tempFileDir) {
@@ -77,8 +69,9 @@ public class TemporaryResources implements Closeable {
}
/**
- * Creates a temporary file that will automatically be deleted when
- * the {@link #close()} method is called, returning its path.
+ * Creates a temporary file that will automatically be deleted when the {@link #close()} method
+ * is called, returning its path.
+ *
* @param suffix -- the suffix of the file if known, starting with "." as in ".pdf"
* @return Path to created temporary file that will be deleted after closing
* @throws IOException
@@ -86,17 +79,20 @@ public class TemporaryResources implements Closeable {
public Path createTempFile(String suffix) throws IOException {
String actualSuffix = StringUtils.isBlank(suffix) ? ".tmp" : suffix;
- final Path path = tempFileDir == null ? Files.createTempFile("apache-tika-", actualSuffix) :
- Files.createTempFile(tempFileDir, "apache-tika-", actualSuffix);
- addResource(() -> {
- try {
- Files.delete(path);
- } catch (IOException e) {
- // delete when exit if current delete fail
- LOG.warn("delete tmp file fail, will delete it on exit");
- path.toFile().deleteOnExit();
- }
- });
+ final Path path =
+ tempFileDir == null
+ ? Files.createTempFile("apache-tika-", actualSuffix)
+ : Files.createTempFile(tempFileDir, "apache-tika-", actualSuffix);
+ addResource(
+ () -> {
+ try {
+ Files.delete(path);
+ } catch (IOException e) {
+ // delete when exit if current delete fail
+ LOG.warn("delete tmp file fail, will delete it on exit");
+ path.toFile().deleteOnExit();
+ }
+ });
return path;
}
@@ -105,8 +101,8 @@ public class TemporaryResources implements Closeable {
}
/**
- * Creates a temporary file that will automatically be deleted when
- * the {@link #close()} method is called, returning its path.
+ * Creates a temporary file that will automatically be deleted when the {@link #close()} method
+ * is called, returning its path.
*
* @return Path to created temporary file that will be deleted after closing
* @throws IOException
@@ -118,9 +114,10 @@ public class TemporaryResources implements Closeable {
}
return createTempFile(FilenameUtils.getSuffixFromPath(resourceName));
}
+
/**
- * Creates and returns a temporary file that will automatically be
- * deleted when the {@link #close()} method is called.
+ * Creates and returns a temporary file that will automatically be deleted when the {@link
+ * #close()} method is called.
*
* @return Created temporary file that'll be deleted after closing
* @throws IOException
@@ -131,8 +128,8 @@ public class TemporaryResources implements Closeable {
}
/**
- * Adds a new resource to the set of tracked resources that will all be
- * closed when the {@link #close()} method is called.
+ * Adds a new resource to the set of tracked resources that will all be closed when the {@link
+ * #close()} method is called.
*
* @param resource resource to be tracked
*/
@@ -141,8 +138,8 @@ public class TemporaryResources implements Closeable {
}
/**
- * Returns the latest of the tracked resources that implements or
- * extends the given interface or class.
+ * Returns the latest of the tracked resources that implements or extends the given interface or
+ * class.
*
* @param klass interface or class
* @return matching resource, or <code>null</code> if not found
@@ -158,15 +155,13 @@ public class TemporaryResources implements Closeable {
}
/**
- * Closes all tracked resources. The resources are closed in reverse order
- * from how they were added.
- * <p>
- * Any suppressed exceptions from managed resources are collected and
- * then added to the first thrown exception, which is re-thrown once
- * all the resources have been closed.
+ * Closes all tracked resources. The resources are closed in reverse order from how they were
+ * added.
*
- * @throws IOException if one or more of the tracked resources
- * could not be closed
+ * <p>Any suppressed exceptions from managed resources are collected and then added to the first
+ * thrown exception, which is re-thrown once all the resources have been closed.
+ *
+ * @throws IOException if one or more of the tracked resources could not be closed
*/
public void close() throws IOException {
// Release all resources and keep track of any exceptions
@@ -191,12 +186,10 @@ public class TemporaryResources implements Closeable {
}
/**
- * Calls the {@link #close()} method and wraps the potential
- * {@link IOException} into a {@link TikaException} for convenience
- * when used within Tika.
+ * Calls the {@link #close()} method and wraps the potential {@link IOException} into a {@link
+ * TikaException} for convenience when used within Tika.
*
- * @throws TikaException if one or more of the tracked resources
- * could not be closed
+ * @throws TikaException if one or more of the tracked resources could not be closed
*/
public void dispose() throws TikaException {
try {
@@ -205,5 +198,4 @@ public class TemporaryResources implements Closeable {
throw new TikaException("Failed to close temporary resources", e);
}
}
-
}
diff --git a/tika-core/src/main/java/org/apache/tika/io/TikaInputStream.java b/tika-core/src/main/java/org/apache/tika/io/TikaInputStream.java
index a70ade4c3..b121ad4e3 100644
--- a/tika-core/src/main/java/org/apache/tika/io/TikaInputStream.java
+++ b/tika-core/src/main/java/org/apache/tika/io/TikaInputStream.java
@@ -35,97 +35,88 @@ import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Blob;
import java.sql.SQLException;
-
import org.apache.commons.io.input.TaggedInputStream;
import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream;
-
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.Parser;
import org.apache.tika.utils.StringUtils;
/**
- * Input stream with extended capabilities. The purpose of this class is
- * to allow files and other resources and information to be associated with
- * the {@link InputStream} instance passed through the
- * {@link org.apache.tika.parser.Parser} interface and other similar APIs.
- * <p>
- * TikaInputStream instances can be created using the various static
- * <code>get()</code> factory methods. Most of these methods take an optional
- * {@link Metadata} argument that is then filled with the available input
- * metadata from the given resource. The created TikaInputStream instance
- * keeps track of the original resource used to create it, while behaving
- * otherwise just like a normal, buffered {@link InputStream}.
- * A TikaInputStream instance is also guaranteed to support the
- * {@link #mark(int)} feature.
- * <p>
- * Code that wants to access the underlying file or other resources
- * associated with a TikaInputStream should first use the
- * {@link #get(InputStream)} factory method to cast or wrap a given
- * {@link InputStream} into a TikaInputStream instance.
- * <p>
- * TikaInputStream includes a few safety features to protect against parsers
- * that may fail to check for an EOF or may incorrectly rely on the unreliable
- * value returned from {@link FileInputStream#skip}. These parser failures
- * can lead to infinite loops. We strongly encourage the use of
- * TikaInputStream.
+ * Input stream with extended capabilities. The purpose of this class is to allow files and other
+ * resources and information to be associated with the {@link InputStream} instance passed through
+ * the {@link org.apache.tika.parser.Parser} interface and other similar APIs.
+ *
+ * <p>TikaInputStream instances can be created using the various static <code>get()</code> factory
+ * methods. Most of these methods take an optional {@link Metadata} argument that is then filled
+ * with the available input metadata from the given resource. The created TikaInputStream instance
+ * keeps track of the original resource used to create it, while behaving otherwise just like a
+ * normal, buffered {@link InputStream}. A TikaInputStream instance is also guaranteed to support
+ * the {@link #mark(int)} feature.
+ *
+ * <p>Code that wants to access the underlying file or other resources associated with a
+ * TikaInputStream should first use the {@link #get(InputStream)} factory method to cast or wrap a
+ * given {@link InputStream} into a TikaInputStream instance.
+ *
+ * <p>TikaInputStream includes a few safety features to protect against parsers that may fail to
+ * check for an EOF or may incorrectly rely on the unreliable value returned from {@link
+ * FileInputStream#skip}. These parser failures can lead to infinite loops. We strongly encourage
+ * the use of TikaInputStream.
*
* @since Apache Tika 0.8
*/
public class TikaInputStream extends TaggedInputStream {
private static final int MAX_CONSECUTIVE_EOFS = 1000;
+
/**
- * Blob size threshold that limits the largest BLOB size to be
- * buffered fully in memory by the {@link #get(Blob, Metadata)}
- * method.
+ * Blob size threshold that limits the largest BLOB size to be buffered fully in memory by the
+ * {@link #get(Blob, Metadata)} method.
*/
private static final int BLOB_SIZE_THRESHOLD = 1024 * 1024;
- /**
- * Tracker of temporary resources.
- */
+
+ /** Tracker of temporary resources. */
private final TemporaryResources tmp;
+
/**
- * The Factory that can create fresh {@link InputStream}s for
- * the resource this reads for, eg when needing to re-read.
+ * The Factory that can create fresh {@link InputStream}s for the resource this reads for, eg
+ * when needing to re-read.
*/
private InputStreamFactory streamFactory;
+
/**
- * The path to the file that contains the contents of this stream.
- * This is either the original file passed to the
- * {@link #TikaInputStream(Path)} constructor or a temporary file created
- * by a call to the {@link #getPath()} method. If neither has been called,
- * then the value is <code>null</code>.
+ * The path to the file that contains the contents of this stream. This is either the original
+ * file passed to the {@link #TikaInputStream(Path)} constructor or a temporary file created by
+ * a call to the {@link #getPath()} method. If neither has been called, then the value is <code>
+ * null</code>.
*/
private Path path;
- /**
- * Total length of the stream, or -1 if unknown.
- */
+
+ /** Total length of the stream, or -1 if unknown. */
private long length;
- /**
- * Current read position within this stream.
- */
+
+ /** Current read position within this stream. */
private long position = 0;
- /**
- * Marked position, or -1 if there is no current mark.
- */
+
+ /** Marked position, or -1 if there is no current mark. */
private long mark = -1;
+
/**
- * A opened container, such as a POIFS FileSystem
- * for an OLE2 document, or a Zip file for a
- * zip based (eg ooxml, odf) document.
+ * A opened container, such as a POIFS FileSystem for an OLE2 document, or a Zip file for a zip
+ * based (eg ooxml, odf) document.
*/
private Object openContainer;
+
private int consecutiveEOFs = 0;
private byte[] skipBuffer;
- //suffix of the file if known. This is used to create temp files
- //with the right suffixes. This should include the initial . as in ".doc"
+ // suffix of the file if known. This is used to create temp files
+ // with the right suffixes. This should include the initial . as in ".doc"
private String suffix = null;
... 34540 lines suppressed ...