From 9b639b2a758355c9047985e27b19c68041f7d673 Mon Sep 17 00:00:00 2001 From: duncdrum Date: Tue, 31 Mar 2026 11:15:22 +0200 Subject: [PATCH 1/9] [ignore] update .gitignore to include moderne configuration - Added .moderne directory to .gitignore while excluding context and moderne.yml files to ensure proper handling of prethink output. --- .gitignore | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.gitignore b/.gitignore index 2f96c7e51c2..e69f3843bf6 100644 --- a/.gitignore +++ b/.gitignore @@ -26,6 +26,9 @@ work/ # Claude planning files plans/ .codacy/ +.moderne/ +!.moderne/context/ +!.moderne/moderne.yml # Debug logs (e.g. from reindex investigation) reindex-dbg.log From f5859d860d7a4ec803a4dd2717a324c4e100527b Mon Sep 17 00:00:00 2001 From: duncdrum Date: Mon, 30 Mar 2026 17:43:13 +0200 Subject: [PATCH 2/9] [refactor] java 21 updates mod run . --recipe org.openrewrite.java.migrate.UpgradeToJava21 --- .../main/java/org/exist/ant/BackupTask.java | 4 +- .../java/org/exist/ant/XMLDBExtractTask.java | 4 +- .../java/org/exist/ant/AbstractTaskTest.java | 3 +- .../java/org/exist/ant/ServerTaskTest.java | 3 +- .../src/main/java/org/exist/BTreeTest.java | 5 +- .../main/java/org/exist/EXistException.java | 3 + .../src/main/java/org/exist/TestUtils.java | 3 +- .../main/java/org/exist/backup/Backup.java | 17 +- .../java/org/exist/backup/BackupDialog.java | 2 + .../org/exist/backup/BackupDirectory.java | 3 +- .../org/exist/backup/ConsistencyCheck.java | 4 +- .../org/exist/backup/CreateBackupDialog.java | 5 +- .../main/java/org/exist/backup/ExportGUI.java | 17 +- .../java/org/exist/backup/ExportMain.java | 3 +- .../backup/FileSystemBackupDescriptor.java | 6 +- .../org/exist/backup/FileSystemWriter.java | 3 +- .../src/main/java/org/exist/backup/Main.java | 23 +- .../java/org/exist/backup/RestoreDialog.java | 2 + .../java/org/exist/backup/SystemExport.java | 13 +- .../backup/ZipArchiveBackupDescriptor.java | 12 +- .../main/java/org/exist/backup/ZipWriter.java | 3 +- .../restore/AbstractRestoreHandler.java | 6 +- .../org/exist/backup/xquery/ListBackups.java | 3 +- .../exist/backup/xquery/RetrieveBackup.java | 5 +- .../java/org/exist/client/ClientFrame.java | 36 +- .../org/exist/client/ConnectionDialog.java | 7 +- .../java/org/exist/client/DocumentView.java | 21 +- .../client/HighlightedTableCellRenderer.java | 14 +- .../java/org/exist/client/IndexDialog.java | 15 +- .../org/exist/client/InteractiveClient.java | 77 +- .../java/org/exist/client/QueryDialog.java | 10 +- .../org/exist/client/ResourceDescriptor.java | 6 +- .../java/org/exist/client/TriggersDialog.java | 5 + .../java/org/exist/client/UploadDialog.java | 4 +- .../client/security/EditGroupDialog.java | 4 +- .../exist/client/security/EditUserDialog.java | 4 +- .../exist/client/security/GroupDialog.java | 2 + .../security/ReadOnlyDefaultTableModel.java | 3 + .../client/security/RegExpInputVerifier.java | 4 +- .../client/security/SortedListModel.java | 10 +- .../exist/client/security/UmaskEditor.java | 5 +- .../client/security/UmaskEditorFormatter.java | 2 + .../client/security/UmaskSpinnerModel.java | 2 +- .../org/exist/client/security/UserDialog.java | 4 +- .../client/security/UserManagerDialog.java | 2 + .../CollectionConfigurationException.java | 5 +- .../exist/collections/LockedCollection.java | 4 +- .../triggers/TriggerException.java | 5 +- .../triggers/TriggerStatePerThread.java | 4 +- .../collections/triggers/XQueryTrigger.java | 4 +- .../config/ConfigurationDocumentTrigger.java | 4 +- .../exist/config/ConfigurationException.java | 3 + .../java/org/exist/config/Configurator.java | 28 +- .../org/exist/debugger/ExceptionTimeout.java | 5 +- .../main/java/org/exist/dom/NodeListImpl.java | 2 + .../org/exist/dom/memtree/ElementImpl.java | 8 +- .../java/org/exist/dom/memtree/NodeImpl.java | 4 +- .../exist/dom/persistent/DocumentImpl.java | 4 +- .../org/exist/dom/persistent/ElementImpl.java | 8 +- .../exist/dom/persistent/ExtArrayNodeSet.java | 8 +- .../exist/dom/persistent/NewArrayNodeSet.java | 16 +- .../org/exist/dom/persistent/NodeProxy.java | 12 +- .../org/exist/dom/persistent/StoredNode.java | 6 +- .../org/exist/http/BadRequestException.java | 5 +- .../main/java/org/exist/http/Descriptor.java | 9 +- .../exist/http/MethodNotAllowedException.java | 3 + .../org/exist/http/NotFoundException.java | 5 +- .../main/java/org/exist/http/Response.java | 10 +- .../org/exist/http/filter/GuestFilter.java | 4 +- .../org/exist/http/filter/PathFilter.java | 4 +- .../servlets/AbstractExistHttpServlet.java | 19 +- .../org/exist/http/servlets/EXistServlet.java | 6 +- .../http/servlets/HttpRequestWrapper.java | 20 +- .../http/servlets/RedirectorServlet.java | 5 +- .../exist/http/servlets/XQueryServlet.java | 27 +- .../org/exist/http/servlets/XSLTServlet.java | 12 +- .../exist/http/urlrewrite/RewriteConfig.java | 7 +- .../http/urlrewrite/XQueryURLRewrite.java | 5 +- .../java/org/exist/indexing/IndexManager.java | 4 +- .../java/org/exist/indexing/ReindexScope.java | 16 +- .../main/java/org/exist/jetty/JettyStart.java | 11 +- .../java/org/exist/jetty/ServerShutdown.java | 2 +- .../exist/launcher/ConfigurationDialog.java | 7 +- .../java/org/exist/launcher/Launcher.java | 25 +- .../org/exist/launcher/LauncherWrapper.java | 9 +- .../java/org/exist/launcher/SplashScreen.java | 2 + .../exist/launcher/WindowsServiceManager.java | 5 +- .../exist/management/client/JMXClient.java | 58 +- .../exist/management/client/JMXServlet.java | 7 +- .../exist/management/impl/BinaryValues.java | 14 +- .../org/exist/repo/AutoDeploymentTrigger.java | 5 +- .../java/org/exist/repo/ClasspathHelper.java | 3 +- .../main/java/org/exist/repo/Deployment.java | 4 +- .../java/org/exist/repo/ExistRepository.java | 17 +- .../org/exist/resolver/ResolverFactory.java | 4 +- .../org/exist/scheduler/JobException.java | 5 +- .../org/exist/scheduler/ScheduledJobInfo.java | 8 +- .../org/exist/scheduler/UserXQueryJob.java | 6 +- .../scheduler/impl/QuartzSchedulerImpl.java | 16 +- .../org/exist/security/AbstractAccount.java | 8 +- .../org/exist/security/AbstractSubject.java | 4 +- .../security/AuthenticationException.java | 5 +- .../security/PermissionDeniedException.java | 5 +- .../org/exist/security/PermissionFactory.java | 12 +- .../security/PermissionRequiredAspect.java | 6 +- .../exist/security/SimpleACLPermission.java | 4 +- .../org/exist/security/internal/Password.java | 4 +- .../security/internal/web/HttpAccount.java | 8 +- .../java/org/exist/source/AbstractSource.java | 4 +- .../java/org/exist/source/SourceFactory.java | 27 +- .../main/java/org/exist/source/URLSource.java | 24 +- .../org/exist/storage/BackupSystemTask.java | 3 +- .../java/org/exist/storage/BrokerPool.java | 10 +- .../java/org/exist/storage/BrokerPools.java | 4 +- .../exist/storage/ConsistencyCheckTask.java | 3 +- .../java/org/exist/storage/DataBackup.java | 3 +- .../java/org/exist/storage/NativeBroker.java | 23 +- .../org/exist/storage/ProcessMonitor.java | 2 +- .../java/org/exist/storage/XQueryPool.java | 4 +- .../org/exist/storage/blob/BlobStoreImpl.java | 8 +- .../exist/storage/btree/BTreeException.java | 5 +- .../org/exist/storage/btree/DBException.java | 7 +- .../java/org/exist/storage/btree/Value.java | 8 +- .../java/org/exist/storage/index/BFile.java | 4 +- .../org/exist/storage/journal/Journal.java | 2 +- .../exist/storage/journal/LogException.java | 5 +- .../storage/lock/EnsureLockingAspect.java | 8 +- .../exist/storage/lock/FileLockService.java | 3 +- .../serializers/ChainOfReceiversFactory.java | 4 +- .../CustomMatchListenerFactory.java | 4 +- .../exist/storage/serializers/Serializer.java | 8 +- .../storage/serializers/XIncludeFilter.java | 5 +- .../storage/txn/TransactionException.java | 3 + .../exist/storage/txn/TransactionManager.java | 2 +- .../main/java/org/exist/test/DiffMatcher.java | 4 +- .../org/exist/test/ExistEmbeddedServer.java | 3 +- .../exist/test/runner/AbstractTestRunner.java | 5 +- .../test/runner/ExtTestFailureFunction.java | 7 +- .../exist/test/runner/XQueryFailureLog.java | 3 +- .../exist/test/runner/XQueryTestRunner.java | 3 +- .../java/org/exist/test/runner/XSuite.java | 11 +- .../main/java/org/exist/util/CharSlice.java | 4 +- .../main/java/org/exist/util/Collations.java | 2 +- .../org/exist/util/CompressedWhitespace.java | 4 +- .../java/org/exist/util/Configuration.java | 9 +- .../org/exist/util/ConfigurationHelper.java | 17 +- .../util/DatabaseConfigurationException.java | 5 +- .../org/exist/util/DeadlockException.java | 5 +- .../main/java/org/exist/util/FileUtils.java | 2 +- .../java/org/exist/util/LockException.java | 5 +- .../main/java/org/exist/util/MimeTable.java | 3 +- .../org/exist/util/ReadOnlyException.java | 5 +- .../org/exist/util/SaxonConfiguration.java | 3 +- .../util/SingleInstanceConfiguration.java | 4 +- .../main/java/org/exist/util/SwapVals.java | 17 +- .../java/org/exist/util/SyntaxException.java | 5 +- .../io/AbstractFilterInputStreamCache.java | 4 +- .../util/io/CachingFilterInputStream.java | 4 +- .../exist/util/io/TemporaryFileManager.java | 3 +- .../org/exist/util/sanity/AssertFailure.java | 5 +- .../exist/util/serializer/ReceiverToSAX.java | 4 +- .../resolver/SearchResourceResolver.java | 4 +- .../java/org/exist/webstart/JnlpJarFiles.java | 5 +- .../java/org/exist/webstart/JnlpServlet.java | 13 +- .../java/org/exist/webstart/JnlpWriter.java | 4 +- .../exist/webstart/LatestFileResolver.java | 3 +- .../java/org/exist/xmldb/AbstractLocal.java | 4 +- .../exist/xmldb/AbstractRemoteResource.java | 84 +- .../java/org/exist/xmldb/DatabaseImpl.java | 6 +- .../org/exist/xmldb/LocalBinaryResource.java | 4 +- .../org/exist/xmldb/LocalResourceSet.java | 12 +- .../org/exist/xmldb/LocalRestoreService.java | 5 +- .../org/exist/xmldb/LocalXMLResource.java | 10 +- .../exist/xmldb/LocalXPathQueryService.java | 12 +- .../java/org/exist/xmldb/MapResourceSet.java | 4 +- .../org/exist/xmldb/RemoteBinaryResource.java | 4 +- .../org/exist/xmldb/RemoteCollection.java | 36 +- .../exist/xmldb/RemoteResourceIterator.java | 2 +- .../org/exist/xmldb/RemoteRestoreService.java | 7 +- .../org/exist/xmldb/RemoteXMLResource.java | 15 +- .../exist/xmldb/RemoteXPathQueryService.java | 2 +- .../main/java/org/exist/xmldb/XmldbURI.java | 8 +- .../java/org/exist/xmlrpc/ACEAiderParser.java | 18 +- .../java/org/exist/xmlrpc/QueryResult.java | 4 +- .../java/org/exist/xmlrpc/RpcConnection.java | 21 +- .../java/org/exist/xmlrpc/RpcServlet.java | 12 +- .../java/org/exist/xmlrpc/TupleParser.java | 10 +- .../org/exist/xquery/AbstractFLWORClause.java | 6 +- .../java/org/exist/xquery/Annotations.java | 2 +- .../exist/xquery/AttributeConstructor.java | 16 +- .../exist/xquery/BasicExpressionVisitor.java | 8 +- .../org/exist/xquery/BindingExpression.java | 10 +- .../xquery/DefaultExpressionVisitor.java | 4 +- .../org/exist/xquery/DynamicNameCheck.java | 8 +- .../org/exist/xquery/ElementConstructor.java | 4 +- .../java/org/exist/xquery/EnclosedExpr.java | 2 +- .../java/org/exist/xquery/ErrorCodes.java | 13 +- .../main/java/org/exist/xquery/ForExpr.java | 8 +- .../java/org/exist/xquery/FunctionCall.java | 4 +- .../org/exist/xquery/FunctionFactory.java | 12 +- .../org/exist/xquery/GeneralComparison.java | 28 +- .../main/java/org/exist/xquery/GroupSpec.java | 2 +- .../main/java/org/exist/xquery/JavaCall.java | 20 +- .../main/java/org/exist/xquery/LetExpr.java | 8 +- .../java/org/exist/xquery/LocationStep.java | 12 +- .../main/java/org/exist/xquery/Lookup.java | 4 +- .../exist/xquery/NamedFunctionReference.java | 4 +- .../main/java/org/exist/xquery/Optimizer.java | 4 +- .../main/java/org/exist/xquery/Option.java | 4 +- .../main/java/org/exist/xquery/PathExpr.java | 16 +- .../org/exist/xquery/PerformanceStats.java | 2 +- .../main/java/org/exist/xquery/Predicate.java | 8 +- .../main/java/org/exist/xquery/Profiler.java | 8 +- .../org/exist/xquery/RangeExpression.java | 2 +- .../exist/xquery/StaticXQueryException.java | 7 +- .../org/exist/xquery/TerminatedException.java | 15 +- .../org/exist/xquery/TryCatchExpression.java | 22 +- .../main/java/org/exist/xquery/UnaryExpr.java | 4 +- .../org/exist/xquery/UntypedValueCheck.java | 4 +- .../org/exist/xquery/ValueComparison.java | 16 +- .../java/org/exist/xquery/VariableImpl.java | 4 +- .../java/org/exist/xquery/WindowExpr.java | 2 +- .../java/org/exist/xquery/XPathException.java | 20 +- .../main/java/org/exist/xquery/XQuery.java | 4 +- .../java/org/exist/xquery/XQueryContext.java | 17 +- .../xquery/functions/fn/FnFormatDates.java | 6 +- .../xquery/functions/fn/FnHasChildren.java | 4 +- .../org/exist/xquery/functions/fn/FunAbs.java | 4 +- .../exist/xquery/functions/fn/FunCeiling.java | 6 +- .../xquery/functions/fn/FunDocumentURI.java | 4 +- .../exist/xquery/functions/fn/FunFloor.java | 4 +- .../xquery/functions/fn/FunGenerateId.java | 12 +- .../xquery/functions/fn/FunIRIToURI.java | 65 +- .../functions/fn/FunInScopePrefixes.java | 6 +- .../exist/xquery/functions/fn/FunIndexOf.java | 41 +- .../xquery/functions/fn/FunInsertBefore.java | 33 +- .../exist/xquery/functions/fn/FunLang.java | 27 +- .../xquery/functions/fn/FunLocalName.java | 34 +- .../exist/xquery/functions/fn/FunMatches.java | 53 +- .../org/exist/xquery/functions/fn/FunMax.java | 72 +- .../org/exist/xquery/functions/fn/FunMin.java | 76 +- .../exist/xquery/functions/fn/FunName.java | 40 +- .../xquery/functions/fn/FunNamespaceURI.java | 29 +- .../fn/FunNamespaceURIForPrefix.java | 18 +- .../xquery/functions/fn/FunNodeName.java | 4 +- .../functions/fn/FunNormalizeSpace.java | 20 +- .../functions/fn/FunNormalizeUnicode.java | 61 +- .../org/exist/xquery/functions/fn/FunNot.java | 9 +- .../exist/xquery/functions/fn/FunNumber.java | 46 +- .../xquery/functions/fn/FunOnFunctions.java | 4 +- .../xquery/functions/fn/FunParseIetfDate.java | 5 +- .../exist/xquery/functions/fn/FunPath.java | 14 +- .../exist/xquery/functions/fn/FunQName.java | 20 +- .../exist/xquery/functions/fn/FunRemove.java | 23 +- .../exist/xquery/functions/fn/FunReplace.java | 60 +- .../xquery/functions/fn/FunResolveQName.java | 38 +- .../xquery/functions/fn/FunResolveURI.java | 22 +- .../exist/xquery/functions/fn/FunRoot.java | 16 +- .../xquery/functions/fn/FunRoundBase.java | 4 +- .../functions/fn/FunRoundHalfToEven.java | 51 +- .../xquery/functions/fn/FunStartsWith.java | 41 +- .../xquery/functions/fn/FunStrLength.java | 12 +- .../xquery/functions/fn/FunTranslate.java | 26 +- .../xquery/functions/fn/FunUriCollection.java | 12 +- .../functions/fn/transform/Convert.java | 4 +- .../functions/fn/transform/Options.java | 4 +- .../functions/fn/transform/Transform.java | 13 +- .../inspect/InspectFunctionHelper.java | 8 +- .../integer/DigitsIntegerPicture.java | 2 +- .../exist/xquery/functions/map/MapType.java | 4 +- .../functions/request/GetContextPath.java | 7 +- .../functions/request/GetCookieValue.java | 2 +- .../functions/request/GetParameter.java | 2 +- .../xquery/functions/request/GetPathInfo.java | 5 +- .../SetPrincipalMetadataFunction.java | 10 +- .../functions/session/GetAttribute.java | 4 +- .../functions/session/GetAttributeNames.java | 2 +- .../functions/session/GetCreationTime.java | 2 +- .../session/GetLastAccessedTime.java | 2 +- .../session/GetMaxInactiveInterval.java | 2 +- .../xquery/functions/session/Invalidate.java | 2 +- .../xquery/functions/system/FnImport.java | 6 +- .../functions/system/FunctionAvailable.java | 10 +- .../xquery/functions/system/Restore.java | 4 +- .../xquery/functions/transform/Transform.java | 19 +- .../functions/util/DocumentNameOrId.java | 12 +- .../org/exist/xquery/functions/util/Eval.java | 40 +- .../functions/util/GetFragmentBetween.java | 4 +- .../xquery/functions/util/NodeXPath.java | 4 +- .../functions/validation/GrammarTooling.java | 24 +- .../xquery/functions/validation/Jaxp.java | 4 +- .../functions/xmldb/XMLDBLoadFromPattern.java | 5 +- .../xmldb/XMLDBRegisterDatabase.java | 2 +- .../xquery/functions/xmldb/XMLDBStore.java | 17 +- .../org/exist/xquery/modules/ModuleUtils.java | 4 +- .../org/exist/xquery/parser/XQueryAST.java | 4 +- .../exist/xquery/pragmas/ForceIndexUse.java | 2 +- .../org/exist/xquery/pragmas/Optimize.java | 8 +- .../org/exist/xquery/pragmas/TimePragma.java | 4 +- .../org/exist/xquery/update/Modification.java | 4 +- .../exist/xquery/util/ExpressionDumper.java | 4 +- .../exist/xquery/util/NumberFormatter.java | 2 +- .../exist/xquery/value/AbstractSequence.java | 4 +- .../org/exist/xquery/value/AnyURIValue.java | 4 +- .../org/exist/xquery/value/BooleanValue.java | 4 +- .../xquery/value/DayTimeDurationValue.java | 14 +- .../org/exist/xquery/value/IntegerValue.java | 6 +- .../org/exist/xquery/value/QNameValue.java | 4 +- .../xquery/value/UntypedAtomicValue.java | 4 +- .../xquery/value/YearMonthDurationValue.java | 14 +- .../org/exist/xquery/xqdoc/XQDocHelper.java | 4 +- .../java/org/exist/xslt/EXistURIResolver.java | 4 +- .../java/org/exist/xslt/TemplatesFactory.java | 5 +- .../org/exist/xslt/XSLTErrorsListener.java | 2 +- .../java/org/exist/xupdate/Modification.java | 4 +- .../src/test/java/org/exist/Indexer2Test.java | 10 +- .../src/test/java/org/exist/Indexer3Test.java | 257 +++--- .../src/test/java/org/exist/IndexerTest.java | 155 ++-- .../java/org/exist/TestDataGenerator.java | 12 +- .../org/exist/backup/RestoreAppsTest.java | 26 +- .../exist/backup/SystemExportFiltersTest.java | 14 +- .../exist/backup/SystemExportImportTest.java | 14 +- .../org/exist/backup/XMLDBRestoreTest.java | 88 +- .../exist/collections/ConcurrencyTest.java | 17 +- .../triggers/HistoryTriggerTest.java | 13 +- .../collections/triggers/SAXTriggerTest.java | 13 +- .../org/exist/config/ConfigurableTest.java | 2 +- .../org/exist/config/TwoDatabasesTest.java | 9 +- .../exist/dom/memtree/DocumentImplTest.java | 7 +- .../dom/memtree/MemtreeInXQueryTest.java | 59 +- .../org/exist/dom/memtree/MemtreeTest.java | 39 +- .../org/exist/dom/persistent/DocTypeTest.java | 3 +- .../dom/persistent/PersistentDomTest.java | 21 +- .../org/exist/dom/persistent/XMLUtilTest.java | 5 +- .../java/org/exist/http/RESTServiceTest.java | 304 +++--- .../java/org/exist/numbering/DLNTest.java | 4 +- .../BackupRestoreSecurityPrincipalsTest.java | 9 +- .../aider/UnixStylePermissionAiderTest.java | 4 +- .../org/exist/source/SourceFactoryTest.java | 12 +- .../stax/EmbeddedXMLStreamReaderTest.java | 19 +- .../exist/storage/AbstractRecoverTest.java | 3 +- .../org/exist/storage/AbstractUpdateTest.java | 2 +- .../storage/ConcurrentBrokerPoolTest.java | 3 +- .../exist/storage/ConcurrentStoreTest.java | 2 +- .../org/exist/storage/CopyCollectionTest.java | 2 +- .../org/exist/storage/DOMFileRecoverTest.java | 2 +- .../exist/storage/RangeIndexUpdateTest.java | 2 +- .../org/exist/storage/RecoverBinary2Test.java | 3 +- .../org/exist/storage/RecoverXmlTest.java | 8 +- .../java/org/exist/storage/Recovery2Test.java | 3 +- .../exist/storage/ReindexRecoveryTest.java | 2 +- .../java/org/exist/storage/ReindexTest.java | 9 +- .../org/exist/storage/RemoveCollectionIT.java | 45 +- .../java/org/exist/storage/RemoveTest.java | 2 +- .../java/org/exist/storage/ResourceTest.java | 2 +- .../org/exist/storage/StoreBinaryTest.java | 2 +- .../org/exist/storage/UpdateRecoverTest.java | 4 +- .../storage/blob/BlobStoreRecoveryTest.java | 32 +- .../exist/storage/journal/JournalTest.java | 83 +- .../org/exist/storage/lock/DeadlockIT.java | 43 +- .../exist/storage/lock/ProtectedModeTest.java | 43 +- .../statistics/StatisticsIndexTest.java | 5 +- .../NativeStructuralIndexWorkerTest.java | 16 +- .../test/runner/InspectLineSourceTest.java | 3 +- .../exist/test/runner/XMLTestRunnerTest.java | 2 +- .../test/runner/XQueryTestRunnerTest.java | 6 +- .../test/runner/XSuiteDiscoveryTest.java | 5 +- .../java/org/exist/util/MimeTableTest.java | 7 +- .../io/FilterInputStreamCacheMonitorTest.java | 3 +- .../exist/util/sorters/ComparatorChecker.java | 2 +- .../CollectionConfigSchema6000Test.java | 3 +- ...baseInsertResourcesWithValidationTest.java | 27 +- .../java/org/exist/w3c/tests/TestCase.java | 13 +- .../exist/xmldb/BinaryResourceUpdateIT.java | 6 +- .../exist/xmldb/BinaryResourceUpdateTest.java | 8 +- .../xmldb/CollectionConfigurationTest.java | 19 +- .../exist/xmldb/CreateCollectionsTest.java | 5 +- .../java/org/exist/xmldb/DOMJUnitTest.java | 30 +- .../org/exist/xmldb/DeclareVariableTest.java | 7 +- .../java/org/exist/xmldb/IndexingTest.java | 8 +- .../java/org/exist/xmldb/ResourceTest.java | 8 +- .../org/exist/xmldb/SerializationTest.java | 10 +- .../exist/xmldb/TestEXistXMLSerialize.java | 22 +- .../concurrent/ConcurrentResourceTest2.java | 3 +- .../exist/xmldb/concurrent/DeadlockTest.java | 15 +- .../action/MultiResourcesAction.java | 3 +- .../concurrent/action/XQueryUpdateAction.java | 23 +- .../org/exist/xmlrpc/QuerySessionTest.java | 43 +- .../org/exist/xquery/AbsolutePathTests.java | 27 +- .../AbstractDescendantOrSelfNodeKindTest.java | 25 +- .../java/org/exist/xquery/CleanupTest.java | 9 +- .../xquery/ConstructedNodesRecoveryTest.java | 34 +- .../exist/xquery/ConstructedNodesTest.java | 85 +- .../org/exist/xquery/ConversionsTest.java | 11 +- .../org/exist/xquery/CountExpressionTest.java | 19 +- .../org/exist/xquery/DocumentUpdateTest.java | 6 +- .../exist/xquery/DuplicateAttributesTest.java | 62 +- .../exist/xquery/ForwardReferenceTest.java | 88 +- .../FunctionTypeInElementContentTest.java | 4 +- .../org/exist/xquery/ImportModuleTest.java | 866 ++++++++++-------- .../org/exist/xquery/ModuleImportTest.java | 3 +- .../org/exist/xquery/NamespaceUpdateTest.java | 18 +- .../xquery/ReservedNamesConflictTest.java | 9 +- .../org/exist/xquery/StoredModuleTest.java | 18 +- .../java/org/exist/xquery/TransformTest.java | 61 +- .../java/org/exist/xquery/ValueIndexTest.java | 31 +- .../java/org/exist/xquery/VariablesTest.java | 43 +- .../org/exist/xquery/WindowClauseTest.java | 144 +-- .../java/org/exist/xquery/XPathQueryTest.java | 88 +- .../xquery/XQueryContextAttributesTest.java | 6 +- .../xquery/XQueryDeclareContextItemTest.java | 51 +- .../org/exist/xquery/XQueryFunctionsTest.java | 81 +- .../XQueryProcessingInstructionTest.java | 13 +- .../java/org/exist/xquery/XQueryTest.java | 347 ++++--- .../org/exist/xquery/XQueryUpdateTest.java | 170 ++-- .../PermissionsFunctionChmodTest.java | 7 +- .../PermissionsFunctionChownTest.java | 5 +- .../transform/ImportLocalStylesheetTest.java | 3 +- .../functions/transform/TransformTest.java | 114 +-- .../exist/xquery/functions/util/EvalTest.java | 155 ++-- .../xquery/functions/util/ExpandTest.java | 33 +- .../validate/AdditionalJingXsdRngTest.java | 212 ++--- .../functions/validate/JaxpParseTest.java | 9 +- .../xquery/functions/xmldb/DbStore2Test.java | 5 +- .../xquery/functions/xmldb/DbStoreTest.java | 13 +- .../xmldb/XMLDBAuthenticateTest.java | 119 +-- .../xquery3/DeclareVariableTest.java | 17 +- .../value/Base64BinaryValueTypeTest.java | 5 +- .../java/org/exist/xupdate/XUpdateTest.java | 3 +- exist-samples/pom.xml | 6 + .../start/CompatibleJavaVersionCheck.java | 2 +- .../src/main/java/org/exist/start/Main.java | 11 +- .../exist/start/classloader/Classpath.java | 6 +- .../xquery/ContentFunctionsTest.java | 39 +- .../java/org/expath/exist/HttpClientTest.java | 26 +- .../modules/request/ParameterFunctions.java | 4 +- .../restxq/impl/ExistXqueryRegistry.java | 8 +- .../impl/ResourceFunctionExecutorImpl.java | 12 +- .../RestXqServiceRegistryPersistence.java | 4 +- .../exquery/restxq/impl/XQueryCompiler.java | 6 +- .../restxq/impl/adapters/SequenceAdapter.java | 6 +- .../restxq/impl/AbstractIntegrationTest.java | 13 +- .../restxq/impl/MediaTypeIntegrationTest.java | 94 +- ...portCircularDependencyIntegrationTest.java | 16 +- .../exist/indexing/EnforceIndexUseTest.java | 35 +- .../exist/indexing/lucene/AnalyzerConfig.java | 8 +- .../indexing/lucene/BinaryTokenStream.java | 4 +- .../exist/indexing/lucene/LuceneConfig.java | 2 +- .../indexing/lucene/LuceneFieldConfig.java | 7 +- .../indexing/lucene/LuceneIndexWorker.java | 12 +- .../indexing/lucene/LuceneMatchListener.java | 2 +- .../lucene/LuceneVectorFieldConfig.java | 4 +- .../org/exist/indexing/lucene/XMLToQuery.java | 3 +- .../exist/xquery/modules/lucene/Query.java | 2 +- .../xquery/modules/lucene/QueryOptions.java | 6 +- .../exist/xquery/modules/lucene/Search.java | 17 +- .../indexing/lucene/AnalyzerConfigTest.java | 121 +-- .../FacetPollutionJavaReproducerTest.java | 5 +- .../indexing/lucene/LuceneIndexTest.java | 40 +- .../lucene/LuceneMatchListenerTest.java | 71 +- .../lucene/SerializeAttrMatchesTest.java | 13 +- .../lucene/VectorSearchEmbeddingTest.java | 3 +- .../modules/ngram/HighlightMatches.java | 25 +- .../xquery/modules/ngram/NGramSearch.java | 2 +- .../query/WildcardedExpressionSequence.java | 16 +- .../exist/indexing/ngram/CustomIndexTest.java | 18 +- .../indexing/ngram/MatchListenerTest.java | 37 +- .../range/RangeIndexConfigCondition.java | 10 +- .../indexing/range/RangeIndexWorker.java | 68 +- .../range/conversion/DateConverter.java | 2 +- .../exist/xquery/modules/range/Lookup.java | 2 +- .../modules/range/OptimizeFieldPragma.java | 6 +- .../modules/range/RangeQueryRewriter.java | 8 +- .../Issue4074IndexKeysServletContextTest.java | 7 +- .../spatial/SpatialIndexException.java | 3 + .../exist/indexing/spatial/GMLIndexTest.java | 4 +- .../lucene/VectorSearchEmbeddingIT.java | 10 +- .../xquery/modules/cache/CacheFunctions.java | 2 +- .../xquery/modules/cache/LazyCacheTest.java | 3 +- .../modules/cache/NonLazyCacheTest.java | 3 +- .../compression/AbstractCompressFunction.java | 3 +- .../modules/compression/EntryFunctions.java | 1 - .../org/exist/repo/ExampleModuleTest.java | 20 +- .../java/org/exist/repo/PackageTriggerIT.java | 5 +- .../xquery/modules/file/DirectoryList.java | 15 +- .../xquery/modules/file/FileModuleHelper.java | 5 +- .../xquery/modules/image/CropFunction.java | 4 +- .../modules/image/GetThumbnailsFunction.java | 7 +- .../xquery/modules/mail/MessageFunctions.java | 8 +- .../modules/mail/SendEmailFunction.java | 2 +- .../exist/xquery/modules/process/Execute.java | 3 +- .../xquery/modules/sql/ExecuteFunction.java | 4 +- .../exist/xquery/modules/sql/SQLModule.java | 2 +- .../xquery/modules/sql/ConnectionIT.java | 5 +- .../xquery/modules/sql/ConnectionPoolIT.java | 5 +- .../sql/ImplicitConnectionCloseIT.java | 5 +- .../xquery/modules/sql/JndiConnectionIT.java | 5 +- .../exist/xquery/modules/xmldiff/Compare.java | 8 +- .../xquery/modules/xslfo/ApacheFopTest.java | 76 +- .../realm/iprange/IPRangeServlet.java | 2 + .../org/exist/vector/HttpVectorProvider.java | 13 +- .../org/exist/vector/ModelPathResolver.java | 3 +- .../java/org/exist/vector/ModelRegistry.java | 3 +- .../java/org/exist/webdav/ExistDocument.java | 6 +- .../CollectionDoesNotExistException.java | 3 + .../exceptions/CollectionExistsException.java | 3 + .../DocumentAlreadyLockedException.java | 3 + .../DocumentNotLockedException.java | 3 + .../exceptions/EXistWebdavException.java | 3 + .../org/exist/webdav/SerializationTest.java | 10 +- .../java/org/exist/xqdoc/ant/XQDocTask.java | 36 +- 511 files changed, 4893 insertions(+), 4215 deletions(-) diff --git a/exist-ant/src/main/java/org/exist/ant/BackupTask.java b/exist-ant/src/main/java/org/exist/ant/BackupTask.java index e914432447d..f2aff34928b 100644 --- a/exist-ant/src/main/java/org/exist/ant/BackupTask.java +++ b/exist-ant/src/main/java/org/exist/ant/BackupTask.java @@ -26,7 +26,7 @@ import org.exist.backup.Backup; import org.exist.xmldb.XmldbURI; -import java.nio.file.Paths; +import java.nio.file.Path; /** @@ -55,7 +55,7 @@ public void execute() throws BuildException log( "Backup directory: " + dir ); try { - final Backup backup = new Backup(user, password, Paths.get(dir), XmldbURI.create( uri ), null, deduplicateBlobs); + final Backup backup = new Backup(user, password, Path.of(dir), XmldbURI.create( uri ), null, deduplicateBlobs); backup.backup( false, null ); } diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBExtractTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBExtractTask.java index f31a149eecb..66f93963e73 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBExtractTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBExtractTask.java @@ -211,8 +211,8 @@ private void extractSubCollections(final Collection base, final String path) thr * @throws IOException if an I/O error occurs */ private void writeResource(final Resource res, final Path dest) throws XMLDBException, IOException { - if (res instanceof XMLResource) { - writeXMLResource((XMLResource) res, dest); + if (res instanceof XMLResource lResource) { + writeXMLResource(lResource, dest); } else if (res instanceof ExtendedResource) { writeBinaryResource(res, dest); } diff --git a/exist-ant/src/test/java/org/exist/ant/AbstractTaskTest.java b/exist-ant/src/test/java/org/exist/ant/AbstractTaskTest.java index 3d02c3afad2..b631f9a3260 100644 --- a/exist-ant/src/test/java/org/exist/ant/AbstractTaskTest.java +++ b/exist-ant/src/test/java/org/exist/ant/AbstractTaskTest.java @@ -32,7 +32,6 @@ import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; -import java.nio.file.Paths; import static org.junit.Assert.assertNotNull; @@ -54,7 +53,7 @@ public void setup() throws URISyntaxException { final URL buildFileUrl = getBuildFile(); assertNotNull(buildFileUrl); - final Path buildFile = Paths.get(buildFileUrl.toURI()); + final Path buildFile = Path.of(buildFileUrl.toURI()); buildFileRule.configureProject(buildFile.toAbsolutePath().toString()); final Project project = buildFileRule.getProject(); project.setProperty(PROP_ANT_ADMIN_USER, TestUtils.ADMIN_DB_USER); diff --git a/exist-ant/src/test/java/org/exist/ant/ServerTaskTest.java b/exist-ant/src/test/java/org/exist/ant/ServerTaskTest.java index 7db1a5cfb48..d2625b1954a 100644 --- a/exist-ant/src/test/java/org/exist/ant/ServerTaskTest.java +++ b/exist-ant/src/test/java/org/exist/ant/ServerTaskTest.java @@ -34,7 +34,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -67,7 +66,7 @@ public void backup() throws IOException { public void restore() throws URISyntaxException, XMLDBException { final URL backupContentsUrl = getClass().getResource("backup-test/db/__contents__.xml"); assertNotNull(backupContentsUrl); - final Path backupDir = Paths.get(backupContentsUrl.toURI()).getParent().getParent(); + final Path backupDir = Path.of(backupContentsUrl.toURI()).getParent().getParent(); final Project project = buildFileRule.getProject(); project.setProperty(PROP_ANT_TEST_DATA_BACKUP_DIR, backupDir.toAbsolutePath().toString()); diff --git a/exist-core/src/main/java/org/exist/BTreeTest.java b/exist-core/src/main/java/org/exist/BTreeTest.java index 0295b1adfcc..f5d1bfa8a0f 100644 --- a/exist-core/src/main/java/org/exist/BTreeTest.java +++ b/exist-core/src/main/java/org/exist/BTreeTest.java @@ -31,7 +31,6 @@ import java.io.IOException; import java.io.OutputStreamWriter; import java.nio.file.Path; -import java.nio.file.Paths; public class BTreeTest { @@ -43,7 +42,7 @@ public class BTreeTest { private BrokerPool pool = null; public BTreeTest() { - file = Paths.get(System.getProperty("exist.home", ".")).resolve("test/test.dbx"); + file = Path.of(System.getProperty("exist.home", ".")).resolve("test/test.dbx"); try { Configuration config = new Configuration(); @@ -144,4 +143,4 @@ public static void main(String[] args) { test.shutdown(); } } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/EXistException.java b/exist-core/src/main/java/org/exist/EXistException.java index 89aa95d6b21..00637b7a247 100644 --- a/exist-core/src/main/java/org/exist/EXistException.java +++ b/exist-core/src/main/java/org/exist/EXistException.java @@ -21,6 +21,8 @@ */ package org.exist; +import java.io.Serial; + /** * General exception type. * @@ -28,6 +30,7 @@ */ public class EXistException extends Exception { + @Serial private static final long serialVersionUID = 3256728389837665330L; public EXistException() { diff --git a/exist-core/src/main/java/org/exist/TestUtils.java b/exist-core/src/main/java/org/exist/TestUtils.java index 22d53246780..bee8481b454 100644 --- a/exist-core/src/main/java/org/exist/TestUtils.java +++ b/exist-core/src/main/java/org/exist/TestUtils.java @@ -35,7 +35,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Iterator; import java.util.Optional; import java.util.stream.Stream; @@ -184,7 +183,7 @@ public static Optional getEXistHome() { * @throws IOException if an IO error occurs. */ public static Optional getExistHomeFile(final String fileName) throws IOException { - final Path path = getEXistHome().orElseGet(() -> Paths.get(".")).resolve(fileName); + final Path path = getEXistHome().orElseGet(() -> Path.of(".")).resolve(fileName); if(Files.exists(path)) { return Optional.of(path); } else { diff --git a/exist-core/src/main/java/org/exist/backup/Backup.java b/exist-core/src/main/java/org/exist/backup/Backup.java index e000fa6d93e..e760ee7e032 100644 --- a/exist-core/src/main/java/org/exist/backup/Backup.java +++ b/exist-core/src/main/java/org/exist/backup/Backup.java @@ -48,7 +48,6 @@ import java.awt.*; import java.io.*; import java.nio.file.Path; -import java.nio.file.Paths; import java.time.Instant; import java.util.List; import java.util.HashSet; @@ -150,10 +149,10 @@ public static void main(final String[] args) { CompatibleJavaVersionCheck.checkForCompatibleJavaVersion(); final Class cl = Class.forName("org.exist.xmldb.DatabaseImpl"); - final Database database = (Database) cl.newInstance(); + final Database database = (Database) cl.getDeclaredConstructor().newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); - final Backup backup = new Backup("admin", null, Paths.get("backup"), URIUtils.encodeXmldbUriFor(args[0])); + final Backup backup = new Backup("admin", null, Path.of("backup"), URIUtils.encodeXmldbUriFor(args[0])); backup.backup(false, null); } catch (final StartException e) { if (e.getMessage() != null && !e.getMessage().isEmpty()) { @@ -313,8 +312,8 @@ private void backup(final Set seenBlobIds, final Collection current, fin serializer.startElement(Namespaces.EXIST_NS, "collection", "collection", attr); - if (currentPerms instanceof ACLPermission) { - writeACLPermission(serializer, (ACLPermission) currentPerms); + if (currentPerms instanceof ACLPermission permission) { + writeACLPermission(serializer, permission); } // scan through resources @@ -369,9 +368,9 @@ private void backup(final Set seenBlobIds, final Collection current, fin final OutputStream os; if (resource instanceof ExtendedResource) { - if (deduplicateBlobs && resource instanceof EXistBinaryResource) { + if (deduplicateBlobs && resource instanceof EXistBinaryResource binaryResource) { // only add distinct blobs to the Blob Store once! - final String blobId = ((EXistBinaryResource) resource).getBlobId().toString(); + final String blobId = binaryResource.getBlobId().toString(); if (!seenBlobIds.contains(blobId)) { os = output.newBlobEntry(blobId); ((ExtendedResource) resource).getContentIntoAStream(os); @@ -444,8 +443,8 @@ private void backup(final Set seenBlobIds, final Collection current, fin } serializer.startElement(Namespaces.EXIST_NS, "resource", "resource", attr); - if (perms[i] instanceof ACLPermission) { - writeACLPermission(serializer, (ACLPermission) perms[i]); + if (perms[i] instanceof ACLPermission permission) { + writeACLPermission(serializer, permission); } serializer.endElement(Namespaces.EXIST_NS, "resource", "resource"); } catch (final XMLDBException e) { diff --git a/exist-core/src/main/java/org/exist/backup/BackupDialog.java b/exist-core/src/main/java/org/exist/backup/BackupDialog.java index 73951fcc54d..9902507b22f 100644 --- a/exist-core/src/main/java/org/exist/backup/BackupDialog.java +++ b/exist-core/src/main/java/org/exist/backup/BackupDialog.java @@ -23,9 +23,11 @@ import javax.swing.*; import java.awt.*; +import java.io.Serial; public class BackupDialog extends JDialog { + @Serial private static final long serialVersionUID = -4960002499478536048L; JTextField currentCollection; diff --git a/exist-core/src/main/java/org/exist/backup/BackupDirectory.java b/exist-core/src/main/java/org/exist/backup/BackupDirectory.java index a3bb3bae2ce..051ac53b41d 100644 --- a/exist-core/src/main/java/org/exist/backup/BackupDirectory.java +++ b/exist-core/src/main/java/org/exist/backup/BackupDirectory.java @@ -28,7 +28,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; @@ -56,7 +55,7 @@ public class BackupDirectory { private final Matcher matcher; public BackupDirectory(final String dirPath) { - this(Paths.get(dirPath)); + this(Path.of(dirPath)); } diff --git a/exist-core/src/main/java/org/exist/backup/ConsistencyCheck.java b/exist-core/src/main/java/org/exist/backup/ConsistencyCheck.java index 1733caa213b..92d3db94624 100644 --- a/exist-core/src/main/java/org/exist/backup/ConsistencyCheck.java +++ b/exist-core/src/main/java/org/exist/backup/ConsistencyCheck.java @@ -579,8 +579,8 @@ public void checkDocs() { } } if (report != null) { - if (report instanceof ErrorReport.ResourceError) { - ((ErrorReport.ResourceError) report).setDocumentId(doc.getDocId()); + if (report instanceof ErrorReport.ResourceError error) { + error.setDocumentId(doc.getDocId()); } if (errors != null) { diff --git a/exist-core/src/main/java/org/exist/backup/CreateBackupDialog.java b/exist-core/src/main/java/org/exist/backup/CreateBackupDialog.java index 189d06b3b96..c00af246885 100644 --- a/exist-core/src/main/java/org/exist/backup/CreateBackupDialog.java +++ b/exist-core/src/main/java/org/exist/backup/CreateBackupDialog.java @@ -31,13 +31,14 @@ import javax.swing.*; import java.awt.*; +import java.io.Serial; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Collections; import java.util.Vector; public class CreateBackupDialog extends JPanel { + @Serial private static final long serialVersionUID = 4571248257313559856L; JComboBox collections; @@ -148,7 +149,7 @@ private void actionSelect() { chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); chooser.addChoosableFileFilter(new MimeTypeFileFilter("application/zip")); - chooser.setSelectedFile(Paths.get("eXist-backup.zip").toFile()); + chooser.setSelectedFile(Path.of("eXist-backup.zip").toFile()); chooser.setCurrentDirectory(backupDir.toFile()); if (chooser.showDialog(this, Messages.getString("CreateBackupDialog.5")) == JFileChooser.APPROVE_OPTION) { diff --git a/exist-core/src/main/java/org/exist/backup/ExportGUI.java b/exist-core/src/main/java/org/exist/backup/ExportGUI.java index 598183a7ff3..1fef9e4ef8d 100644 --- a/exist-core/src/main/java/org/exist/backup/ExportGUI.java +++ b/exist-core/src/main/java/org/exist/backup/ExportGUI.java @@ -43,9 +43,9 @@ import java.io.File; import java.io.IOException; import java.io.PrintWriter; +import java.io.Serial; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import java.util.Optional; @@ -61,6 +61,7 @@ * @author wolf */ public class ExportGUI extends javax.swing.JFrame { + @Serial private static final long serialVersionUID = -8104424554660744639L; /* general arguments */ @@ -100,16 +101,16 @@ public ExportGUI() { super("Consistency Check and Repair"); initComponents(); final String existHome = System.getProperty("exist.home", "./"); - final Path home = Paths.get(existHome).normalize(); + final Path home = Path.of(existHome).normalize(); dbConfig.setText( - Optional.ofNullable(System.getProperty("exist.configurationFile")).map(Paths::get) + Optional.ofNullable(System.getProperty("exist.configurationFile")).map(Path::of) .orElse(home.resolve("etc").resolve("conf.xml")) .toAbsolutePath().toString()); outputDir.setText(home.resolve("export").toAbsolutePath().toString()); } protected boolean checkOutputDir() { - final Path dir = Paths.get(outputDir.getText()).normalize(); + final Path dir = Path.of(outputDir.getText()).normalize(); if (!Files.exists(dir)) { @@ -133,7 +134,7 @@ protected boolean startDB() { if (pool != null) { return true; } - final Path confFile = Paths.get(dbConfig.getText()).normalize(); + final Path confFile = Path.of(dbConfig.getText()).normalize(); if (!(Files.exists(confFile) && Files.isReadable(confFile))) { JOptionPane.showMessageDialog(this, "The selected database configuration file " + confFile.toAbsolutePath() + " does not exist or is not readable.", "Configuration Error", JOptionPane.ERROR_MESSAGE); @@ -383,7 +384,7 @@ private void exportBtnActionPerformed(final java.awt.event.ActionEvent evt) { // private void btnChangeDirActionPerformed(final java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnChangeDirActionPerformed - final Path dir = Paths.get(outputDir.getText()); + final Path dir = Path.of(outputDir.getText()); final JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); @@ -403,12 +404,12 @@ private void menuQuitActionPerformed(final java.awt.event.ActionEvent evt) { // private void btnConfSelectActionPerformed(final java.awt.event.ActionEvent evt) { // GEN-FIRST:event_btnConfSelectActionPerformed - final Path dir = Paths.get(dbConfig.getText()).normalize().getParent(); + final Path dir = Path.of(dbConfig.getText()).normalize().getParent(); final JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setSelectedFile(Optional.ofNullable(System.getProperty("exist.configurationFile")) - .map(Paths::get) + .map(Path::of) .orElse(dir.resolve("etc").resolve("conf.xml")) .toFile()); chooser.setCurrentDirectory(dir.resolve("etc").toFile()); diff --git a/exist-core/src/main/java/org/exist/backup/ExportMain.java b/exist-core/src/main/java/org/exist/backup/ExportMain.java index 39fbe1d9698..0d731359286 100644 --- a/exist-core/src/main/java/org/exist/backup/ExportMain.java +++ b/exist-core/src/main/java/org/exist/backup/ExportMain.java @@ -42,7 +42,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import java.util.Optional; @@ -100,7 +99,7 @@ public class ExportMain { .build(); private static final Argument outputDirArg = fileArgument("-d", "--dir") .description("the directory to which all output will be written.") - .defaultValue(Paths.get("export").toAbsolutePath().toFile()) + .defaultValue(Path.of("export").toAbsolutePath().toFile()) .build(); protected static BrokerPool startDB(final Optional configFile) { diff --git a/exist-core/src/main/java/org/exist/backup/FileSystemBackupDescriptor.java b/exist-core/src/main/java/org/exist/backup/FileSystemBackupDescriptor.java index 956aa7a19a8..cee725837a3 100644 --- a/exist-core/src/main/java/org/exist/backup/FileSystemBackupDescriptor.java +++ b/exist-core/src/main/java/org/exist/backup/FileSystemBackupDescriptor.java @@ -36,7 +36,6 @@ import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Collections; import java.util.List; import java.util.Optional; @@ -91,8 +90,7 @@ public List getChildBackupDescriptors() { return Optional.empty(); } }) - .filter(Optional::isPresent) - .map(Optional::get)) { + .flatMap(Optional::stream)) { return entries.collect(Collectors.toList()); } } catch (final IOException e) { @@ -108,7 +106,7 @@ public BackupDescriptor getBackupDescriptor(final String describedItem) { BackupDescriptor bd = null; try { - bd = new FileSystemBackupDescriptor(root, Paths.get(desc)); + bd = new FileSystemBackupDescriptor(root, Path.of(desc)); } catch (final FileNotFoundException fnfe) { // DoNothing(R) } diff --git a/exist-core/src/main/java/org/exist/backup/FileSystemWriter.java b/exist-core/src/main/java/org/exist/backup/FileSystemWriter.java index 434eebc43ed..3561af10a39 100644 --- a/exist-core/src/main/java/org/exist/backup/FileSystemWriter.java +++ b/exist-core/src/main/java/org/exist/backup/FileSystemWriter.java @@ -31,7 +31,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Properties; @@ -48,7 +47,7 @@ public class FileSystemWriter implements BackupWriter { private boolean dataWritten = false; public FileSystemWriter(final String path) throws IOException { - this(Paths.get(path)); + this(Path.of(path)); } public FileSystemWriter(final Path file) throws IOException { diff --git a/exist-core/src/main/java/org/exist/backup/Main.java b/exist-core/src/main/java/org/exist/backup/Main.java index 4d9886bb8da..d84ec0610ac 100644 --- a/exist-core/src/main/java/org/exist/backup/Main.java +++ b/exist-core/src/main/java/org/exist/backup/Main.java @@ -40,7 +40,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Map; import java.util.Optional; import java.util.Properties; @@ -204,7 +203,7 @@ public static void process(final ParsedArguments arguments) { String collection = backupCollection.get(); if (collection.isEmpty()) { if (guiMode) { - final CreateBackupDialog dialog = new CreateBackupDialog(properties.getProperty(URI_PROP, DEFAULT_URI), properties.getProperty(USER_PROP, DEFAULT_USER), properties.getProperty(PASSWORD_PROP, DEFAULT_PASSWORD), Paths.get(preferences.get("directory.backup", System.getProperty("user.dir")))); + final CreateBackupDialog dialog = new CreateBackupDialog(properties.getProperty(URI_PROP, DEFAULT_URI), properties.getProperty(USER_PROP, DEFAULT_USER), properties.getProperty(PASSWORD_PROP, DEFAULT_PASSWORD), Path.of(preferences.get("directory.backup", System.getProperty("user.dir")))); if (JOptionPane.showOptionDialog(null, dialog, "Create Backup", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null) == JOptionPane.YES_OPTION) { collection = dialog.getCollection(); @@ -221,7 +220,7 @@ public static void process(final ParsedArguments arguments) { final Backup backup = new Backup( properties.getProperty(USER_PROP, DEFAULT_USER), properties.getProperty(PASSWORD_PROP, DEFAULT_PASSWORD), - Paths.get(properties.getProperty(BACKUP_DIR_PROP, DEFAULT_BACKUP_DIR)), + Path.of(properties.getProperty(BACKUP_DIR_PROP, DEFAULT_BACKUP_DIR)), XmldbURI.xmldbUriFor(properties.getProperty(URI_PROP, DEFAULT_URI) + collection), properties, deduplicateBlobs @@ -316,13 +315,17 @@ private static void restoreWithoutGui(final String username, final String passwo System.err.println("Rebuilding application repository failed!"); } } else { - System.out.println("\nIf you restored collections inside /db/apps, you may want\n" + - "to rebuild the application repository. To do so, run the following query\n" + - "as admin:\n\n" + - "import module namespace repair=\"http://exist-db.org/xquery/repo/repair\"\n" + - "at \"resource:org/exist/xquery/modules/expathrepo/repair.xql\";\n" + - "repair:clean-all(),\n" + - "repair:repair()\n"); + System.out.println(""" + + If you restored collections inside /db/apps, you may want + to rebuild the application repository. To do so, run the following query + as admin: + + import module namespace repair="http://exist-db.org/xquery/repo/repair" + at "resource:org/exist/xquery/modules/expathrepo/repair.xql"; + repair:clean-all(), + repair:repair() + """); } } diff --git a/exist-core/src/main/java/org/exist/backup/RestoreDialog.java b/exist-core/src/main/java/org/exist/backup/RestoreDialog.java index 80ed93006ac..de30c1c7ee8 100644 --- a/exist-core/src/main/java/org/exist/backup/RestoreDialog.java +++ b/exist-core/src/main/java/org/exist/backup/RestoreDialog.java @@ -23,10 +23,12 @@ import javax.swing.*; import java.awt.*; +import java.io.Serial; import java.text.DecimalFormat; public class RestoreDialog extends JDialog { + @Serial private static final long serialVersionUID = 3773486348231766907L; private static final DecimalFormat PERCENTAGE_FORMAT = new DecimalFormat("###.##%"); diff --git a/exist-core/src/main/java/org/exist/backup/SystemExport.java b/exist-core/src/main/java/org/exist/backup/SystemExport.java index 0a8b585746a..7953f4c7963 100644 --- a/exist-core/src/main/java/org/exist/backup/SystemExport.java +++ b/exist-core/src/main/java/org/exist/backup/SystemExport.java @@ -76,7 +76,6 @@ import java.io.*; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.*; @@ -404,8 +403,8 @@ private void export(final Collection current, final BackupWriter output, final D serializer.startElement(Namespaces.EXIST_NS, "collection", "collection", attr); - if (perm instanceof ACLPermission) { - Backup.writeACLPermission(serializer, (ACLPermission) perm); + if (perm instanceof ACLPermission permission) { + Backup.writeACLPermission(serializer, permission); } final int docsCount = current.getDocumentCountNoLock(broker); @@ -565,8 +564,8 @@ private void exportDocument(final BackupWriter output, final Date date, final Ba // } serializer.startElement(Namespaces.EXIST_NS, "resource", "resource", attr); - if (perms instanceof ACLPermission) { - Backup.writeACLPermission(serializer, (ACLPermission) perms); + if (perms instanceof ACLPermission permission) { + Backup.writeACLPermission(serializer, permission); } serializer.endElement(Namespaces.EXIST_NS, "resource", "resource"); @@ -671,11 +670,11 @@ private void writeXML(final DocumentImpl doc, final Receiver receiver) { public static Path getUniqueFile(final String base, final String extension, final String dir) { final SimpleDateFormat creationDateFormat = new SimpleDateFormat(DataBackup.DATE_FORMAT_PICTURE); final String filename = base + '-' + creationDateFormat.format(Calendar.getInstance().getTime()); - Path file = Paths.get(dir, filename + extension); + Path file = Path.of(dir, filename + extension); int version = 0; while (Files.exists(file)) { - file = Paths.get(dir, filename + '_' + version++ + extension); + file = Path.of(dir, filename + '_' + version++ + extension); } return file; } diff --git a/exist-core/src/main/java/org/exist/backup/ZipArchiveBackupDescriptor.java b/exist-core/src/main/java/org/exist/backup/ZipArchiveBackupDescriptor.java index 515ae009ef0..ca5caa23c42 100644 --- a/exist-core/src/main/java/org/exist/backup/ZipArchiveBackupDescriptor.java +++ b/exist-core/src/main/java/org/exist/backup/ZipArchiveBackupDescriptor.java @@ -34,7 +34,6 @@ import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Enumeration; import java.util.List; @@ -98,8 +97,8 @@ public ZipArchiveBackupDescriptor(final Path fileArchive) throws IOException { throw new FileNotFoundException("Archive " + fileArchive.toAbsolutePath() + " is not a valid eXist backup archive"); } - final Path fakeDbRoot = Paths.get("/db"); - if (!fakeDbRoot.resolve(Paths.get(base)).normalize().startsWith(fakeDbRoot)) { + final Path fakeDbRoot = Path.of("/db"); + if (!fakeDbRoot.resolve(Path.of(base)).normalize().startsWith(fakeDbRoot)) { throw new IOException("Detected archive exit attack! zipFile=" + fileArchive.toAbsolutePath().normalize()); } @@ -173,8 +172,7 @@ public List getChildBackupDescriptors() { return Optional.empty(); } }) - .filter(Optional::isPresent) - .map(Optional::get)) { + .flatMap(Optional::stream)) { return entries.collect(Collectors.toList()); } @@ -256,12 +254,12 @@ public Path getRepoBackup() throws IOException { @Override public Path getParentDir() { - return Paths.get(archive.getName()).getParent(); + return Path.of(archive.getName()).getParent(); } @Override public String getName() { - return FileUtils.fileName(Paths.get(archive.getName())); + return FileUtils.fileName(Path.of(archive.getName())); } private void countDescendantResourceEntries(final ZipFile zipFile, final String base) { diff --git a/exist-core/src/main/java/org/exist/backup/ZipWriter.java b/exist-core/src/main/java/org/exist/backup/ZipWriter.java index 6e214f37030..8c3f94a5a84 100644 --- a/exist-core/src/main/java/org/exist/backup/ZipWriter.java +++ b/exist-core/src/main/java/org/exist/backup/ZipWriter.java @@ -25,7 +25,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Properties; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; @@ -43,7 +42,7 @@ public class ZipWriter implements BackupWriter public ZipWriter(final String zipFile, final String collection) throws IOException { - this(Paths.get(zipFile), collection); + this(Path.of(zipFile), collection); } diff --git a/exist-core/src/main/java/org/exist/backup/restore/AbstractRestoreHandler.java b/exist-core/src/main/java/org/exist/backup/restore/AbstractRestoreHandler.java index 755e4285a17..a3022b30a6f 100644 --- a/exist-core/src/main/java/org/exist/backup/restore/AbstractRestoreHandler.java +++ b/exist-core/src/main/java/org/exist/backup/restore/AbstractRestoreHandler.java @@ -329,7 +329,7 @@ private DeferredPermission restoreResourceEntry(final Attributes attributes) thr is = descriptor.getBlobInputSource(blobId); if (is == null) { - final String msg = String.format("Failed to restore resource '%s'%nfrom BLOB '%s'.%nReason: Unable to obtain its EXistInputSource", commonAttributes.name, blobId); + final String msg = "Failed to restore resource '%s'%nfrom BLOB '%s'.%nReason: Unable to obtain its EXistInputSource".formatted(commonAttributes.name, blobId); listener.warn(msg); return new SkippedEntryDeferredPermission(); } @@ -337,7 +337,7 @@ private DeferredPermission restoreResourceEntry(final Attributes attributes) thr is = descriptor.getInputSource(filename); if (is == null) { - final String msg = String.format("Failed to restore resource '%s'%nfrom file '%s'.%nReason: Unable to obtain its EXistInputSource", commonAttributes.name, descriptor.getSymbolicPath(commonAttributes.name, false)); + final String msg = "Failed to restore resource '%s'%nfrom file '%s'.%nReason: Unable to obtain its EXistInputSource".formatted(commonAttributes.name, descriptor.getSymbolicPath(commonAttributes.name, false)); listener.warn(msg); return new SkippedEntryDeferredPermission(); } @@ -425,7 +425,7 @@ This allows us to commit the transaction (so the restore doesn't stop) return deferredPermission; } catch(final Exception e) { - final String message = String.format("Failed to restore resource '%s'%nfrom file '%s'.%nReason: %s", commonAttributes.name, descriptor.getSymbolicPath(commonAttributes.name, false), e.getMessage()); + final String message = "Failed to restore resource '%s'%nfrom file '%s'.%nReason: %s".formatted(commonAttributes.name, descriptor.getSymbolicPath(commonAttributes.name, false), e.getMessage()); listener.warn(message); LOG.error(message, e); return new SkippedEntryDeferredPermission(); diff --git a/exist-core/src/main/java/org/exist/backup/xquery/ListBackups.java b/exist-core/src/main/java/org/exist/backup/xquery/ListBackups.java index b506855622e..f44e4ca7218 100644 --- a/exist-core/src/main/java/org/exist/backup/xquery/ListBackups.java +++ b/exist-core/src/main/java/org/exist/backup/xquery/ListBackups.java @@ -37,7 +37,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import java.util.Properties; import java.util.regex.Matcher; @@ -67,7 +66,7 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence ) thr } final String exportDir = args[0].getStringValue(); - Path dir = Paths.get(exportDir); + Path dir = Path.of(exportDir); if(!dir.isAbsolute() ) { dir = ((Path)context.getBroker().getConfiguration().getProperty(BrokerPool.PROPERTY_DATA_DIR)).resolve(exportDir); diff --git a/exist-core/src/main/java/org/exist/backup/xquery/RetrieveBackup.java b/exist-core/src/main/java/org/exist/backup/xquery/RetrieveBackup.java index 64a54d8746c..7777220d646 100644 --- a/exist-core/src/main/java/org/exist/backup/xquery/RetrieveBackup.java +++ b/exist-core/src/main/java/org/exist/backup/xquery/RetrieveBackup.java @@ -36,7 +36,6 @@ import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import java.util.Properties; @@ -60,7 +59,7 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence ) thr } final String exportDir = args[0].getStringValue(); - Path dir = Paths.get( exportDir ); + Path dir = Path.of( exportDir ); if( !dir.isAbsolute() ) { dir = ((Path)context.getBroker().getConfiguration().getProperty(BrokerPool.PROPERTY_DATA_DIR)).resolve(exportDir); @@ -92,7 +91,7 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence ) thr final Optional maybeResponse = Optional.ofNullable(context.getHttpContext()) .map(XQueryContext.HttpContext::getResponse); - if(!maybeResponse.isPresent()) { + if(maybeResponse.isEmpty()) { throw( new XPathException( this, "No response object found in the current XQuery context." ) ); } diff --git a/exist-core/src/main/java/org/exist/client/ClientFrame.java b/exist-core/src/main/java/org/exist/client/ClientFrame.java index acf6c7cba92..1ea9fd688c4 100644 --- a/exist-core/src/main/java/org/exist/client/ClientFrame.java +++ b/exist-core/src/main/java/org/exist/client/ClientFrame.java @@ -71,7 +71,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import java.util.List; import java.util.concurrent.*; @@ -89,6 +88,7 @@ */ public class ClientFrame extends JFrame implements WindowFocusListener, KeyListener, ActionListener, MouseListener { + @Serial private static final long serialVersionUID = 1L; public static final String CUT = Messages.getString("ClientFrame.0"); //$NON-NLS-1$ @@ -1016,7 +1016,7 @@ private void backupAction(final ActionEvent ev) { properties.getProperty(InteractiveClient.URI, "xmldb:exist://"), properties.getProperty(InteractiveClient.USER, SecurityManager.DBA_USER), properties.getProperty(InteractiveClient.PASSWORD, null), - Paths.get(preferences.get("directory.backup", System.getProperty("user.home"))), + Path.of(preferences.get("directory.backup", System.getProperty("user.home"))), defaultSelectedCollection ); @@ -1026,10 +1026,10 @@ private void backupAction(final ActionEvent ev) { final String backuptarget = dialog.getBackupTarget(); final boolean deduplicateBlobs = dialog.getDeduplicateBlobs(); - final Path target = Paths.get(backuptarget).normalize(); + final Path target = Path.of(backuptarget).normalize(); if (Files.exists(target)) { final int response = JOptionPane.showConfirmDialog(this, - String.format("%s %s %s", Messages.getString("CreateBackupDialog.6a"), backuptarget, Messages.getString("CreateBackupDialog.6b")), + "%s %s %s".formatted(Messages.getString("CreateBackupDialog.6a"), backuptarget, Messages.getString("CreateBackupDialog.6b")), Messages.getString("CreateBackupDialog.6c"), JOptionPane.YES_NO_OPTION); if (response == JOptionPane.YES_OPTION) { @@ -1044,7 +1044,7 @@ private void backupAction(final ActionEvent ev) { try { final Backup backup = new Backup( properties.getProperty(InteractiveClient.USER, SecurityManager.DBA_USER), - properties.getProperty(InteractiveClient.PASSWORD, null), Paths.get(backuptarget), + properties.getProperty(InteractiveClient.PASSWORD, null), Path.of(backuptarget), XmldbURI.xmldbUriFor(properties.getProperty(InteractiveClient.URI, "xmldb:exist://") + collection), null, deduplicateBlobs @@ -1080,7 +1080,7 @@ private void restoreAction(final ActionEvent ev) { final String restoreFile = f.toAbsolutePath().toString(); final boolean overwriteApps = overwriteCb.isSelected(); final GuiRestoreServiceTaskListener listener = new GuiRestoreServiceTaskListener(this); - doRestore(listener, properties.getProperty(InteractiveClient.USER, SecurityManager.DBA_USER), properties.getProperty(InteractiveClient.PASSWORD, null), newDbaPass, Paths.get(restoreFile), properties.getProperty(InteractiveClient.URI, "xmldb:exist://"), overwriteApps); + doRestore(listener, properties.getProperty(InteractiveClient.USER, SecurityManager.DBA_USER), properties.getProperty(InteractiveClient.PASSWORD, null), newDbaPass, Path.of(restoreFile), properties.getProperty(InteractiveClient.URI, "xmldb:exist://"), overwriteApps); } } } @@ -1136,10 +1136,11 @@ private void doRestore(final GuiRestoreServiceTaskListener listener, final Strin public static void repairRepository(Collection collection) throws XMLDBException { final EXistXQueryService service = collection.getService(EXistXQueryService.class); - service.query("import module namespace repair=\"http://exist-db.org/xquery/repo/repair\"\n" + - "at \"resource:org/exist/xquery/modules/expathrepo/repair.xql\";\n" + - "repair:clean-all(),\n" + - "repair:repair()"); + service.query(""" + import module namespace repair="http://exist-db.org/xquery/repo/repair" + at "resource:org/exist/xquery/modules/expathrepo/repair.xql"; + repair:clean-all(), + repair:repair()"""); } public UserManagementService getUserManagementService() throws XMLDBException { @@ -1174,7 +1175,7 @@ private void exportAction(final ActionEvent ev) { final JFileChooser chooser = new JFileChooser(preferences.get("directory.last", System.getProperty("user.dir"))); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - chooser.setSelectedFile(Paths.get(desc.getName().getCollectionPath()).toFile()); + chooser.setSelectedFile(Path.of(desc.getName().getCollectionPath()).toFile()); if (chooser.showDialog(this, "Select file for export") == JFileChooser.APPROVE_OPTION) { preferences.put("directory.last", chooser.getCurrentDirectory().getAbsolutePath()); final Path file = chooser.getSelectedFile().toPath(); @@ -1190,9 +1191,9 @@ private void exportAction(final ActionEvent ev) { final Collection collection = client.getCollection(); resource = collection .getResource(desc.getName().toString()); - if (resource instanceof ExtendedResource) { + if (resource instanceof ExtendedResource extendedResource) { try(final OutputStream os = new BufferedOutputStream(Files.newOutputStream(file))) { - ((ExtendedResource) resource).getContentIntoAStream(os); + extendedResource.getContentIntoAStream(os); } } else { contentSerializer = (SAXSerializer) SerializerPool @@ -1285,11 +1286,11 @@ private void setPermAction(final ActionEvent ev) throws PermissionDeniedExceptio thisCreated = DATE_TIME_FORMATTER.format(res.getCreationTime()); thisModified = DATE_TIME_FORMATTER.format(res.getLastModificationTime()); thisMimeType = ((EXistResource) res).getMimeType(); - if (res instanceof EXistBinaryResource) { - final MessageDigest messageDigest = ((EXistBinaryResource) res).getContentDigest(DigestType.BLAKE_256); + if (res instanceof EXistBinaryResource resource) { + final MessageDigest messageDigest = resource.getContentDigest(DigestType.BLAKE_256); thisMessageDigestType = messageDigest.getDigestType().getCommonNames()[0]; thisMessageDigestValue = messageDigest.toHexString(); - thisSize = humanSize(((EXistBinaryResource) res).getContentLength()); + thisSize = humanSize(resource.getContentLength()); } else { thisMessageDigestType = NON_APPLICABLE; thisMessageDigestValue = NON_APPLICABLE; @@ -1572,6 +1573,7 @@ public void run() { static class ResourceTableModel extends AbstractTableModel { + @Serial private static final long serialVersionUID = 1L; private final String[] columnNames = new String[]{ @@ -1959,7 +1961,7 @@ private List getFilesUnix(final Transferable transferable) throws ClassNot files = new ArrayList<>(); } - files.add(Paths.get(new URI(token))); + files.add(Path.of(new URI(token))); } return files; diff --git a/exist-core/src/main/java/org/exist/client/ConnectionDialog.java b/exist-core/src/main/java/org/exist/client/ConnectionDialog.java index 5b662702007..fc1c02769b8 100644 --- a/exist-core/src/main/java/org/exist/client/ConnectionDialog.java +++ b/exist-core/src/main/java/org/exist/client/ConnectionDialog.java @@ -25,7 +25,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -70,7 +69,7 @@ private enum ConnectionType { public ConnectionDialog(final java.awt.Frame parent, final boolean modal, final DefaultConnectionSettings defaultConnectionSettings, final boolean embeddedByDefault, final boolean disableEmbeddedConnectionType) { super(parent, modal); this.defaultConnectionSettings = defaultConnectionSettings; - this.config = Paths.get(defaultConnectionSettings.getConfiguration()); + this.config = Path.of(defaultConnectionSettings.getConfiguration()); this.disableEmbeddedConnectionType = disableEmbeddedConnectionType; this.setIconImage(InteractiveClient.getExistIcon(getClass()).getImage()); initComponents(); @@ -587,7 +586,7 @@ private void lstFavouritesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIR }//GEN-LAST:event_lstFavouritesMouseClicked private void miImportFavouritesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miImportFavouritesActionPerformed - final Path file = Paths.get("favourites.xml"); //$NON-NLS-1$ + final Path file = Path.of("favourites.xml"); //$NON-NLS-1$ final JFileChooser chooser = new JFileChooser(); chooser.setSelectedFile(file.toFile()); chooser.showOpenDialog(this); @@ -619,7 +618,7 @@ private void miImportFavouritesActionPerformed(java.awt.event.ActionEvent evt) { }//GEN-LAST:event_miImportFavouritesActionPerformed private void miExportFavouritesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_miExportFavouritesActionPerformed - final Path file = Paths.get(Messages.getString("LoginPanel.25")); //$NON-NLS-1$ + final Path file = Path.of(Messages.getString("LoginPanel.25")); //$NON-NLS-1$ final JFileChooser chooser = new JFileChooser(); chooser.setSelectedFile(file.toFile()); chooser.showSaveDialog(this); diff --git a/exist-core/src/main/java/org/exist/client/DocumentView.java b/exist-core/src/main/java/org/exist/client/DocumentView.java index 315c686830a..1867bac300d 100644 --- a/exist-core/src/main/java/org/exist/client/DocumentView.java +++ b/exist-core/src/main/java/org/exist/client/DocumentView.java @@ -33,7 +33,7 @@ import java.net.URL; import java.nio.charset.Charset; import java.nio.file.Files; -import java.nio.file.Paths; +import java.nio.file.Path; import java.util.Observable; import java.util.Observer; import java.util.Properties; @@ -77,6 +77,7 @@ class DocumentView extends JFrame { + @Serial private static final long serialVersionUID = 1L; protected InteractiveClient client; @@ -343,16 +344,16 @@ private void save() { final Runnable saveTask = () -> { try { statusMessage.setText(Messages.getString("DocumentView.36") + URIUtils.urlDecodeUtf8(resource.getId())); //$NON-NLS-1$ - if (collection instanceof Observable) { - ((Observable) collection) + if (collection instanceof Observable observable) { + observable .addObserver(new ProgressObserver()); } progress.setIndeterminate(true); progress.setVisible(true); resource.setContent(text.getText()); collection.storeResource(resource); - if (collection instanceof Observable) { - ((Observable) collection).deleteObservers(); + if (collection instanceof Observable observable) { + observable.deleteObservers(); } } catch (final XMLDBException e) { ClientFrame.showErrorMessage(Messages.getString("DocumentView.37") //$NON-NLS-1$ @@ -373,8 +374,8 @@ private void saveAs() { try { //Change status message and display a progress dialog statusMessage.setText(Messages.getString("DocumentView.39") + nameres); //$NON-NLS-1$ - if (collection instanceof Observable) { - ((Observable) collection).addObserver(new ProgressObserver()); + if (collection instanceof Observable observable) { + observable.addObserver(new ProgressObserver()); } progress.setIndeterminate(true); progress.setVisible(true); @@ -385,8 +386,8 @@ private void saveAs() { result.setContent(text.getText()); collection.storeResource(result); client.reloadCollection(); //reload the client collection - if (collection instanceof Observable) { - ((Observable) collection).deleteObservers(); + if (collection instanceof Observable observable) { + observable.deleteObservers(); } } catch (final XMLDBException e) { ClientFrame.showErrorMessage(Messages.getString("DocumentView.40") + e.getMessage(), e); //$NON-NLS-1$ @@ -406,7 +407,7 @@ private void export() throws XMLDBException { final JFileChooser chooser = new JFileChooser(workDir); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); - chooser.setSelectedFile(Paths.get(resource.getId()).toFile()); + chooser.setSelectedFile(Path.of(resource.getId()).toFile()); if (chooser.showDialog(this, Messages.getString("DocumentView.44")) == JFileChooser.APPROVE_OPTION) { final File file = chooser.getSelectedFile(); diff --git a/exist-core/src/main/java/org/exist/client/HighlightedTableCellRenderer.java b/exist-core/src/main/java/org/exist/client/HighlightedTableCellRenderer.java index cd0531cd27c..e2075f2adc2 100644 --- a/exist-core/src/main/java/org/exist/client/HighlightedTableCellRenderer.java +++ b/exist-core/src/main/java/org/exist/client/HighlightedTableCellRenderer.java @@ -47,16 +47,16 @@ public class HighlightedTableCellRenderer extends */ @Override public Component getTableCellRendererComponent(final JTable table, Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { - if(value instanceof XmldbURI) { - value = new PrettyXmldbURI((XmldbURI)value); + if(value instanceof XmldbURI rI) { + value = new PrettyXmldbURI(rI); } final Component renderer = super.getTableCellRendererComponent(table, value, isSelected,hasFocus, row, column); - if(renderer instanceof JCheckBox) { - ((JCheckBox)renderer).setOpaque(true); - } else if(renderer instanceof JLabel) { - ((JLabel)renderer).setOpaque(true); + if(renderer instanceof JCheckBox box) { + box.setOpaque(true); + } else if(renderer instanceof JLabel label) { + label.setOpaque(true); } final Color foreground; @@ -65,7 +65,7 @@ public Component getTableCellRendererComponent(final JTable table, Object value, if (isSelected) { foreground = highForeground; background = highBackground; - } else if (resources instanceof ResourceTableModel && ((ResourceTableModel)resources).getRow(row).isCollection()) { + } else if (resources instanceof ResourceTableModel model && model.getRow(row).isCollection()) { foreground = collectionForeground; background = collectionBackground; } else if (row % 2 == 0) { diff --git a/exist-core/src/main/java/org/exist/client/IndexDialog.java b/exist-core/src/main/java/org/exist/client/IndexDialog.java index 6acf725ea0c..e0aeff35292 100644 --- a/exist-core/src/main/java/org/exist/client/IndexDialog.java +++ b/exist-core/src/main/java/org/exist/client/IndexDialog.java @@ -36,6 +36,7 @@ import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; +import java.io.Serial; import java.util.ArrayList; /** @@ -47,7 +48,8 @@ */ class IndexDialog extends JFrame { - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; private static final String[] CONFIG_TYPE = { "qname", @@ -346,7 +348,8 @@ private void actionGetIndexes(String collectionName) public static class ComboBoxCellRenderer extends JComboBox implements TableCellRenderer { - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; public ComboBoxCellRenderer(String[] items) { @@ -375,7 +378,8 @@ public Component getTableCellRendererComponent(JTable table, Object value, boole public static class ComboBoxCellEditor extends DefaultCellEditor { - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; public ComboBoxCellEditor(String[] items) { @@ -384,8 +388,9 @@ public ComboBoxCellEditor(String[] items) } class RangeIndexTableModel extends AbstractTableModel - { - private static final long serialVersionUID = 1L; + { + @Serial + private static final long serialVersionUID = 1L; private final String[] columnNames = new String[] { "Type", "XPath", "xsType" }; diff --git a/exist-core/src/main/java/org/exist/client/InteractiveClient.java b/exist-core/src/main/java/org/exist/client/InteractiveClient.java index cea242b147a..6c045bca3b2 100644 --- a/exist-core/src/main/java/org/exist/client/InteractiveClient.java +++ b/exist-core/src/main/java/org/exist/client/InteractiveClient.java @@ -30,7 +30,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.util.*; @@ -662,7 +661,7 @@ protected boolean process(final String line) { messageln("please specify a query file."); return true; } - try (final BufferedReader reader = Files.newBufferedReader(Paths.get(args[1]))) { + try (final BufferedReader reader = Files.newBufferedReader(Path.of(args[1]))) { final StringBuilder buf = new StringBuilder(); String nextLine; while ((nextLine = reader.readLine()) != null) { @@ -760,7 +759,7 @@ protected boolean process(final String line) { messageln("missing argument."); return true; } - final boolean r = parse(Paths.get(args[1])); + final boolean r = parse(Path.of(args[1])); getResources(); return r; @@ -770,7 +769,7 @@ protected boolean process(final String line) { messageln("missing argument."); return true; } - final boolean r = parseZip(Paths.get(args[1])); + final boolean r = parseZip(Path.of(args[1])); getResources(); return r; @@ -1133,7 +1132,7 @@ private Optional getTraceWriter() { if (options.traceQueriesFile.isPresent()) { //lazy initialization - if (!lazyTraceWriter.isPresent()) { + if (lazyTraceWriter.isEmpty()) { try (final Writer traceWriter = Files.newBufferedWriter(options.traceQueriesFile.get(), UTF_8)) { traceWriter.write("" + EOL); traceWriter.write("" + EOL); @@ -1282,7 +1281,7 @@ private void reindex() throws XMLDBException { } private void storeBinary(final String fileName) throws XMLDBException { - final Path file = Paths.get(fileName).normalize(); + final Path file = Path.of(fileName).normalize(); if (Files.isReadable(file)) { final MimeType mime = MimeTable.getInstance().getContentTypeFor(FileUtils.fileName(file)); try (final BinaryResource resource = current.createResource(FileUtils.fileName(file), BinaryResource.class)) { @@ -1314,9 +1313,9 @@ private synchronized boolean findRecursive(final Collection collection, final Pa c = mgtService.createCollection(XmldbURI.xmldbUriFor(FileUtils.fileName(file))); } - if (c instanceof Observable && options.verbose) { + if (c instanceof Observable observable && options.verbose) { final ProgressObserver observer = new ProgressObserver(); - ((Observable) c).addObserver(observer); + observable.addObserver(observer); } findRecursive(c, file, next); } else { @@ -1357,9 +1356,9 @@ protected synchronized boolean parse(final Path file) throws XMLDBException { try { // String xml; - if (current instanceof Observable && options.verbose) { + if (current instanceof Observable observable && options.verbose) { final ProgressObserver observer = new ProgressObserver(); - ((Observable) current).addObserver(observer); + observable.addObserver(observer); } List files = new ArrayList<>(); @@ -1385,7 +1384,7 @@ protected synchronized boolean parse(final Path file) throws XMLDBException { directoryScanner.scan(); for (final String includedFile : directoryScanner.getIncludedFiles()) { // files.add(baseDir.resolve(includedFile)); - files.add(Paths.get(includedFile)); + files.add(Path.of(includedFile)); } } @@ -1439,9 +1438,9 @@ private synchronized boolean findGZipRecursive(final Collection collection, fina mgtService = collection.getService(EXistCollectionManagementService.class); c = mgtService.createCollection(XmldbURI.xmldbUriFor(FileUtils.fileName(file))); } - if (c instanceof Observable && options.verbose) { + if (c instanceof Observable observable && options.verbose) { final ProgressObserver observer = new ProgressObserver(); - ((Observable) c).addObserver(observer); + observable.addObserver(observer); } findGZipRecursive(c, file, next); } else { @@ -1492,11 +1491,11 @@ protected synchronized boolean parseGZip(String fileName) throws XMLDBException, //TODO : why is this test for ? Fileshould make it, shouldn't it ? -pb fileName = fileName.replace('/', java.io.File.separatorChar).replace('\\', java.io.File.separatorChar); - final Path file = Paths.get(fileName); + final Path file = Path.of(fileName); // String xml; - if (current instanceof Observable && options.verbose) { + if (current instanceof Observable observable && options.verbose) { final ProgressObserver observer = new ProgressObserver(); - ((Observable) current).addObserver(observer); + observable.addObserver(observer); } final List files; if (Files.isReadable(file)) { @@ -1527,7 +1526,7 @@ protected synchronized boolean parseGZip(String fileName) throws XMLDBException, files = new ArrayList<>(includedFiles.length); for (final String includedFile : includedFiles) { // files.add(baseDir.resolve(includedFile)); - files.add(Paths.get(includedFile)); + files.add(Path.of(includedFile)); } } @@ -1583,9 +1582,9 @@ protected synchronized boolean parseGZip(String fileName) throws XMLDBException, */ protected synchronized boolean parseZip(final Path zipPath) throws XMLDBException { try (final ZipFile zfile = new ZipFile(zipPath.toFile())) { - if (current instanceof Observable && options.verbose) { + if (current instanceof Observable observable && options.verbose) { final ProgressObserver observer = new ProgressObserver(); - ((Observable) current).addObserver(observer); + observable.addObserver(observer); } final long start0 = System.currentTimeMillis(); @@ -1600,7 +1599,7 @@ protected synchronized boolean parseZip(final Path zipPath) throws XMLDBExceptio final ZipEntry ze = e.nextElement(); final String zeName = ze.getName().replace('\\', '/'); - if (!Paths.get("/db").resolve(zeName).normalize().startsWith(Paths.get("/db"))) { + if (!Path.of("/db").resolve(zeName).normalize().startsWith(Path.of("/db"))) { throw new IOException("Detected archive exit attack! zipFile=" + zipPath.toAbsolutePath() + ", entry=" + ze.getName()); } @@ -1621,9 +1620,9 @@ protected synchronized boolean parseZip(final Path zipPath) throws XMLDBExceptio } base = c; } - if (base instanceof Observable && options.verbose) { + if (base instanceof Observable observable && options.verbose) { final ProgressObserver observer = new ProgressObserver(); - ((Observable) base).addObserver(observer); + observable.addObserver(observer); } baseStr = currStr.toString(); messageln("entering directory " + baseStr); @@ -1672,8 +1671,8 @@ protected synchronized boolean parse(final List files, final UploadDialog upload.setVisible(true); } - if (uploadRootCollection instanceof Observable) { - ((Observable) uploadRootCollection).addObserver(upload.getObserver()); + if (uploadRootCollection instanceof Observable observable) { + observable.addObserver(upload.getObserver()); } upload.setTotalSize(FileUtils.sizeQuietly(files)); for (final Path file : files) { @@ -1683,8 +1682,8 @@ protected synchronized boolean parse(final List files, final UploadDialog // should replace the lines above store(uploadRootCollection, file, upload); } - if (uploadRootCollection instanceof Observable) { - ((Observable) uploadRootCollection).deleteObservers(); + if (uploadRootCollection instanceof Observable observable) { + observable.deleteObservers(); } upload.uploadCompleted(); return true; @@ -1734,8 +1733,8 @@ private void store(final Collection collection, final Path file, final UploadDia // change displayed collection if it's OK upload.setCurrentDir(file.toAbsolutePath().toString()); - if (c instanceof Observable) { - ((Observable) c).addObserver(upload.getObserver()); + if (c instanceof Observable observable) { + observable.addObserver(upload.getObserver()); } // maybe a depth or recurs flag could be added here final Collection childCollection = c; @@ -1829,7 +1828,7 @@ protected void setPropertiesFromCommandLine(final CommandlineOptions options, fi options.username.ifPresent(username -> props.setProperty(USER, username)); options.password.ifPresent(password -> props.setProperty(PASSWORD, password)); - boolean needPassword = options.username.isPresent() && !options.password.isPresent(); + boolean needPassword = options.username.isPresent() && options.password.isEmpty(); if (options.useSSL) { props.setProperty(SSL_ENABLE, "TRUE"); } @@ -1991,8 +1990,8 @@ private boolean processCommandLineActions() throws IOException { for (int i = 0; i < maxResults && i < result.getSize(); i++) { final Resource res = result.getResource(i); - if (res instanceof ExtendedResource) { - ((ExtendedResource) res).getContentIntoAStream(ps); + if (res instanceof ExtendedResource resource) { + resource.getContentIntoAStream(ps); } else { ps.print(res.getContent().toString()); } @@ -2001,8 +2000,8 @@ private boolean processCommandLineActions() throws IOException { } else { for (int i = 0; i < maxResults && i < result.getSize(); i++) { final Resource res = result.getResource(i); - if (res instanceof ExtendedResource) { - ((ExtendedResource) res).getContentIntoAStream(System.out); + if (res instanceof ExtendedResource resource) { + resource.getContentIntoAStream(System.out); } else { consoleOut(String.valueOf(res.getContent())); } @@ -2099,8 +2098,8 @@ public boolean run() throws Exception { return false; } - historyFile = home.map(h -> h.resolve(".exist_history")).orElse(Paths.get(".exist_history")); - queryHistoryFile = home.map(h -> h.resolve(".exist_query_history")).orElse(Paths.get(".exist_query_history")); + historyFile = home.map(h -> h.resolve(".exist_history")).orElse(Path.of(".exist_history")); + queryHistoryFile = home.map(h -> h.resolve(".exist_query_history")).orElse(Path.of(".exist_query_history")); readQueryHistory(); if (interactive) { @@ -2153,7 +2152,7 @@ private boolean checkLoginInfos(boolean interactive) { return true; } - } else if (options.username.isPresent() && !options.password.isPresent()) { + } else if (options.username.isPresent() && options.password.isEmpty()) { try { properties.setProperty(PASSWORD, console.readLine("password: ", '*')); } catch (final Exception e) { @@ -2166,7 +2165,7 @@ private boolean checkLoginInfos(boolean interactive) { private void applyDefaultConfig(Optional home) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException { Optional configFile = ConfigurationHelper.getFromSystemProperty(); - if (!configFile.isPresent()) { + if (configFile.isEmpty()) { final Class cl = Class.forName(properties.getProperty(DRIVER)); final Field CONF_XML = cl.getDeclaredField("CONF_XML"); if (CONF_XML != null && home.isPresent()) { @@ -2593,8 +2592,8 @@ public void update(final Observable o, final Object obj) { private void writeOutputFile(final Path file, final Object data) throws IOException { try (final OutputStream os = new BufferedOutputStream(Files.newOutputStream(file))) { - if (data instanceof byte[]) { - os.write((byte[]) data); + if (data instanceof byte[] bytes) { + os.write(bytes); } else { try (final Writer writer = new OutputStreamWriter(os, Charset.forName(properties.getProperty(ENCODING)))) { writer.write(data.toString()); diff --git a/exist-core/src/main/java/org/exist/client/QueryDialog.java b/exist-core/src/main/java/org/exist/client/QueryDialog.java index 5c7c3d58198..188010222e0 100644 --- a/exist-core/src/main/java/org/exist/client/QueryDialog.java +++ b/exist-core/src/main/java/org/exist/client/QueryDialog.java @@ -31,7 +31,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Properties; @@ -86,6 +85,7 @@ import static org.xmldb.api.base.ResourceType.XML_RESOURCE; public class QueryDialog extends JFrame { + @Serial private static final long serialVersionUID = 1L; private static final String LOADING_INDICATOR = "Loading..."; @@ -410,7 +410,7 @@ public void popupMenuCanceled(final PopupMenuEvent e) { private void open() { final String workDir = properties.getProperty(WORKING_DIR, System.getProperty("user.dir")); final JFileChooser chooser = new JFileChooser(); - chooser.setCurrentDirectory(Paths.get(workDir).toFile()); + chooser.setCurrentDirectory(Path.of(workDir).toFile()); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.addChoosableFileFilter(new MimeTypeFileFilter("application/xquery")); @@ -446,7 +446,7 @@ private void save(String stringToSave, String fileCategory) { final String workDir = properties.getProperty(WORKING_DIR, System.getProperty("user.dir")); final JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); - chooser.setCurrentDirectory(Paths.get(workDir).toFile()); + chooser.setCurrentDirectory(Path.of(workDir).toFile()); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); if ("result".equals(fileCategory)) { chooser.addChoosableFileFilter(new MimeTypeFileFilter("application/xhtml+xml")); @@ -576,8 +576,8 @@ public void run() { final CompiledExpression compiled = service.compile(xpath); final long t1 = System.currentTimeMillis(); // Check could also be collection instanceof LocalCollection - if (compiled instanceof CompiledXQuery) { - context = ((CompiledXQuery) compiled).getContext(); + if (compiled instanceof CompiledXQuery xQuery) { + context = xQuery.getContext(); runningContext.set(context); } tCompiled = t1 - t0; diff --git a/exist-core/src/main/java/org/exist/client/ResourceDescriptor.java b/exist-core/src/main/java/org/exist/client/ResourceDescriptor.java index b235a0710f0..9f0b87cf98b 100644 --- a/exist-core/src/main/java/org/exist/client/ResourceDescriptor.java +++ b/exist-core/src/main/java/org/exist/client/ResourceDescriptor.java @@ -80,7 +80,7 @@ public boolean isCollection() { @Override public String getPermissionsDescription() { - return "-" + ((permissions instanceof ACLPermission && ((ACLPermission) permissions).getACECount() > 0) ? permissions.toString() + '+' : permissions.toString()); + return "-" + ((permissions instanceof ACLPermission aclp && aclp.getACECount() > 0) ? permissions.toString() + '+' : permissions.toString()); } } @@ -100,8 +100,8 @@ public boolean isCollection() { @Override public String getPermissionsDescription() { - return "c" + ((permissions instanceof ACLPermission && ((ACLPermission) permissions).getACECount() > 0) ? permissions.toString() + '+' : permissions.toString()); + return "c" + ((permissions instanceof ACLPermission aclp && aclp.getACECount() > 0) ? permissions.toString() + '+' : permissions.toString()); } } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/client/TriggersDialog.java b/exist-core/src/main/java/org/exist/client/TriggersDialog.java index 832b2af8581..398aeddae41 100644 --- a/exist-core/src/main/java/org/exist/client/TriggersDialog.java +++ b/exist-core/src/main/java/org/exist/client/TriggersDialog.java @@ -28,6 +28,7 @@ import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; +import java.io.Serial; import java.util.ArrayList; import java.util.List; import javax.swing.Box; @@ -58,6 +59,7 @@ */ class TriggersDialog extends JFrame { + @Serial private static final long serialVersionUID = 1L; private CollectionXConf cx = null; @@ -257,6 +259,7 @@ private void actionGetTriggers(final String collectionName) { } public static class CheckBoxCellRenderer extends JCheckBox implements TableCellRenderer { + @Serial private static final long serialVersionUID = 1L; public CheckBoxCellRenderer() { @@ -281,6 +284,7 @@ public Component getTableCellRendererComponent(final JTable table, final Object } public static class CheckBoxCellEditor extends DefaultCellEditor { + @Serial private static final long serialVersionUID = 1L; public CheckBoxCellEditor() { @@ -289,6 +293,7 @@ public CheckBoxCellEditor() { } class TriggersTableModel extends AbstractTableModel { + @Serial private static final long serialVersionUID = 1L; private final String[] columnNames = new String[] { "class", "Parameters" }; diff --git a/exist-core/src/main/java/org/exist/client/UploadDialog.java b/exist-core/src/main/java/org/exist/client/UploadDialog.java index c3193d50ce5..6de37f8a9cb 100644 --- a/exist-core/src/main/java/org/exist/client/UploadDialog.java +++ b/exist-core/src/main/java/org/exist/client/UploadDialog.java @@ -24,6 +24,7 @@ import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; +import java.io.Serial; import java.util.Observable; import java.util.Observer; @@ -41,7 +42,8 @@ class UploadDialog extends JFrame { - private static final long serialVersionUID = 1L; + @Serial + private static final long serialVersionUID = 1L; JTextField currentFile; JTextField currentDir; diff --git a/exist-core/src/main/java/org/exist/client/security/EditGroupDialog.java b/exist-core/src/main/java/org/exist/client/security/EditGroupDialog.java index defe5a7231d..707477a63ab 100644 --- a/exist-core/src/main/java/org/exist/client/security/EditGroupDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/EditGroupDialog.java @@ -21,6 +21,7 @@ */ package org.exist.client.security; +import java.io.Serial; import java.util.Arrays; import java.util.HashSet; import java.util.List; @@ -38,7 +39,8 @@ * @author Adam Retter */ public class EditGroupDialog extends GroupDialog { - + + @Serial private static final long serialVersionUID = -9092253443709031810L; private final Group group; diff --git a/exist-core/src/main/java/org/exist/client/security/EditUserDialog.java b/exist-core/src/main/java/org/exist/client/security/EditUserDialog.java index fe8e922c1a2..13f200c5463 100644 --- a/exist-core/src/main/java/org/exist/client/security/EditUserDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/EditUserDialog.java @@ -21,6 +21,7 @@ */ package org.exist.client.security; +import java.io.Serial; import java.util.*; import javax.swing.JOptionPane; import org.exist.client.DialogCompleteWithResponse; @@ -38,7 +39,8 @@ * @author Adam Retter */ public class EditUserDialog extends UserDialog implements DialogWithResponse { - + + @Serial private static final long serialVersionUID = 9097018734007436201L; private final static String HIDDEN_PASSWORD_CONST = "password"; diff --git a/exist-core/src/main/java/org/exist/client/security/GroupDialog.java b/exist-core/src/main/java/org/exist/client/security/GroupDialog.java index 6a6e1915bdb..f621f9f8d60 100644 --- a/exist-core/src/main/java/org/exist/client/security/GroupDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/GroupDialog.java @@ -21,6 +21,7 @@ */ package org.exist.client.security; +import java.io.Serial; import java.util.regex.Pattern; import javax.swing.InputVerifier; import javax.swing.JOptionPane; @@ -39,6 +40,7 @@ */ public class GroupDialog extends javax.swing.JFrame { + @Serial private static final long serialVersionUID = 2291775874309563932L; private final Pattern PTN_GROUPNAME = Pattern.compile("[a-zA-Z0-9\\-\\._@]{3,}"); diff --git a/exist-core/src/main/java/org/exist/client/security/ReadOnlyDefaultTableModel.java b/exist-core/src/main/java/org/exist/client/security/ReadOnlyDefaultTableModel.java index f98c6fbef4f..01c0edbfee2 100644 --- a/exist-core/src/main/java/org/exist/client/security/ReadOnlyDefaultTableModel.java +++ b/exist-core/src/main/java/org/exist/client/security/ReadOnlyDefaultTableModel.java @@ -23,12 +23,15 @@ import javax.swing.table.DefaultTableModel; +import java.io.Serial; + /** * * @author Adam Retter */ public class ReadOnlyDefaultTableModel extends DefaultTableModel { + @Serial private static final long serialVersionUID = 8229062312676408884L; public ReadOnlyDefaultTableModel(final String[][] data, final String[] columnNames) { diff --git a/exist-core/src/main/java/org/exist/client/security/RegExpInputVerifier.java b/exist-core/src/main/java/org/exist/client/security/RegExpInputVerifier.java index 0446cad38ca..8e7b928ac7e 100644 --- a/exist-core/src/main/java/org/exist/client/security/RegExpInputVerifier.java +++ b/exist-core/src/main/java/org/exist/client/security/RegExpInputVerifier.java @@ -41,8 +41,8 @@ public RegExpInputVerifier(final Pattern pattern) { @Override public boolean verify(final JComponent input) { - if(input instanceof JTextField) { - matcher.reset(((JTextField)input).getText()); + if(input instanceof JTextField field) { + matcher.reset(field.getText()); return matcher.matches(); } diff --git a/exist-core/src/main/java/org/exist/client/security/SortedListModel.java b/exist-core/src/main/java/org/exist/client/security/SortedListModel.java index 429dbc04cfd..01b90990bf3 100644 --- a/exist-core/src/main/java/org/exist/client/security/SortedListModel.java +++ b/exist-core/src/main/java/org/exist/client/security/SortedListModel.java @@ -20,7 +20,8 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.exist.client.security; - + +import java.io.Serial; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; @@ -30,6 +31,7 @@ public class SortedListModel extends AbstractListModel { + @Serial private static final long serialVersionUID = 8156990970750901747L; private final SortedSet model; @@ -70,7 +72,7 @@ public boolean contains(Object element) { } public T firstElement() { - return model.first(); + return model.getFirst(); } public Iterator iterator() { @@ -78,7 +80,7 @@ public Iterator iterator() { } public T lastElement() { - return model.last(); + return model.getLast(); } public boolean removeElement(final T element) { @@ -88,4 +90,4 @@ public boolean removeElement(final T element) { } return removed; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/client/security/UmaskEditor.java b/exist-core/src/main/java/org/exist/client/security/UmaskEditor.java index 10ea11eaaa2..62e2e5551f7 100644 --- a/exist-core/src/main/java/org/exist/client/security/UmaskEditor.java +++ b/exist-core/src/main/java/org/exist/client/security/UmaskEditor.java @@ -27,12 +27,15 @@ import javax.swing.JTextField; import javax.swing.text.DefaultFormatterFactory; +import java.io.Serial; + /** * * @author Adam Retter */ public class UmaskEditor extends DefaultEditor { - + + @Serial private static final long serialVersionUID = 1531848918506511061L; public UmaskEditor(final JSpinner jSpinner) { diff --git a/exist-core/src/main/java/org/exist/client/security/UmaskEditorFormatter.java b/exist-core/src/main/java/org/exist/client/security/UmaskEditorFormatter.java index 2c291fe5485..5fbef34ad6f 100644 --- a/exist-core/src/main/java/org/exist/client/security/UmaskEditorFormatter.java +++ b/exist-core/src/main/java/org/exist/client/security/UmaskEditorFormatter.java @@ -21,6 +21,7 @@ */ package org.exist.client.security; +import java.io.Serial; import java.text.ParseException; import javax.swing.JFormattedTextField.AbstractFormatter; import javax.swing.text.DocumentFilter; @@ -31,6 +32,7 @@ */ public class UmaskEditorFormatter extends AbstractFormatter { + @Serial private static final long serialVersionUID = -1209002227738149636L; @Override diff --git a/exist-core/src/main/java/org/exist/client/security/UmaskSpinnerModel.java b/exist-core/src/main/java/org/exist/client/security/UmaskSpinnerModel.java index 9094bda9f2a..86fb9c06c5a 100644 --- a/exist-core/src/main/java/org/exist/client/security/UmaskSpinnerModel.java +++ b/exist-core/src/main/java/org/exist/client/security/UmaskSpinnerModel.java @@ -98,6 +98,6 @@ public static int octalUmaskToInt(final String octalUmask) { } public static String intToOctalUmask(final int umask) { - return String.format("%4s", Integer.toString(umask, OCTAL_RADIX)).replace(' ', '0'); + return "%4s".formatted(Integer.toString(umask, OCTAL_RADIX)).replace(' ', '0'); } } diff --git a/exist-core/src/main/java/org/exist/client/security/UserDialog.java b/exist-core/src/main/java/org/exist/client/security/UserDialog.java index cb6b1267fff..76f1a62578f 100644 --- a/exist-core/src/main/java/org/exist/client/security/UserDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/UserDialog.java @@ -21,6 +21,7 @@ */ package org.exist.client.security; +import java.io.Serial; import java.util.Iterator; import java.util.regex.Pattern; import javax.swing.InputVerifier; @@ -41,6 +42,7 @@ */ public class UserDialog extends javax.swing.JFrame { + @Serial private static final long serialVersionUID = -7544980948396443454L; private final Pattern PTN_USERNAME = Pattern.compile("[a-zA-Z0-9\\-\\._@]{3,}"); @@ -504,7 +506,7 @@ private InputVerifier getPasswordInputVerifier() { } private String getUmask() { - return String.format("%4s", Integer.toString(Permission.DEFAULT_UMASK, UmaskSpinnerModel.OCTAL_RADIX)).replace(' ', '0'); + return "%4s".formatted(Integer.toString(Permission.DEFAULT_UMASK, UmaskSpinnerModel.OCTAL_RADIX)).replace(' ', '0'); } protected SortedListModel getAvailableGroupsListModel() { diff --git a/exist-core/src/main/java/org/exist/client/security/UserManagerDialog.java b/exist-core/src/main/java/org/exist/client/security/UserManagerDialog.java index 6bfff3d75ae..9148415e6c4 100644 --- a/exist-core/src/main/java/org/exist/client/security/UserManagerDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/UserManagerDialog.java @@ -24,6 +24,7 @@ import org.exist.client.DialogCompleteWithResponse; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; +import java.io.Serial; import java.util.Arrays; import java.util.Properties; import javax.swing.JOptionPane; @@ -47,6 +48,7 @@ */ public class UserManagerDialog extends javax.swing.JFrame { + @Serial private static final long serialVersionUID = 2091215304766070041L; private UserManagementService userManagementService; diff --git a/exist-core/src/main/java/org/exist/collections/CollectionConfigurationException.java b/exist-core/src/main/java/org/exist/collections/CollectionConfigurationException.java index 305076a0b30..76eea54d0a5 100644 --- a/exist-core/src/main/java/org/exist/collections/CollectionConfigurationException.java +++ b/exist-core/src/main/java/org/exist/collections/CollectionConfigurationException.java @@ -21,12 +21,15 @@ */ package org.exist.collections; +import java.io.Serial; + /** * @author wolf */ public class CollectionConfigurationException extends Exception { - private static final long serialVersionUID = 2646147244407222955L; + @Serial + private static final long serialVersionUID = 2646147244407222955L; /** * diff --git a/exist-core/src/main/java/org/exist/collections/LockedCollection.java b/exist-core/src/main/java/org/exist/collections/LockedCollection.java index 10138374e30..199c45445e6 100644 --- a/exist-core/src/main/java/org/exist/collections/LockedCollection.java +++ b/exist-core/src/main/java/org/exist/collections/LockedCollection.java @@ -77,9 +77,9 @@ public LockedCollection(final ManagedCollectionLock managedCollectionLock, final */ public static Collection unwrapLocked(final Collection collection) { //TODO(AR) do we want to stay with LockedCollection implements Collection design {@link LockedCollection#getCollection()} - if(collection instanceof LockedCollection) { + if(collection instanceof LockedCollection lockedCollection) { // unwrap the locked collection - return ((LockedCollection)collection).collection; + return lockedCollection.collection; } else { return collection; } diff --git a/exist-core/src/main/java/org/exist/collections/triggers/TriggerException.java b/exist-core/src/main/java/org/exist/collections/triggers/TriggerException.java index a28cbb5b511..a88102f2d59 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/TriggerException.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/TriggerException.java @@ -23,12 +23,15 @@ import org.xml.sax.SAXException; +import java.io.Serial; + /** * @author wolf */ public class TriggerException extends SAXException { - private static final long serialVersionUID = -6501877347817156557L; + @Serial + private static final long serialVersionUID = -6501877347817156557L; public TriggerException() { super(); diff --git a/exist-core/src/main/java/org/exist/collections/triggers/TriggerStatePerThread.java b/exist-core/src/main/java/org/exist/collections/triggers/TriggerStatePerThread.java index 1e24fb9aa58..d566c74414d 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/TriggerStatePerThread.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/TriggerStatePerThread.java @@ -190,8 +190,8 @@ public String toString() { builder.append(')'); builder.append(": "); builder.append(trigger.getClass().getSimpleName()); - if (trigger instanceof XQueryTrigger) { - final String urlQuery = ((XQueryTrigger) trigger).getUrlQuery(); + if (trigger instanceof XQueryTrigger queryTrigger) { + final String urlQuery = queryTrigger.getUrlQuery(); if (urlQuery != null && !urlQuery.isEmpty()) { builder.append('('); builder.append(urlQuery); diff --git a/exist-core/src/main/java/org/exist/collections/triggers/XQueryTrigger.java b/exist-core/src/main/java/org/exist/collections/triggers/XQueryTrigger.java index 2e4bd8c2328..d272cd416c1 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/XQueryTrigger.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/XQueryTrigger.java @@ -352,8 +352,8 @@ private CompiledXQuery getScript(final DBBroker broker, final Txn transaction) t } final XQueryContext context = new XQueryContext(broker.getBrokerPool()); - if (query instanceof DBSource) { - context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI_PREFIX + ((DBSource)query).getDocumentPath().removeLastSegment().toString()); + if (query instanceof DBSource source) { + context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI_PREFIX + source.getDocumentPath().removeLastSegment().toString()); } CompiledXQuery compiledQuery; diff --git a/exist-core/src/main/java/org/exist/config/ConfigurationDocumentTrigger.java b/exist-core/src/main/java/org/exist/config/ConfigurationDocumentTrigger.java index ce1fc9dd6d0..e9ac7b9595d 100644 --- a/exist-core/src/main/java/org/exist/config/ConfigurationDocumentTrigger.java +++ b/exist-core/src/main/java/org/exist/config/ConfigurationDocumentTrigger.java @@ -427,8 +427,8 @@ private String findName() { } } - if (inName && event instanceof Characters) { - name.append(((Characters) event).ch); + if (inName && event instanceof Characters characters) { + name.append(characters.ch); } } diff --git a/exist-core/src/main/java/org/exist/config/ConfigurationException.java b/exist-core/src/main/java/org/exist/config/ConfigurationException.java index e1fb840cceb..05a2b9932eb 100644 --- a/exist-core/src/main/java/org/exist/config/ConfigurationException.java +++ b/exist-core/src/main/java/org/exist/config/ConfigurationException.java @@ -23,11 +23,14 @@ import org.exist.EXistException; +import java.io.Serial; + /** * @author Dmitriy Shabanov */ public class ConfigurationException extends EXistException { + @Serial private static final long serialVersionUID = 1441009248525222734L; public ConfigurationException() { diff --git a/exist-core/src/main/java/org/exist/config/Configurator.java b/exist-core/src/main/java/org/exist/config/Configurator.java index 5a349f8d788..1d33f7a168e 100644 --- a/exist-core/src/main/java/org/exist/config/Configurator.java +++ b/exist-core/src/main/java/org/exist/config/Configurator.java @@ -432,15 +432,15 @@ private static Configuration configureByCurrent(final Configurable instance, fin list.remove(i); //TODO Surely we should log a problem here or throw an exception? continue; - } else if (obj instanceof Reference) { + } else if (obj instanceof Reference reference) { - if (!referenceBy.isPresent()) { + if (referenceBy.isEmpty()) { LOG.error("illegal design '{}' [{}]", configuration.getName(), field); list.remove(i); continue; } else { - final String name = ((Reference) obj).getName(); + final String name = reference.getName(); //Lookup for new configuration, update if found final List applicableConfs = filter(confs, conf -> @@ -515,7 +515,7 @@ private static Configuration configureByCurrent(final Configurable instance, fin if(value != null) { final Optional> updateFn = updateListFn(instance, confName, removed, value); - if(!updateFn.isPresent()) { + if(updateFn.isEmpty()) { LOG.error("Could not insert configured object"); } else { try { @@ -535,7 +535,7 @@ private static Configuration configureByCurrent(final Configurable instance, fin if (value != null) { final Optional> updateFn = updateListFn(instance, confName, removed, value); - if(!updateFn.isPresent()) { + if(updateFn.isEmpty()) { LOG.error("Could not insert configured object"); } else { try { @@ -579,7 +579,7 @@ private static Configuration configureByCurrent(final Configurable instance, fin objs = new Object[]{id.toLowerCase(), id}; } - final String clazzName = String.format(annotation.value(), objs); + final String clazzName = annotation.value().formatted(objs); final Configurable obj = create(conf, instance, clazzName); if (obj != null) { @@ -707,7 +707,7 @@ private static Configurable create(final Configuration conf, final Configurable return null; } - if (obj instanceof LifeCycle) { + if (obj instanceof LifeCycle cycle) { BrokerPool db = null; try { @@ -721,7 +721,7 @@ private static Configurable create(final Configuration conf, final Configurable if (db != null) { try(final DBBroker broker = db.getBroker(); final Txn transaction = broker.continueOrBeginTransaction()) { - ((LifeCycle) obj).start(broker, transaction); + cycle.start(broker, transaction); transaction.commit(); } } @@ -1068,8 +1068,8 @@ private static void serializeList(final Configurable instance, //determine the list entries type from its generic type final Type fieldGenericType = field.getGenericType(); - if (fieldGenericType instanceof ParameterizedType) { - final Type genericTypeArgs[] = ((ParameterizedType) fieldGenericType).getActualTypeArguments(); + if (fieldGenericType instanceof ParameterizedType type) { + final Type genericTypeArgs[] = type.getActualTypeArguments(); if (genericTypeArgs != null && genericTypeArgs.length == 1) { final Type genericListType = genericTypeArgs[0]; if (genericListType.equals(String.class)) { @@ -1136,8 +1136,8 @@ private static void serializeMap(final String mapName, final Map } public static FullXmldbURI getFullURI(final BrokerPool pool, final XmldbURI uri) { - if (uri instanceof FullXmldbURI) { - return (FullXmldbURI) uri; + if (uri instanceof FullXmldbURI rI) { + return rI; } final StringBuilder accessor = new StringBuilder(XmldbURI.XMLDB_URI_PREFIX); @@ -1347,8 +1347,8 @@ public static synchronized void clear(final Database db) { final FullXmldbURI uri = entry.getKey(); if (uri.getInstanceName().equals(db.getId())) { final Configuration conf = entry.getValue(); - if (conf instanceof ConfigurationImpl) { - ((ConfigurationImpl) conf).configuredObjectReference = null; + if (conf instanceof ConfigurationImpl impl) { + impl.configuredObjectReference = null; } } hotConfigs.remove(uri); diff --git a/exist-core/src/main/java/org/exist/debugger/ExceptionTimeout.java b/exist-core/src/main/java/org/exist/debugger/ExceptionTimeout.java index 2c110a5d825..267d3158688 100644 --- a/exist-core/src/main/java/org/exist/debugger/ExceptionTimeout.java +++ b/exist-core/src/main/java/org/exist/debugger/ExceptionTimeout.java @@ -21,13 +21,16 @@ */ package org.exist.debugger; +import java.io.Serial; + /** * @author Dmitriy Shabanov * */ public class ExceptionTimeout extends Exception { - private static final long serialVersionUID = -5783619743744719741L; + @Serial + private static final long serialVersionUID = -5783619743744719741L; public ExceptionTimeout() { super(); diff --git a/exist-core/src/main/java/org/exist/dom/NodeListImpl.java b/exist-core/src/main/java/org/exist/dom/NodeListImpl.java index 4bcf9aa6644..ffbc7de96b8 100644 --- a/exist-core/src/main/java/org/exist/dom/NodeListImpl.java +++ b/exist-core/src/main/java/org/exist/dom/NodeListImpl.java @@ -24,10 +24,12 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import java.io.Serial; import java.util.ArrayList; public class NodeListImpl extends ArrayList implements NodeList { + @Serial private static final long serialVersionUID = 5505309345079983721L; public NodeListImpl() { diff --git a/exist-core/src/main/java/org/exist/dom/memtree/ElementImpl.java b/exist-core/src/main/java/org/exist/dom/memtree/ElementImpl.java index 514d4d9e0b9..02100e4261a 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/ElementImpl.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/ElementImpl.java @@ -715,11 +715,11 @@ public String getTextContent() throws DOMException { final StringBuilder result = new StringBuilder(); for(int i = 0; i < this.getChildCount(); i++) { final Node child = getChildNodes().item(i); - if(child instanceof Text) { + if(child instanceof Text text) { if(i > 0) { result.append(" "); } - result.append(((Text) child).getData()); + result.append(text.getData()); } } return result.toString(); @@ -746,9 +746,9 @@ public Node appendChild(final Node newChild) throws DOMException { "A Document Type Node may not be appended to an element"); } - if(newChild instanceof NodeImpl) { + if(newChild instanceof NodeImpl impl) { final int treeLevel = document.treeLevel[nodeNumber]; - final int newChildTreeLevel = document.treeLevel[((NodeImpl)newChild).nodeNumber]; + final int newChildTreeLevel = document.treeLevel[impl.nodeNumber]; if(newChildTreeLevel < treeLevel) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "The node to append is one of this node's ancestors"); diff --git a/exist-core/src/main/java/org/exist/dom/memtree/NodeImpl.java b/exist-core/src/main/java/org/exist/dom/memtree/NodeImpl.java index 47f03d4096b..92463ba41e5 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/NodeImpl.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/NodeImpl.java @@ -592,8 +592,8 @@ public void toSAX(final DBBroker broker, final ContentHandler handler, final Pro serializer.setProperties(properties); } - if (handler instanceof LexicalHandler) { - serializer.setSAXHandlers(handler, (LexicalHandler) handler); + if (handler instanceof LexicalHandler lexicalHandler) { + serializer.setSAXHandlers(handler, lexicalHandler); } else { serializer.setSAXHandlers(handler, null); } diff --git a/exist-core/src/main/java/org/exist/dom/persistent/DocumentImpl.java b/exist-core/src/main/java/org/exist/dom/persistent/DocumentImpl.java index b09099dbfb4..1529b92e744 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/DocumentImpl.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/DocumentImpl.java @@ -1442,8 +1442,8 @@ public void setChildCount(final int count) { @EnsureContainerLocked(mode=READ_LOCK) public boolean isSameNode(final Node other) { // This function is used by Saxon in some circumstances, and this partial implementation is required for proper Saxon operation. - if(other instanceof DocumentImpl) { - return this.docId == ((DocumentImpl) other).getDocId(); + if(other instanceof DocumentImpl impl) { + return this.docId == impl.getDocId(); } else { return false; } diff --git a/exist-core/src/main/java/org/exist/dom/persistent/ElementImpl.java b/exist-core/src/main/java/org/exist/dom/persistent/ElementImpl.java index c490a4dfaff..4cf5fd93107 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/ElementImpl.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/ElementImpl.java @@ -507,8 +507,8 @@ public Node appendChild(final Node newChild) throws DOMException { "A Document Type Node may not be appended to an element"); } - if(newChild instanceof IStoredNode) { - final NodeId newChildId = ((IStoredNode)newChild).getNodeId(); + if(newChild instanceof IStoredNode node) { + final NodeId newChildId = node.getNodeId(); if(newChildId != null && getNodeId().isDescendantOf(newChildId)) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "The node to append is one of this node's ancestors"); @@ -2041,8 +2041,8 @@ public boolean accept(final INodeIterator iterator, final NodeVisitor visitor) { public String lookupNamespaceURI(final String prefix) { for (Node pathNode = this; pathNode != null; pathNode = pathNode.getParentNode()) { - if (pathNode instanceof ElementImpl) { - final String namespaceForPrefix = ((ElementImpl)pathNode).getNamespaceForPrefix(prefix); + if (pathNode instanceof ElementImpl impl) { + final String namespaceForPrefix = impl.getNamespaceForPrefix(prefix); if (namespaceForPrefix != null) { return namespaceForPrefix; } diff --git a/exist-core/src/main/java/org/exist/dom/persistent/ExtArrayNodeSet.java b/exist-core/src/main/java/org/exist/dom/persistent/ExtArrayNodeSet.java index 29d2b5b94e1..32c38324f6f 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/ExtArrayNodeSet.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/ExtArrayNodeSet.java @@ -466,8 +466,8 @@ public boolean containsReference(final Item item) { public boolean contains(final Item item) { if (item instanceof Node) { @Nullable final Document doc; - if (item instanceof Document) { - doc = (Document) item; + if (item instanceof Document document) { + doc = document; } else { doc = ((Node) item).getOwnerDocument(); } @@ -477,8 +477,8 @@ public boolean contains(final Item item) { } final int docId; - if (doc instanceof DocumentImpl) { - docId = ((DocumentImpl) doc).getDocId(); + if (doc instanceof DocumentImpl impl) { + docId = impl.getDocId(); } else { docId = (int) ((org.exist.dom.memtree.DocumentImpl) doc).getDocId(); } diff --git a/exist-core/src/main/java/org/exist/dom/persistent/NewArrayNodeSet.java b/exist-core/src/main/java/org/exist/dom/persistent/NewArrayNodeSet.java index ed5f630028d..766eacd68dd 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/NewArrayNodeSet.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/NewArrayNodeSet.java @@ -1110,8 +1110,8 @@ public boolean containsReference(final Item item) { sort(); if (item instanceof Node) { @Nullable final Document doc; - if (item instanceof Document) { - doc = (Document) item; + if (item instanceof Document document) { + doc = document; } else { doc = ((Node) item).getOwnerDocument(); } @@ -1121,8 +1121,8 @@ public boolean containsReference(final Item item) { } final int docId; - if (doc instanceof DocumentImpl) { - docId = ((DocumentImpl) doc).getDocId(); + if (doc instanceof DocumentImpl impl) { + docId = impl.getDocId(); } else { docId = (int) ((org.exist.dom.memtree.DocumentImpl) doc).getDocId(); } @@ -1143,8 +1143,8 @@ public boolean contains(final Item item) { sort(); if (item instanceof Node) { @Nullable final Document doc; - if (item instanceof Document) { - doc = (Document) item; + if (item instanceof Document document) { + doc = document; } else { doc = ((Node) item).getOwnerDocument(); } @@ -1154,8 +1154,8 @@ public boolean contains(final Item item) { } final int docId; - if (doc instanceof DocumentImpl) { - docId = ((DocumentImpl) doc).getDocId(); + if (doc instanceof DocumentImpl impl) { + docId = impl.getDocId(); } else { docId = (int) ((org.exist.dom.memtree.DocumentImpl) doc).getDocId(); } diff --git a/exist-core/src/main/java/org/exist/dom/persistent/NodeProxy.java b/exist-core/src/main/java/org/exist/dom/persistent/NodeProxy.java index 22059466b09..3bb531a4528 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/NodeProxy.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/NodeProxy.java @@ -233,10 +233,10 @@ public NodeProxy(final NodeHandle n) { * @param n a NodeHandle value */ public NodeProxy(final Expression expression, final NodeHandle n) { - this((expression == null && n instanceof NodeProxy) ? ((NodeProxy) n).getExpression() : expression, n.getOwnerDocument(), n.getNodeId(), n.getNodeType(), n.getInternalAddress()); - if(n instanceof NodeProxy) { - this.match = ((NodeProxy) n).match; - this.context = ((NodeProxy) n).context; + this((expression == null && n instanceof NodeProxy np) ? np.getExpression() : expression, n.getOwnerDocument(), n.getNodeId(), n.getNodeType(), n.getInternalAddress()); + if(n instanceof NodeProxy proxy) { + this.match = proxy.match; + this.context = proxy.context; } } @@ -754,8 +754,8 @@ public void toSAX(final DBBroker broker, final ContentHandler handler, final Pro serializer.setProperties(properties); } - if (handler instanceof LexicalHandler) { - serializer.setSAXHandlers(handler, (LexicalHandler) handler); + if (handler instanceof LexicalHandler lexicalHandler) { + serializer.setSAXHandlers(handler, lexicalHandler); } else { serializer.setSAXHandlers(handler, null); } diff --git a/exist-core/src/main/java/org/exist/dom/persistent/StoredNode.java b/exist-core/src/main/java/org/exist/dom/persistent/StoredNode.java index e70641b2247..23907d188bc 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/StoredNode.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/StoredNode.java @@ -296,7 +296,7 @@ public Node getParentNode() { @Override public StoredNode getParentStoredNode() { final Node parent = getParentNode(); - return parent instanceof StoredNode ? (StoredNode) parent : null; + return parent instanceof StoredNode sn ? sn : null; } @Override @@ -544,8 +544,8 @@ public int compareTo(final StoredNode other) { @Override public boolean isSameNode(final Node other) { // This function is used by Saxon in some circumstances, and is required for proper Saxon operation. - if(other instanceof IStoredNode) { - return (this.nodeId.equals(((IStoredNode) other).getNodeId()) && + if(other instanceof IStoredNode node) { + return (this.nodeId.equals(node.getNodeId()) && this.ownerDocument.getDocId() == ((IStoredNode) other).getOwnerDocument().getDocId()); } else { return false; diff --git a/exist-core/src/main/java/org/exist/http/BadRequestException.java b/exist-core/src/main/java/org/exist/http/BadRequestException.java index c72898b7512..4aef267d4bc 100644 --- a/exist-core/src/main/java/org/exist/http/BadRequestException.java +++ b/exist-core/src/main/java/org/exist/http/BadRequestException.java @@ -21,9 +21,12 @@ */ package org.exist.http; +import java.io.Serial; + public class BadRequestException extends Exception { - private static final long serialVersionUID = 8663399057134424372L; + @Serial + private static final long serialVersionUID = 8663399057134424372L; public BadRequestException(String message) { super(message); diff --git a/exist-core/src/main/java/org/exist/http/Descriptor.java b/exist-core/src/main/java/org/exist/http/Descriptor.java index 35258774bc2..571aa558276 100644 --- a/exist-core/src/main/java/org/exist/http/Descriptor.java +++ b/exist-core/src/main/java/org/exist/http/Descriptor.java @@ -45,7 +45,6 @@ import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Date; @@ -141,7 +140,7 @@ private Descriptor() { //load attribue settings if ("true".equals(doc.getDocumentElement().getAttribute("request-replay-log"))) { - final Path logFile = Paths.get("request-replay-log.txt"); + final Path logFile = Path.of("request-replay-log.txt"); bufWriteReplayLog = Files.newBufferedWriter(logFile); final String attr = doc.getDocumentElement().getAttribute("filtered"); if (!attr.isEmpty()) { @@ -212,7 +211,7 @@ private void configureAllowSourceXQuery(Element allowsourcexqueries) { return; } path = path.replaceAll("\\$\\{WEBAPP_HOME\\}", - SingleInstanceConfiguration.getWebappHome().orElse(Paths.get(".")).toAbsolutePath().toString().replace('\\', '/')); + SingleInstanceConfiguration.getWebappHome().orElse(Path.of(".")).toAbsolutePath().toString().replace('\\', '/')); //store the path allowSourceList[i] = path; @@ -248,7 +247,7 @@ private void configureMaps(Element maps) { return; } path = path.replaceAll("\\$\\{WEBAPP_HOME\\}", - SingleInstanceConfiguration.getWebappHome().orElse(Paths.get(".")).toAbsolutePath().toString().replace('\\', '/')); + SingleInstanceConfiguration.getWebappHome().orElse(Path.of(".")).toAbsolutePath().toString().replace('\\', '/')); //must be a view to map to if (view.isEmpty()) { @@ -256,7 +255,7 @@ private void configureMaps(Element maps) { return; } view = view.replaceAll("\\$\\{WEBAPP_HOME\\}", - SingleInstanceConfiguration.getWebappHome().orElse(Paths.get(".")).toAbsolutePath().toString().replace('\\', '/')); + SingleInstanceConfiguration.getWebappHome().orElse(Path.of(".")).toAbsolutePath().toString().replace('\\', '/')); //store what to map from /* if(path != null) diff --git a/exist-core/src/main/java/org/exist/http/MethodNotAllowedException.java b/exist-core/src/main/java/org/exist/http/MethodNotAllowedException.java index e727600601b..6be13388b51 100644 --- a/exist-core/src/main/java/org/exist/http/MethodNotAllowedException.java +++ b/exist-core/src/main/java/org/exist/http/MethodNotAllowedException.java @@ -21,8 +21,11 @@ */ package org.exist.http; +import java.io.Serial; + public class MethodNotAllowedException extends Exception { + @Serial private static final long serialVersionUID = -8399138417913514619L; public MethodNotAllowedException(String message) { diff --git a/exist-core/src/main/java/org/exist/http/NotFoundException.java b/exist-core/src/main/java/org/exist/http/NotFoundException.java index c94e9e54074..fbe0a69936c 100644 --- a/exist-core/src/main/java/org/exist/http/NotFoundException.java +++ b/exist-core/src/main/java/org/exist/http/NotFoundException.java @@ -21,9 +21,12 @@ */ package org.exist.http; +import java.io.Serial; + public class NotFoundException extends Exception { - private static final long serialVersionUID = -8399138517913514619L; + @Serial + private static final long serialVersionUID = -8399138517913514619L; public NotFoundException(String message) { super(message); diff --git a/exist-core/src/main/java/org/exist/http/Response.java b/exist-core/src/main/java/org/exist/http/Response.java index 366f8bba33c..120dfc6dade 100644 --- a/exist-core/src/main/java/org/exist/http/Response.java +++ b/exist-core/src/main/java/org/exist/http/Response.java @@ -32,9 +32,11 @@ public class Response { private final static String stdHeaders = - "Allow: POST GET PUT DELETE\n" + - "Server: eXist\n" + - "Cache-control: no-cache\n"; + """ + Allow: POST GET PUT DELETE + Server: eXist + Cache-control: no-cache + """; private int code = HttpServletResponse.SC_OK; private String statusDesc = null; @@ -123,4 +125,4 @@ public void write(DataOutputStream os) throws IOException { os.flush(); os.close(); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/http/filter/GuestFilter.java b/exist-core/src/main/java/org/exist/http/filter/GuestFilter.java index a618eb04c3e..d69640e9976 100644 --- a/exist-core/src/main/java/org/exist/http/filter/GuestFilter.java +++ b/exist-core/src/main/java/org/exist/http/filter/GuestFilter.java @@ -55,8 +55,8 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo HttpServletRequest httpServletRequest; HttpServletResponse httpServletResponse; - if (servletRequest instanceof HttpServletRequest) { - httpServletRequest = (HttpServletRequest)servletRequest; + if (servletRequest instanceof HttpServletRequest request) { + httpServletRequest = request; httpServletResponse = (HttpServletResponse)servletResponse; LOG.info("HTTP Servlet Request confirmed"); } diff --git a/exist-core/src/main/java/org/exist/http/filter/PathFilter.java b/exist-core/src/main/java/org/exist/http/filter/PathFilter.java index a6f42f09d92..e8fcde78d0d 100644 --- a/exist-core/src/main/java/org/exist/http/filter/PathFilter.java +++ b/exist-core/src/main/java/org/exist/http/filter/PathFilter.java @@ -81,8 +81,8 @@ public void doFilter(ServletRequest servletRequest, ServletResponse servletRespo HttpServletRequest httpServletRequest; HttpServletResponse httpServletResponse; - if (servletRequest instanceof HttpServletRequest) { - httpServletRequest = (HttpServletRequest)servletRequest; + if (servletRequest instanceof HttpServletRequest request) { + httpServletRequest = request; httpServletResponse = (HttpServletResponse)servletResponse; } else { diff --git a/exist-core/src/main/java/org/exist/http/servlets/AbstractExistHttpServlet.java b/exist-core/src/main/java/org/exist/http/servlets/AbstractExistHttpServlet.java index b2a9dd0ca92..2987350316b 100644 --- a/exist-core/src/main/java/org/exist/http/servlets/AbstractExistHttpServlet.java +++ b/exist-core/src/main/java/org/exist/http/servlets/AbstractExistHttpServlet.java @@ -43,9 +43,9 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; +import java.io.Serial; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.security.Principal; import java.util.Optional; @@ -58,7 +58,8 @@ @MultipartConfig public abstract class AbstractExistHttpServlet extends HttpServlet { - private static final long serialVersionUID = 804071766041263220L; + @Serial + private static final long serialVersionUID = 804071766041263220L; public final static String DEFAULT_ENCODING = UTF_8.name(); @@ -107,17 +108,17 @@ private BrokerPool getOrCreateBrokerPool(final ServletConfig config) throws EXis final Optional dbHome = Optional.ofNullable(config.getInitParameter("basedir")) .map(baseDir -> Optional.ofNullable(config.getServletContext().getRealPath(baseDir)) - .map(rp -> Optional.of(Paths.get(rp))) + .map(rp -> Optional.of(Path.of(rp))) .orElse( Optional.ofNullable(config.getServletContext().getRealPath("/")) - .map(dir -> Paths.get(dir).resolve("WEB-INF").toAbsolutePath()) + .map(dir -> Path.of(dir).resolve("WEB-INF").toAbsolutePath()) ) ) - .orElse(Optional.ofNullable(config.getServletContext().getRealPath("/")).map(Paths::get)); + .orElse(Optional.ofNullable(config.getServletContext().getRealPath("/")).map(Path::of)); getLog().info("EXistServlet: exist.home={}", dbHome.map(Path::toString).orElse("null")); - final Path cf = dbHome.map(h -> h.resolve(confFile)).orElse(Paths.get(confFile)); + final Path cf = dbHome.map(h -> h.resolve(confFile)).orElse(Path.of(confFile)); getLog().info("Reading configuration from {}", cf.toAbsolutePath().toString()); if (!Files.isReadable(cf)) { throw new ServletException("Configuration file " + confFile + " not found or not readable"); @@ -243,8 +244,8 @@ protected Subject authenticate(HttpServletRequest request, HttpServletResponse r } } - if (principal instanceof Subject) { - return (Subject)principal; + if (principal instanceof Subject subject) { + return subject; } } @@ -319,4 +320,4 @@ protected BrokerPool getPool() { private void setPool(BrokerPool pool) { this.pool = pool; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/http/servlets/EXistServlet.java b/exist-core/src/main/java/org/exist/http/servlets/EXistServlet.java index 26d66e1a0a6..9359daafeb5 100644 --- a/exist-core/src/main/java/org/exist/http/servlets/EXistServlet.java +++ b/exist-core/src/main/java/org/exist/http/servlets/EXistServlet.java @@ -44,6 +44,7 @@ import jakarta.servlet.http.HttpServletResponse; import java.io.EOFException; import java.io.IOException; +import java.io.Serial; import java.net.URI; import java.net.URISyntaxException; import java.util.Optional; @@ -56,6 +57,7 @@ */ public class EXistServlet extends AbstractExistHttpServlet { + @Serial private static final long serialVersionUID = -3563999345725645647L; private final static Logger LOG = LogManager.getLogger(EXistServlet.class); private RESTServer srvREST; @@ -572,8 +574,8 @@ protected void doPost(final HttpServletRequest req, final HttpServletResponse re throw new ServletException("An unknown error occurred: " + e.getMessage(), e); } } finally { - if (request instanceof HttpServletRequestWrapper) { - ((HttpServletRequestWrapper) request).close(); + if (request instanceof HttpServletRequestWrapper wrapper) { + wrapper.close(); } } } diff --git a/exist-core/src/main/java/org/exist/http/servlets/HttpRequestWrapper.java b/exist-core/src/main/java/org/exist/http/servlets/HttpRequestWrapper.java index 1ff9b6a2ed2..50fe5150e32 100644 --- a/exist-core/src/main/java/org/exist/http/servlets/HttpRequestWrapper.java +++ b/exist-core/src/main/java/org/exist/http/servlets/HttpRequestWrapper.java @@ -187,9 +187,9 @@ private static void addParameter(final Map map, final String par if (original != null) { // Check if original value was already a List - if (original instanceof List) { + if (original instanceof List list1) { // Add value to existing List - ((List) original).add(value); + list1.add(value); } else { // Single value already detected, convert to List and add both items @@ -274,9 +274,9 @@ private boolean isQueryParameter(final String parameterName, @Nullable final Str return parameterValue == null; } - if (queryStringParameterValue instanceof List) { + if (queryStringParameterValue instanceof List list) { // Add value to existing List - return ((List) queryStringParameterValue).contains(parameterValue); + return list.contains(parameterValue); } else { if (parameterValue == null) { return false; @@ -341,14 +341,14 @@ private List getFileItem(final Object obj) { // Cast // Return first Part object if present for(final Object listObject : list) { - if (listObject instanceof Part && !isFormField(((Part) listObject))) { - partList.add((Part) listObject); + if (listObject instanceof Part part && !isFormField(part)) { + partList.add(part); } } - } else if(obj instanceof Part && !isFormField(((Part) obj))) { + } else if(obj instanceof Part part && !isFormField(part)) { // Cast and return - partList.add((Part) obj); + partList.add(part); } // object did not represent a List of Part's or Part. @@ -508,8 +508,8 @@ public String getParameter(final String name) { } // Return just a simple value - } else if (o instanceof String) { - return (String) o; + } else if (o instanceof String string) { + return string; } return null; diff --git a/exist-core/src/main/java/org/exist/http/servlets/RedirectorServlet.java b/exist-core/src/main/java/org/exist/http/servlets/RedirectorServlet.java index 85e4150b794..9fcd5ac0025 100644 --- a/exist-core/src/main/java/org/exist/http/servlets/RedirectorServlet.java +++ b/exist-core/src/main/java/org/exist/http/servlets/RedirectorServlet.java @@ -46,10 +46,10 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; +import java.io.Serial; import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import static java.nio.charset.StandardCharsets.UTF_8; @@ -107,6 +107,7 @@ @Deprecated public class RedirectorServlet extends AbstractExistHttpServlet { + @Serial private static final long serialVersionUID = 853971301553787943L; private static final Logger LOG = LogManager.getLogger(RedirectorServlet.class); @@ -159,7 +160,7 @@ protected void service(final HttpServletRequest req, final HttpServletResponse r } // Try to find the XQuery final String qpath = getServletContext().getRealPath(query); - final Path p = Paths.get(qpath); + final Path p = Path.of(qpath); if (!(Files.isReadable(p) && Files.isRegularFile(p))) { throw new ServletException("Cannot read XQuery source from " + p.toAbsolutePath()); } diff --git a/exist-core/src/main/java/org/exist/http/servlets/XQueryServlet.java b/exist-core/src/main/java/org/exist/http/servlets/XQueryServlet.java index fdda0dab5e4..7439884536d 100644 --- a/exist-core/src/main/java/org/exist/http/servlets/XQueryServlet.java +++ b/exist-core/src/main/java/org/exist/http/servlets/XQueryServlet.java @@ -52,11 +52,11 @@ import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; +import java.io.Serial; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import java.util.Properties; @@ -91,7 +91,8 @@ * @author Wolfgang Meier */ public class XQueryServlet extends AbstractExistHttpServlet { - + + @Serial private static final long serialVersionUID = 5266794852401553015L; private static final Logger LOG = LogManager.getLogger(XQueryServlet.class); @@ -180,8 +181,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse response) thro process(request, response); } finally { - if (request != null && request instanceof HttpServletRequestWrapper) { - ((HttpServletRequestWrapper)request).close(); + if (request != null && request instanceof HttpServletRequestWrapper wrapper) { + wrapper.close(); } } } @@ -215,8 +216,8 @@ protected void doPut(HttpServletRequest req, HttpServletResponse response) throw process(request, response); } finally { - if (request != null && request instanceof HttpServletRequestWrapper) { - ((HttpServletRequestWrapper)request).close(); + if (request != null && request instanceof HttpServletRequestWrapper wrapper) { + wrapper.close(); } } } @@ -327,9 +328,9 @@ protected void process(HttpServletRequest request, HttpServletResponse response) final Object urlAttrib = request.getAttribute(ATTR_XQUERY_URL); if (sourceAttrib != null) { String s; - if (sourceAttrib instanceof Item) + if (sourceAttrib instanceof Item item) try { - s = ((Item) sourceAttrib).getStringValue(); + s = item.getStringValue(); } catch (final XPathException e) { throw new ServletException("Failed to read XQuery source string from " + "request attribute '" + ATTR_XQUERY_SOURCE + "': " + e.getMessage(), e); @@ -354,7 +355,7 @@ protected void process(HttpServletRequest request, HttpServletResponse response) sendError(output, "Error", e.getMessage()); } } else { - final Path f = Paths.get(path); + final Path f = Path.of(path); if(!Files.isReadable(f)) { response.setStatus(HttpServletResponse.SC_NOT_FOUND); sendError(output, "Cannot read source file", path); @@ -388,9 +389,9 @@ protected void process(HttpServletRequest request, HttpServletResponse response) // System.out.println("path="+path); if(descriptor.allowSource(path)) { - if (source instanceof DBSource) { + if (source instanceof DBSource bSource) { try { - ((DBSource) source).validate(user, Permission.READ); + bSource.validate(user, Permission.READ); } catch (final PermissionDeniedException e) { if (getDefaultUser().equals(user)) { getAuthenticator().sendChallenge(request, response); @@ -569,9 +570,9 @@ private String getValue(Object obj) { if(obj == null) {return null;} - if(obj instanceof Sequence) + if(obj instanceof Sequence sequence) try { - return ((Sequence)obj).getStringValue(); + return sequence.getStringValue(); } catch (final XPathException e) { return null; } diff --git a/exist-core/src/main/java/org/exist/http/servlets/XSLTServlet.java b/exist-core/src/main/java/org/exist/http/servlets/XSLTServlet.java index 6ec1eacecc8..22eb685ee4e 100644 --- a/exist-core/src/main/java/org/exist/http/servlets/XSLTServlet.java +++ b/exist-core/src/main/java/org/exist/http/servlets/XSLTServlet.java @@ -59,7 +59,6 @@ import java.io.*; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Enumeration; import java.util.Optional; import java.util.Properties; @@ -74,6 +73,7 @@ */ public class XSLTServlet extends HttpServlet { + @Serial private static final long serialVersionUID = -7258405385386062151L; private final static String REQ_ATTRIBUTE_PREFIX = "xslt."; @@ -135,8 +135,8 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) } } - if (sourceObj instanceof Item) { - inputNode = (Item) sourceObj; + if (sourceObj instanceof Item item) { + inputNode = item; if (!Type.subTypeOf(inputNode.getType(), Type.NODE)) { throw new ServletException("Input for XSLT servlet is not a node. Read from attribute " + sourceAttrib); @@ -299,7 +299,7 @@ private Stylesheet stylesheet(String stylesheet, HttpServletRequest request, Htt if (stylesheet.indexOf(':') == Constants.STRING_NOT_FOUND) { // replace double slash stylesheet = stylesheet.replaceAll("//", "/"); - Path f = Paths.get(stylesheet).normalize(); + Path f = Path.of(stylesheet).normalize(); if (Files.isReadable(f)) { // Found file, get URI stylesheet = f.toUri().toASCIIString(); @@ -316,7 +316,7 @@ private Stylesheet stylesheet(String stylesheet, HttpServletRequest request, Htt return null; } - f = Paths.get(url); + f = Path.of(url); stylesheet = f.toUri().toASCIIString(); } else { @@ -350,7 +350,7 @@ private Path getCurrentDir(HttpServletRequest request) { path = getServletContext().getRealPath(path); } - final Path file = Paths.get(path).normalize(); + final Path file = Path.of(path).normalize(); if (Files.isDirectory(file)) { return file; } else { diff --git a/exist-core/src/main/java/org/exist/http/urlrewrite/RewriteConfig.java b/exist-core/src/main/java/org/exist/http/urlrewrite/RewriteConfig.java index 6303fd67940..8310d7350e3 100644 --- a/exist-core/src/main/java/org/exist/http/urlrewrite/RewriteConfig.java +++ b/exist-core/src/main/java/org/exist/http/urlrewrite/RewriteConfig.java @@ -54,7 +54,6 @@ import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Optional; @@ -141,9 +140,9 @@ public synchronized URLRewrite lookup(String path, final String serverName, fina * on the server name. If there is a condition on the server name and the names do not * match, then ignore this ControllerForward. */ - if (action instanceof ControllerForward) { + if (action instanceof ControllerForward forward) { if (serverName != null) { - final String controllerServerName = ((ControllerForward) action).getServerName(); + final String controllerServerName = forward.getServerName(); if (controllerServerName != null) { if (!serverName.equalsIgnoreCase(controllerServerName)) { continue; @@ -185,7 +184,7 @@ private void configure(final String controllerConfig) throws ServletException { } } else { try { - final Path d = Paths.get(urlRewrite.getConfig().getServletContext().getRealPath("/")).normalize(); + final Path d = Path.of(urlRewrite.getConfig().getServletContext().getRealPath("/")).normalize(); final Path configFile = d.resolve(controllerConfig); if (Files.isReadable(configFile)) { final Document doc = parseConfig(configFile); diff --git a/exist-core/src/main/java/org/exist/http/urlrewrite/XQueryURLRewrite.java b/exist-core/src/main/java/org/exist/http/urlrewrite/XQueryURLRewrite.java index e0cef4b13d6..ee8a1e19bd0 100644 --- a/exist-core/src/main/java/org/exist/http/urlrewrite/XQueryURLRewrite.java +++ b/exist-core/src/main/java/org/exist/http/urlrewrite/XQueryURLRewrite.java @@ -79,7 +79,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import java.util.Map.Entry; import java.util.regex.Matcher; @@ -577,7 +576,7 @@ private void configure() throws ServletException { } try { final Class driver = Class.forName(DRIVER); - final Database database = (Database) driver.newInstance(); + final Database database = (Database) driver.getDeclaredConstructor().newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); if (LOG.isDebugEnabled()) { @@ -835,7 +834,7 @@ LockedDocument findDbControllerXql(final DBBroker broker, final XmldbURI collect private SourceInfo findSourceFromFs(final String basePath, final String[] components) { final String realPath = config.getServletContext().getRealPath(basePath); - final Path baseDir = Paths.get(realPath); + final Path baseDir = Path.of(realPath); if (!Files.isDirectory(baseDir)) { LOG.warn("Base path for XQueryURLRewrite does not point to a directory"); return null; diff --git a/exist-core/src/main/java/org/exist/indexing/IndexManager.java b/exist-core/src/main/java/org/exist/indexing/IndexManager.java index ac12e426e57..786af20cd21 100644 --- a/exist-core/src/main/java/org/exist/indexing/IndexManager.java +++ b/exist-core/src/main/java/org/exist/indexing/IndexManager.java @@ -297,8 +297,8 @@ public void reopenIndexes() throws DatabaseConfigurationException { public void backupToArchive(final RawDataBackup backup) throws IOException { for (final Iterator i = iterator(); i.hasNext(); ) { final Index index = i.next(); - if (index instanceof RawBackupSupport) { - ((RawBackupSupport) index).backupToArchive(backup); + if (index instanceof RawBackupSupport support) { + support.backupToArchive(backup); } } } diff --git a/exist-core/src/main/java/org/exist/indexing/ReindexScope.java b/exist-core/src/main/java/org/exist/indexing/ReindexScope.java index 6169c400a30..ad8a5ea17a9 100644 --- a/exist-core/src/main/java/org/exist/indexing/ReindexScope.java +++ b/exist-core/src/main/java/org/exist/indexing/ReindexScope.java @@ -53,15 +53,11 @@ public static ReindexScope fromString(final String mode) { if (mode == null || mode.isEmpty()) { return ALL; } - switch (mode.toLowerCase()) { - case "all": - return ALL; - case "fulltext": - return FULLTEXT; - case "vector": - return VECTOR; - default: - return ALL; - } + return switch (mode.toLowerCase()) { + case "all" -> ALL; + case "fulltext" -> FULLTEXT; + case "vector" -> VECTOR; + default -> ALL; + }; } } diff --git a/exist-core/src/main/java/org/exist/jetty/JettyStart.java b/exist-core/src/main/java/org/exist/jetty/JettyStart.java index 3225fbab227..0b0c9baef6a 100644 --- a/exist-core/src/main/java/org/exist/jetty/JettyStart.java +++ b/exist-core/src/main/java/org/exist/jetty/JettyStart.java @@ -57,7 +57,6 @@ import java.net.*; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; @@ -153,9 +152,9 @@ public synchronized void run(final boolean standalone) { final Path jettyConfig; if (standalone) { - jettyConfig = Paths.get(jettyProperty).normalize().resolve("etc").resolve(Main.STANDALONE_ENABLED_JETTY_CONFIGS); + jettyConfig = Path.of(jettyProperty).normalize().resolve("etc").resolve(Main.STANDALONE_ENABLED_JETTY_CONFIGS); } else { - jettyConfig = Paths.get(jettyProperty).normalize().resolve("etc").resolve(Main.STANDARD_ENABLED_JETTY_CONFIGS); + jettyConfig = Path.of(jettyProperty).normalize().resolve("etc").resolve(Main.STANDARD_ENABLED_JETTY_CONFIGS); } run(new String[] { jettyConfig.toAbsolutePath().toString() }, null); } @@ -166,7 +165,7 @@ public synchronized void run(final String[] args, final Observer observer) { return; } - Path jettyConfig = Paths.get(args[0]).normalize(); + Path jettyConfig = Path.of(args[0]).normalize(); boolean configFromClasspath = false; if (Files.notExists(jettyConfig)) { logger.warn("Configuration file: {} does not exist!", jettyConfig.toAbsolutePath().toString()); @@ -177,7 +176,7 @@ public synchronized void run(final String[] args, final Observer observer) { final URL jettyConfigUrl = getClass().getResource("etc/" + jettyConfigFileName); if (jettyConfigUrl != null) { try { - jettyConfig = Paths.get(jettyConfigUrl.toURI()).normalize(); + jettyConfig = Path.of(jettyConfigUrl.toURI()).normalize(); configFromClasspath = true; } catch (final URISyntaxException e) { logger.error("Unable to retrieve configuration file from classpath: {}", e.getMessage(), e); @@ -273,7 +272,7 @@ public synchronized void run(final String[] args, final Observer observer) { // start Jetty final Optional maybeServer = startJetty(configuredObjects); - if(!maybeServer.isPresent()) { + if(maybeServer.isEmpty()) { logger.error("Unable to find a server to start in jetty configurations"); throw new IllegalStateException(); } diff --git a/exist-core/src/main/java/org/exist/jetty/ServerShutdown.java b/exist-core/src/main/java/org/exist/jetty/ServerShutdown.java index 14055204373..80cf1554002 100644 --- a/exist-core/src/main/java/org/exist/jetty/ServerShutdown.java +++ b/exist-core/src/main/java/org/exist/jetty/ServerShutdown.java @@ -107,7 +107,7 @@ private static void process(final ParsedArguments arguments) { // initialize database drivers final Class cl = Class.forName("org.exist.xmldb.DatabaseImpl"); // create the default database - final Database database = (Database) cl.newInstance(); + final Database database = (Database) cl.getDeclaredConstructor().newInstance(); DatabaseManager.registerDatabase(database); if (!uri.endsWith(XmldbURI.ROOT_COLLECTION)) { uri = uri + XmldbURI.ROOT_COLLECTION; diff --git a/exist-core/src/main/java/org/exist/launcher/ConfigurationDialog.java b/exist-core/src/main/java/org/exist/launcher/ConfigurationDialog.java index bd124790041..fa9ff231b91 100644 --- a/exist-core/src/main/java/org/exist/launcher/ConfigurationDialog.java +++ b/exist-core/src/main/java/org/exist/launcher/ConfigurationDialog.java @@ -25,7 +25,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Map; import java.util.Optional; import java.util.Properties; @@ -131,7 +130,7 @@ public void open(boolean firstStart) { lbStartupWarn.setVisible(true); if (SystemUtils.IS_OS_MAC_OSX) { - Path dir = Paths.get(System.getProperty("user.home")).resolve("Library").resolve("Application Support").resolve("org.exist"); + Path dir = Path.of(System.getProperty("user.home")).resolve("Library").resolve("Application Support").resolve("org.exist"); dataDir.setText(dir.toAbsolutePath().toString()); } } else { @@ -479,7 +478,7 @@ private boolean checkDataDir() { if (!dataDirChanged) return true; - Path dir = Paths.get(dataDir.getText()); + Path dir = Path.of(dataDir.getText()); if (Files.exists(dir)) { try (final Stream fileStream = Files.list(dir).filter(p -> FileUtils.fileName(p).endsWith(".dbx"))) { @@ -603,7 +602,7 @@ private void jettyConfigChanged(javax.swing.event.ChangeEvent evt) { private void btnSelectDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSelectDirActionPerformed final Optional currentDir = Optional.ofNullable(dataDir.getText()) - .map(d -> Optional.of(Paths.get(d))) + .map(d -> Optional.of(Path.of(d))) .filter(md -> md.map(Files::exists).orElse(false)) .orElse(ConfigurationHelper.getExistHome()); diff --git a/exist-core/src/main/java/org/exist/launcher/Launcher.java b/exist-core/src/main/java/org/exist/launcher/Launcher.java index 3c858432655..fe523449d75 100644 --- a/exist-core/src/main/java/org/exist/launcher/Launcher.java +++ b/exist-core/src/main/java/org/exist/launcher/Launcher.java @@ -52,7 +52,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import java.util.concurrent.locks.ReentrantLock; @@ -135,7 +134,7 @@ public static void main(final String[] args) { captureConsole(); // try and figure out exist home dir - final Optional existHomeDir = getFromSysPropOrEnv(Main.PROP_EXIST_HOME, Main.ENV_EXIST_HOME).map(Paths::get); + final Optional existHomeDir = getFromSysPropOrEnv(Main.PROP_EXIST_HOME, Main.ENV_EXIST_HOME).map(Path::of); this.jettyConfig = getJettyConfig(existHomeDir); @@ -184,7 +183,7 @@ private void startJetty() { final Runnable runnable = () -> { serviceLock.lock(); try { - if (!jetty.isPresent()) { + if (jetty.isEmpty()) { jetty = Optional.of(new JettyStart()); final String[] args; @@ -635,9 +634,13 @@ void signalStarted() { SwingUtilities.invokeLater(() -> { final int installServiceResult = JOptionPane.showOptionDialog( splash, - "It is recommended to run eXist-db as a service on " + - "Windows.\nNot doing so may lead to data loss if you shutdown the computer before " + - "eXist-db.\n\nWould you like to install the service?", + """ + It is recommended to run eXist-db as a service on \ + Windows. + Not doing so may lead to data loss if you shutdown the computer before \ + eXist-db. + + Would you like to install the service?""", "Install as Service?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, @@ -731,9 +734,9 @@ public void update(final Observable observable, final Object o) { private Path getJettyConfig(final Optional existHomeDir) { - Optional existJettyConfigFile = getFromSysPropOrEnv(Main.PROP_EXIST_JETTY_CONFIG, Main.ENV_EXIST_JETTY_CONFIG).map(Paths::get); - if (!existJettyConfigFile.isPresent()) { - final Optional jettyHomeDir = getFromSysPropOrEnv(Main.PROP_JETTY_HOME, Main.ENV_JETTY_HOME).map(Paths::get); + Optional existJettyConfigFile = getFromSysPropOrEnv(Main.PROP_EXIST_JETTY_CONFIG, Main.ENV_EXIST_JETTY_CONFIG).map(Path::of); + if (existJettyConfigFile.isEmpty()) { + final Optional jettyHomeDir = getFromSysPropOrEnv(Main.PROP_JETTY_HOME, Main.ENV_JETTY_HOME).map(Path::of); if (jettyHomeDir.isPresent() && Files.exists(jettyHomeDir.get().resolve(Main.CONFIG_DIR_NAME))) { existJettyConfigFile = jettyHomeDir.map(f -> f.resolve(Main.CONFIG_DIR_NAME).resolve(Main.STANDARD_ENABLED_JETTY_CONFIGS)); @@ -743,7 +746,7 @@ private Path getJettyConfig(final Optional existHomeDir) { existJettyConfigFile = existHomeDir.map(f -> f.resolve(Main.CONFIG_DIR_NAME).resolve(Main.STANDARD_ENABLED_JETTY_CONFIGS)); } - if (!existJettyConfigFile.isPresent()) { + if (existJettyConfigFile.isEmpty()) { showMessageAndExit("Error Occurred", "ERROR: jetty config file could not be found! Make sure to set exist.jetty.config or EXIST_JETTY_CONFIG.", true); System.exit(SystemExitCodes.CATCH_ALL_GENERAL_ERROR_EXIT_CODE); } @@ -754,7 +757,7 @@ private Path getJettyConfig(final Optional existHomeDir) { private Optional getFromSysPropOrEnv(final String sysPropName, final String envVarName) { Optional value = Optional.ofNullable(System.getProperty(sysPropName)); - if (!value.isPresent()) { + if (value.isEmpty()) { value = Optional.ofNullable(System.getenv().get(envVarName)); // if we managed to detect from environment, store it in a system property value.ifPresent(s -> System.setProperty(sysPropName, s)); diff --git a/exist-core/src/main/java/org/exist/launcher/LauncherWrapper.java b/exist-core/src/main/java/org/exist/launcher/LauncherWrapper.java index c84c6eefec4..ed412edcd85 100644 --- a/exist-core/src/main/java/org/exist/launcher/LauncherWrapper.java +++ b/exist-core/src/main/java/org/exist/launcher/LauncherWrapper.java @@ -35,7 +35,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import static org.exist.launcher.ConfigurationUtility.*; @@ -148,7 +147,7 @@ private void run(final List args) throws IOException { final ProcessBuilder pb = new ProcessBuilder(args); final Optional home = ConfigurationHelper.getExistHome(); - pb.directory(home.orElse(Paths.get(".")).toFile()); + pb.directory(home.orElse(Path.of(".")).toFile()); pb.redirectErrorStream(true); pb.inheritIO(); @@ -159,16 +158,16 @@ private void run(final List args) throws IOException { protected String getJavaCmd() { final File javaHome = new File(System.getProperty("java.home")); if (OS.startsWith("windows")) { - Path javaBin = Paths.get(javaHome.getAbsolutePath(), "bin", "javaw.exe"); + Path javaBin = Path.of(javaHome.getAbsolutePath(), "bin", "javaw.exe"); if (Files.isExecutable(javaBin)) { return '"' + javaBin.toString() + '"'; } - javaBin = Paths.get(javaHome.getAbsolutePath(), "bin", "java.exe"); + javaBin = Path.of(javaHome.getAbsolutePath(), "bin", "java.exe"); if (Files.isExecutable(javaBin)) { return '"' + javaBin.toString() + '"'; } } else { - Path javaBin = Paths.get(javaHome.getAbsolutePath(), "bin", "java"); + Path javaBin = Path.of(javaHome.getAbsolutePath(), "bin", "java"); if (Files.isExecutable(javaBin)) { return javaBin.toString(); } diff --git a/exist-core/src/main/java/org/exist/launcher/SplashScreen.java b/exist-core/src/main/java/org/exist/launcher/SplashScreen.java index 08689214d79..e58fec6783f 100644 --- a/exist-core/src/main/java/org/exist/launcher/SplashScreen.java +++ b/exist-core/src/main/java/org/exist/launcher/SplashScreen.java @@ -27,6 +27,7 @@ import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; +import java.io.Serial; import java.net.URL; import java.util.Observable; import java.util.Observer; @@ -40,6 +41,7 @@ */ public class SplashScreen extends JFrame implements Observer, Comparable { + @Serial private static final long serialVersionUID = -8449133653386075548L; private JLabel statusLabel; diff --git a/exist-core/src/main/java/org/exist/launcher/WindowsServiceManager.java b/exist-core/src/main/java/org/exist/launcher/WindowsServiceManager.java index a21e36b418e..0ba3a6a50b0 100644 --- a/exist-core/src/main/java/org/exist/launcher/WindowsServiceManager.java +++ b/exist-core/src/main/java/org/exist/launcher/WindowsServiceManager.java @@ -36,7 +36,6 @@ import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -80,7 +79,7 @@ private enum WindowsServiceState { .flatMap(exe -> Files.isExecutable(exe) ? Right(exe) : Left(new ServiceManagerException("Procrun is not executable at: " + exe))) ); - this.existHome = ConfigurationHelper.getExistHome().orElse(Paths.get(".")); + this.existHome = ConfigurationHelper.getExistHome().orElse(Path.of(".")); } @Override @@ -287,7 +286,7 @@ public void showNativeServiceManagementConsole() throws UnsupportedOperationExce * @return Path to jvm.dll or empty Optional */ private Optional findJvm() { - final Path javaHome = Paths.get(System.getProperty("java.home")).toAbsolutePath(); + final Path javaHome = Path.of(System.getProperty("java.home")).toAbsolutePath(); Path jvm = javaHome.resolve("bin").resolve("client").resolve("jvm.dll"); if (Files.exists(jvm)) { return Optional.of(jvm.toString()); diff --git a/exist-core/src/main/java/org/exist/management/client/JMXClient.java b/exist-core/src/main/java/org/exist/management/client/JMXClient.java index 9b376688b1f..c5711800685 100755 --- a/exist-core/src/main/java/org/exist/management/client/JMXClient.java +++ b/exist-core/src/main/java/org/exist/management/client/JMXClient.java @@ -79,9 +79,9 @@ public void memoryStats() { final CompositeData composite = (CompositeData) connection.getAttribute(name, "HeapMemoryUsage"); if (composite != null) { echo("\nMEMORY:"); - echo(String.format("Current heap: %,12d k Committed memory: %,12d k", + echo("Current heap: %,12d k Committed memory: %,12d k".formatted( ((Long)composite.get("used")) / 1024, ((Long)composite.get("committed")) / 1024)); - echo(String.format("Max memory: %,12d k", ((Long)composite.get("max")) / 1024)); + echo("Max memory: %,12d k".formatted(((Long)composite.get("max")) / 1024)); } } catch (final Exception e) { error(e); @@ -93,17 +93,17 @@ public void instanceStats() { echo("\nINSTANCE:"); final ObjectName name = new ObjectName("org.exist.management." + instance + ":type=Database"); final Long memReserved = (Long) connection.getAttribute(name, "ReservedMem"); - echo(String.format("%25s: %10d k", "Reserved memory", memReserved / 1024)); + echo("%25s: %10d k".formatted("Reserved memory", memReserved / 1024)); final Long memCache = (Long) connection.getAttribute(name, "CacheMem"); - echo(String.format("%25s: %10d k", "Cache memory", memCache / 1024)); + echo("%25s: %10d k".formatted("Cache memory", memCache / 1024)); final Long memCollCache = (Long) connection.getAttribute(name, "CollectionCacheMem"); - echo(String.format("%25s: %10d k", "Collection cache memory", memCollCache / 1024)); + echo("%25s: %10d k".formatted("Collection cache memory", memCollCache / 1024)); final String cols[] = { "MaxBrokers", "AvailableBrokers", "ActiveBrokers" }; - echo(String.format("\n%17s %17s %17s", cols[0], cols[1], cols[2])); + echo("\n%17s %17s %17s".formatted(cols[0], cols[1], cols[2])); final AttributeList attrs = connection.getAttributes(name, cols); final Object values[] = getValues(attrs); - echo(String.format("%17d %17d %17d", values[0], values[1], values[2])); + echo("%17d %17d %17d".formatted(values[0], values[1], values[2])); final TabularData table = (TabularData) connection.getAttribute(name, "ActiveBrokersMap"); if (!table.isEmpty()) { @@ -112,7 +112,7 @@ public void instanceStats() { for (Object o : table.values()) { final CompositeData data = (CompositeData) o; - echo(String.format("\t%20s: %3d", data.get("owner"), data.get("referenceCount"))); + echo("\t%20s: %3d".formatted(data.get("owner"), data.get("referenceCount"))); } } catch (final Exception e) { error(e); @@ -125,16 +125,16 @@ public void cacheStats() { String cols[] = { "MaxTotal", "CurrentSize" }; AttributeList attrs = connection.getAttributes(name, cols); Object values[] = getValues(attrs); - echo(String.format("\nCACHE [%8d pages max. / %8d pages allocated]", values[0], values[1])); + echo("\nCACHE [%8d pages max. / %8d pages allocated]".formatted(values[0], values[1])); final Set beans = connection.queryNames(new ObjectName("org.exist.management." + instance + ":type=CacheManager.Cache,*"), null); cols = new String[] {"Type", "FileName", "Size", "Used", "Hits", "Fails"}; - echo(String.format("%10s %20s %10s %10s %10s %10s", cols[0], cols[1], cols[2], cols[3], cols[4], cols[5])); + echo("%10s %20s %10s %10s %10s %10s".formatted(cols[0], cols[1], cols[2], cols[3], cols[4], cols[5])); for (ObjectName bean : beans) { name = bean; attrs = connection.getAttributes(name, cols); values = getValues(attrs); - echo(String.format("%10s %20s %,10d %,10d %,10d %,10d", values[0], values[1], values[2], values[3], values[4], values[5])); + echo("%10s %20s %,10d %,10d %,10d %,10d".formatted(values[0], values[1], values[2], values[3], values[4], values[5])); } echo(""); @@ -142,8 +142,8 @@ public void cacheStats() { cols = new String[] { "MaxTotal", "CurrentSize" }; attrs = connection.getAttributes(name, cols); values = getValues(attrs); - echo(String.format("Collection Cache: %10d k max / %10d k allocated", - ((Long)values[0] / 1024), ((Long)values[1] / 1024))); + echo("Collection Cache: %10d k max / %10d k allocated".formatted( + ((Long)values[0] / 1024), ((Long)values[1] / 1024))); } catch (final Exception e) { error(e); } @@ -157,17 +157,17 @@ public void lockTable() { for (Object o : table.values()) { final CompositeData data = (CompositeData) o; echo("Thread " + data.get("waitingThread")); - echo(String.format("%20s: %s", "Lock type", data.get("lockType"))); - echo(String.format("%20s: %s", "Lock mode", data.get("lockMode"))); - echo(String.format("%20s: %s", "Lock id", data.get("id"))); - echo(String.format("%20s: %s", "Held by", Arrays.toString((String[]) data.get("owner")))); + echo("%20s: %s".formatted("Lock type", data.get("lockType"))); + echo("%20s: %s".formatted("Lock mode", data.get("lockMode"))); + echo("%20s: %s".formatted("Lock id", data.get("id"))); + echo("%20s: %s".formatted("Held by", Arrays.toString((String[])data.get("owner")))); final String[] readers = (String[]) data.get("waitingForRead"); if (readers.length > 0) { - echo(String.format("%20s: %s", "Wait for read", Arrays.toString(readers))); + echo("%20s: %s".formatted("Wait for read", Arrays.toString(readers))); } final String[] writers = (String[]) data.get("waitingForWrite"); if (writers.length > 0) { - echo(String.format("%20s: %s", "Wait for write", Arrays.toString(writers))); + echo("%20s: %s".formatted("Wait for write", Arrays.toString(writers))); } } } catch (final MBeanException | AttributeNotFoundException | InstanceNotFoundException | ReflectionException | IOException | MalformedObjectNameException e) { @@ -183,18 +183,18 @@ public void sanityReport() { final String status = (String) connection.getAttribute(name, "Status"); final Date lastCheckStart = (Date) connection.getAttribute(name, "LastCheckStart"); final Date lastCheckEnd = (Date) connection.getAttribute(name, "LastCheckEnd"); - echo(String.format("%22s: %s", "Status", status)); - echo(String.format("%22s: %s", "Last check start", lastCheckStart)); - echo(String.format("%22s: %s", "Last check end", lastCheckEnd)); + echo("%22s: %s".formatted("Status", status)); + echo("%22s: %s".formatted("Last check start", lastCheckStart)); + echo("%22s: %s".formatted("Last check end", lastCheckEnd)); if (lastCheckStart != null && lastCheckEnd != null) - {echo(String.format("%22s: %dms", "Check took", (lastCheckEnd.getTime() - lastCheckStart.getTime())));} + {echo("%22s: %dms".formatted("Check took", (lastCheckEnd.getTime() - lastCheckStart.getTime())));} final TabularData table = (TabularData) connection.getAttribute(name, "Errors"); for (Object o : table.values()) { final CompositeData data = (CompositeData) o; - echo(String.format("%22s: %s", "Error code", data.get("errcode"))); - echo(String.format("%22s: %s", "Description", data.get("description"))); + echo("%22s: %s".formatted("Error code", data.get("errcode"))); + echo("%22s: %s".formatted("Description", data.get("description"))); } } catch (final MBeanException | AttributeNotFoundException | InstanceNotFoundException | ReflectionException | IOException | MalformedObjectNameException e) { error(e); @@ -210,10 +210,10 @@ public void jobReport() { TabularData table = (TabularData) connection.getAttribute(name, "RunningJobs"); String[] cols = new String[] { "ID", "Action", "Info" }; - echo(String.format("%15s %30s %30s", cols[0], cols[1], cols[2])); + echo("%15s %30s %30s".formatted(cols[0], cols[1], cols[2])); for (Object value : table.values()) { final CompositeData data = (CompositeData) value; - echo(String.format("%15s %30s %30s", data.get("id"), data.get("action"), data.get("info"))); + echo("%15s %30s %30s".formatted(data.get("id"), data.get("action"), data.get("info"))); } echo("\nRunning queries"); @@ -221,10 +221,10 @@ public void jobReport() { table = (TabularData) connection.getAttribute(name, "RunningQueries"); cols = new String[] { "ID", "Type", "Key", "Terminating" }; - echo(String.format("%10s %10s %30s %s", cols[0], cols[1], cols[2], cols[3])); + echo("%10s %10s %30s %s".formatted(cols[0], cols[1], cols[2], cols[3])); for (Object o : table.values()) { final CompositeData data = (CompositeData) o; - echo(String.format("%15s %15s %30s %6s", data.get("id"), data.get("sourceType"), data.get("sourceKey"), data.get("terminating"))); + echo("%15s %15s %30s %6s".formatted(data.get("id"), data.get("sourceType"), data.get("sourceKey"), data.get("terminating"))); } } catch (final MBeanException | AttributeNotFoundException | InstanceNotFoundException | ReflectionException | IOException | MalformedObjectNameException e) { error(e); diff --git a/exist-core/src/main/java/org/exist/management/client/JMXServlet.java b/exist-core/src/main/java/org/exist/management/client/JMXServlet.java index e4140ea41d9..2fc447675c3 100644 --- a/exist-core/src/main/java/org/exist/management/client/JMXServlet.java +++ b/exist-core/src/main/java/org/exist/management/client/JMXServlet.java @@ -30,7 +30,6 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import java.util.function.Predicate; import javax.management.*; @@ -133,7 +132,7 @@ private void writeXmlData(final HttpServletRequest request, final HttpServletRes final long responseTime = client.ping(BrokerPool.DEFAULT_INSTANCE_NAME, timeout); if (responseTime == JMXtoXML.PING_TIMEOUT) { - root = client.generateXMLReport(String.format("no response on ping after %sms", timeout), + root = client.generateXMLReport("no response on ping after %sms".formatted(timeout), new String[]{"sanity", "locking", "processes", "instances", "memory"}); } else { root = client.generateXMLReport(null, new String[]{"sanity"}); @@ -195,9 +194,9 @@ public void init(final ServletConfig config) throws ServletException { // Get directory for token file final String jmxDataDir = client.getDataDir(); if (jmxDataDir == null) { - dataDir = Paths.get(config.getServletContext().getRealPath(WEBINF_DATA_DIR)).normalize(); + dataDir = Path.of(config.getServletContext().getRealPath(WEBINF_DATA_DIR)).normalize(); } else { - dataDir = Paths.get(jmxDataDir).normalize(); + dataDir = Path.of(jmxDataDir).normalize(); } if (!Files.isDirectory(dataDir) || !Files.isWritable(dataDir)) { LOG.error("Cannot access directory {}", WEBINF_DATA_DIR); diff --git a/exist-core/src/main/java/org/exist/management/impl/BinaryValues.java b/exist-core/src/main/java/org/exist/management/impl/BinaryValues.java index c3525265693..58fbac014a6 100644 --- a/exist-core/src/main/java/org/exist/management/impl/BinaryValues.java +++ b/exist-core/src/main/java/org/exist/management/impl/BinaryValues.java @@ -71,14 +71,12 @@ public List getCacheInstances() { final BinaryInputStreamCacheInfo result; final FilterInputStreamCache cache = cacheInstance.getCache(); - if (cache instanceof FileFilterInputStreamCache) { - result = new BinaryInputStreamCacheInfo(CacheType.FILE, cacheInstance.getRegistered(), - Optional.of(((FileFilterInputStreamCache) cache).getFilePath()), cache.getLength()); - } else if (cache instanceof MemoryMappedFileFilterInputStreamCache) { - result = new BinaryInputStreamCacheInfo(CacheType.MEMORY_MAPPED_FILE, cacheInstance.getRegistered(), - Optional.of(((MemoryMappedFileFilterInputStreamCache) cache).getFilePath()), cache.getLength()); - } else { - result = new BinaryInputStreamCacheInfo(CacheType.MEMORY, cacheInstance.getRegistered(), + switch (cache) { + case FileFilterInputStreamCache streamCache1 -> result = new BinaryInputStreamCacheInfo(CacheType.FILE, cacheInstance.getRegistered(), + Optional.of(streamCache1.getFilePath()), cache.getLength()); + case MemoryMappedFileFilterInputStreamCache streamCache -> result = new BinaryInputStreamCacheInfo(CacheType.MEMORY_MAPPED_FILE, cacheInstance.getRegistered(), + Optional.of(streamCache.getFilePath()), cache.getLength()); + default -> result = new BinaryInputStreamCacheInfo(CacheType.MEMORY, cacheInstance.getRegistered(), Optional.empty(), cache.getLength()); } diff --git a/exist-core/src/main/java/org/exist/repo/AutoDeploymentTrigger.java b/exist-core/src/main/java/org/exist/repo/AutoDeploymentTrigger.java index 9dc3cf868b6..25d919ce885 100644 --- a/exist-core/src/main/java/org/exist/repo/AutoDeploymentTrigger.java +++ b/exist-core/src/main/java/org/exist/repo/AutoDeploymentTrigger.java @@ -34,7 +34,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Comparator; import java.util.HashMap; import java.util.List; @@ -70,11 +69,11 @@ public void execute(final DBBroker sysBroker, final Txn transaction, final Map homeDir = sysBroker.getConfiguration().getExistHome(); autodeployDir = FileUtils.resolve(homeDir, AUTODEPLOY_DIRECTORY); diff --git a/exist-core/src/main/java/org/exist/repo/ClasspathHelper.java b/exist-core/src/main/java/org/exist/repo/ClasspathHelper.java index 1a1d016afe6..956bb8de32c 100644 --- a/exist-core/src/main/java/org/exist/repo/ClasspathHelper.java +++ b/exist-core/src/main/java/org/exist/repo/ClasspathHelper.java @@ -39,7 +39,6 @@ import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Collection; import java.util.Optional; import java.util.Set; @@ -170,7 +169,7 @@ private static void scanPackageDir(Package pkg, Classpath classpath, Path module try (final BufferedReader reader = Files.newBufferedReader(cp)) { String line; while ((line = reader.readLine()) != null) { - Path p = Paths.get(line); + Path p = Path.of(line); if (!p.isAbsolute()) { final FileSystemStorage.FileSystemResolver res = (FileSystemStorage.FileSystemResolver) pkg.getResolver(); p = res.resolveComponentAsFile(line); diff --git a/exist-core/src/main/java/org/exist/repo/Deployment.java b/exist-core/src/main/java/org/exist/repo/Deployment.java index c4e48b2414e..15c0ac43f71 100644 --- a/exist-core/src/main/java/org/exist/repo/Deployment.java +++ b/exist-core/src/main/java/org/exist/repo/Deployment.java @@ -275,7 +275,7 @@ private void checkProcessorVersion(final PackageLoader.Version version) throws P public Optional undeploy(final DBBroker broker, final Txn transaction, final String pkgName, final Optional repo) throws PackageException { final Optional maybePackageDir = getPackageDir(pkgName, repo); - if (!maybePackageDir.isPresent()) { + if (maybePackageDir.isEmpty()) { // fails silently if package dir is not found? return Optional.empty(); } @@ -319,7 +319,7 @@ public Optional undeploy(final DBBroker broker, final Txn transaction, f public Optional deploy(final DBBroker broker, final Txn transaction, final String pkgName, final Optional repo, final String userTarget) throws PackageException, IOException { final Optional maybePackageDir = getPackageDir(pkgName, repo); - if (!maybePackageDir.isPresent()) { + if (maybePackageDir.isEmpty()) { throw new PackageException("Package not found: " + pkgName); } diff --git a/exist-core/src/main/java/org/exist/repo/ExistRepository.java b/exist-core/src/main/java/org/exist/repo/ExistRepository.java index 6c6ec6fee9b..b4de0ef4d74 100644 --- a/exist-core/src/main/java/org/exist/repo/ExistRepository.java +++ b/exist-core/src/main/java/org/exist/repo/ExistRepository.java @@ -57,7 +57,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Collections; @@ -89,7 +88,7 @@ public class ExistRepository extends Observable implements BrokerPoolService { @Override public void configure(final Configuration configuration) throws BrokerPoolServiceException { final Path dataDir = Optional.ofNullable((Path) configuration.getProperty(BrokerPool.PROPERTY_DATA_DIR)) - .orElse(Paths.get(NativeBroker.DEFAULT_DATA_DIR)); + .orElse(Path.of(NativeBroker.DEFAULT_DATA_DIR)); this.expathDir = dataDir.resolve(EXPATH_REPO_DIR_NAME); } @@ -256,7 +255,7 @@ public Path resolveXQueryModule(final String namespace) throws XPathException { src = pkg.resolve(namespace, URISpace.XQUERY); if (src != null) { sysid = src.getSystemId(); - return Paths.get(new URI(sysid)); + return Path.of(new URI(sysid)); } } catch (final URISyntaxException ex) { throw new XPathException((Expression) null, ErrorCodes.XQST0046, "Error parsing the URI of the query library: " + sysid, ex); @@ -297,15 +296,15 @@ public Path resolveXQueryModule(final String namespace) throws XPathException { // 1. attempt to locate it within a library XmldbURI xqueryDbPath = XmldbURI.create("xmldb:exist:///db/system/repo/" + relXQueryPath); @Nullable Document doc = broker.getXMLResource(xqueryDbPath); - if (doc != null && doc instanceof BinaryDocument) { - return new DBSource(broker.getBrokerPool(), (BinaryDocument) doc, false); + if (doc != null && doc instanceof BinaryDocument document) { + return new DBSource(broker.getBrokerPool(), document, false); } // 2. attempt to locate it within an app xqueryDbPath = XmldbURI.create("xmldb:exist:///db/apps/" + relXQueryPath); doc = broker.getXMLResource(xqueryDbPath); - if (doc != null && doc instanceof BinaryDocument) { - return new DBSource(broker.getBrokerPool(), (BinaryDocument) doc, false); + if (doc != null && doc instanceof BinaryDocument document) { + return new DBSource(broker.getBrokerPool(), document, false); } return null; @@ -336,7 +335,7 @@ public List getJavaModules() { public static Path getRepositoryDir(final Configuration config) throws IOException { final Path dataDir = Optional.ofNullable((Path) config.getProperty(BrokerPool.PROPERTY_DATA_DIR)) - .orElse(Paths.get(NativeBroker.DEFAULT_DATA_DIR)); + .orElse(Path.of(NativeBroker.DEFAULT_DATA_DIR)); final Path expathDir = dataDir.resolve(EXPATH_REPO_DIR_NAME); if(!Files.exists(expathDir)) { @@ -353,7 +352,7 @@ private static void moveOldRepo(final Optional home, final Path newRepo) { } else { return h.resolve(LEGACY_DEFAULT_EXPATH_REPO_DIR); } - }).orElse(Paths.get(System.getProperty("java.io.tmpdir")).resolve(EXPATH_REPO_DIR_NAME)); + }).orElse(Path.of(System.getProperty("java.io.tmpdir")).resolve(EXPATH_REPO_DIR_NAME)); if (Files.isReadable(repo_dir)) { LOG.info("Found old expathrepo directory. Moving to new default location: {}", newRepo.toAbsolutePath().toString()); diff --git a/exist-core/src/main/java/org/exist/resolver/ResolverFactory.java b/exist-core/src/main/java/org/exist/resolver/ResolverFactory.java index d06fc2898ab..632ae152358 100644 --- a/exist-core/src/main/java/org/exist/resolver/ResolverFactory.java +++ b/exist-core/src/main/java/org/exist/resolver/ResolverFactory.java @@ -40,7 +40,7 @@ import java.net.URI; import java.net.URISyntaxException; -import java.nio.file.Paths; +import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @@ -96,7 +96,7 @@ static Resolver newResolver(final List>> ca static String sanitizeCatalogUri(String strCatalogUri) { if (strCatalogUri.indexOf('\\') > -1) { // convert from Windows file path - strCatalogUri = Paths.get(strCatalogUri).toUri().toString(); + strCatalogUri = Path.of(strCatalogUri).toUri().toString(); } return strCatalogUri; } diff --git a/exist-core/src/main/java/org/exist/scheduler/JobException.java b/exist-core/src/main/java/org/exist/scheduler/JobException.java index bca3dd0aa1a..c5c4eec4cc3 100644 --- a/exist-core/src/main/java/org/exist/scheduler/JobException.java +++ b/exist-core/src/main/java/org/exist/scheduler/JobException.java @@ -23,6 +23,8 @@ import org.quartz.JobExecutionException; +import java.io.Serial; + /** * Exception class can be thrown by implementations of org.exist.scheduler.Job. * @@ -31,7 +33,8 @@ * @author Adam Retter */ public class JobException extends Exception { - + + @Serial private static final long serialVersionUID = 1567438994821964637L; public enum JobExceptionAction { diff --git a/exist-core/src/main/java/org/exist/scheduler/ScheduledJobInfo.java b/exist-core/src/main/java/org/exist/scheduler/ScheduledJobInfo.java index d5dfdabc3e8..bc95b8ddcb6 100644 --- a/exist-core/src/main/java/org/exist/scheduler/ScheduledJobInfo.java +++ b/exist-core/src/main/java/org/exist/scheduler/ScheduledJobInfo.java @@ -138,10 +138,10 @@ public Date getFinalFireTime() { * @return The expression that was used to configure the Triggers firing pattern */ public String getTriggerExpression(){ - if(trigger instanceof CronTrigger) { - return ((CronTrigger)trigger).getCronExpression(); - } else if(trigger instanceof SimpleTrigger) { - return String.valueOf(((SimpleTrigger)trigger).getRepeatInterval()); + if(trigger instanceof CronTrigger cronTrigger) { + return cronTrigger.getCronExpression(); + } else if(trigger instanceof SimpleTrigger simpleTrigger) { + return String.valueOf(simpleTrigger.getRepeatInterval()); } return null; diff --git a/exist-core/src/main/java/org/exist/scheduler/UserXQueryJob.java b/exist-core/src/main/java/org/exist/scheduler/UserXQueryJob.java index b3ee6dd9546..55544e04693 100644 --- a/exist-core/src/main/java/org/exist/scheduler/UserXQueryJob.java +++ b/exist-core/src/main/java/org/exist/scheduler/UserXQueryJob.java @@ -196,8 +196,8 @@ private void executeXQuery(final BrokerPool pool, final DBBroker broker, final S context.prepareForReuse(); } - if(source instanceof DBSource) { - final XmldbURI collectionUri = ((DBSource)source).getDocumentPath().removeLastSegment(); + if(source instanceof DBSource bSource) { + final XmldbURI collectionUri = bSource.getDocumentPath().removeLastSegment(); context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI.append(collectionUri.getCollectionPath()).toString()); context.setStaticallyKnownDocuments(new XmldbURI[] { collectionUri }); } @@ -256,4 +256,4 @@ private void abort(final String message, final boolean unschedule) throws JobExe throw jaa; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/scheduler/impl/QuartzSchedulerImpl.java b/exist-core/src/main/java/org/exist/scheduler/impl/QuartzSchedulerImpl.java index f89bbea95c5..46e216ddfb4 100644 --- a/exist-core/src/main/java/org/exist/scheduler/impl/QuartzSchedulerImpl.java +++ b/exist-core/src/main/java/org/exist/scheduler/impl/QuartzSchedulerImpl.java @@ -520,7 +520,7 @@ public void setupConfiguredJobs() { //create a Java job try { final Class jobClass = Class.forName(jobConfig.getResourceName()); - final Object jobObject = jobClass.newInstance(); + final Object jobObject = jobClass.getDeclaredConstructor().newInstance(); if(jobConfig.getType().equals(JobType.SYSTEM)) { if(jobObject instanceof SystemTask task) { task.configure(config, jobConfig.getParameters()); @@ -531,8 +531,8 @@ public void setupConfiguredJobs() { } } else { - if(jobObject instanceof JobDescription) { - job = (JobDescription)jobObject; + if(jobObject instanceof JobDescription description) { + job = description; if(jobConfig.getJobName() != null) { job.setName(jobConfig.getJobName()); } @@ -573,13 +573,13 @@ private void setupJobDataMap(final JobDescription job, final JobDataMap jobDataM //if this is a system job, store the BrokerPool in the job's data map jobDataMap.put(DATABASE, brokerPool); //if this is a system task job, store the SystemTask in the job's data map - if(job instanceof SystemTaskJobImpl) { - jobDataMap.put(SYSTEM_TASK, ((SystemTaskJobImpl)job).getSystemTask()); + if(job instanceof SystemTaskJobImpl impl) { + jobDataMap.put(SYSTEM_TASK, impl.getSystemTask()); } //if this is a users XQuery job, store the XQuery resource and user in the job's data map - if(job instanceof UserXQueryJob) { - jobDataMap.put(XQUERY_SOURCE, ((UserXQueryJob)job).getXQueryResource()); - jobDataMap.put(ACCOUNT, ((UserXQueryJob)job).getUser()); + if(job instanceof UserXQueryJob queryJob) { + jobDataMap.put(XQUERY_SOURCE, queryJob.getXQueryResource()); + jobDataMap.put(ACCOUNT, queryJob.getUser()); } //copy any parameters into the job's data map if(params != null) { diff --git a/exist-core/src/main/java/org/exist/security/AbstractAccount.java b/exist-core/src/main/java/org/exist/security/AbstractAccount.java index 01462c1e893..466946fb6be 100644 --- a/exist-core/src/main/java/org/exist/security/AbstractAccount.java +++ b/exist-core/src/main/java/org/exist/security/AbstractAccount.java @@ -252,10 +252,10 @@ public boolean equals(final Object obj) { return Optional .ofNullable(obj) .flatMap(other -> { - if(other instanceof AbstractSubject) { - return Optional.of(((AbstractSubject)other).account); - } else if(other instanceof AbstractAccount) { - return Optional.of((AbstractAccount)other); + if(other instanceof AbstractSubject subject) { + return Optional.of(subject.account); + } else if(other instanceof AbstractAccount account) { + return Optional.of(account); } else { return Optional.empty(); } diff --git a/exist-core/src/main/java/org/exist/security/AbstractSubject.java b/exist-core/src/main/java/org/exist/security/AbstractSubject.java index ed354a49809..da3f03fd521 100644 --- a/exist-core/src/main/java/org/exist/security/AbstractSubject.java +++ b/exist-core/src/main/java/org/exist/security/AbstractSubject.java @@ -181,7 +181,7 @@ public boolean isEnabled() { public boolean equals(final Object obj) { return Optional .ofNullable(obj) - .flatMap(other -> other instanceof Account ? Optional.of((Account)other) : Optional.empty()) + .flatMap(other -> other instanceof Account a ? Optional.of(a) : Optional.empty()) .map(account::equals) .orElse(false); } @@ -240,4 +240,4 @@ public int getUserMask() { public void setUserMask(final int umask) { account.setUserMask(umask); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/security/AuthenticationException.java b/exist-core/src/main/java/org/exist/security/AuthenticationException.java index f9f9f123e44..26095c8e6c9 100644 --- a/exist-core/src/main/java/org/exist/security/AuthenticationException.java +++ b/exist-core/src/main/java/org/exist/security/AuthenticationException.java @@ -21,6 +21,8 @@ */ package org.exist.security; +import java.io.Serial; + /** * Authentication process error. * @@ -29,7 +31,8 @@ */ public class AuthenticationException extends Exception { - private static final long serialVersionUID = 8966739840703820248L; + @Serial + private static final long serialVersionUID = 8966739840703820248L; public static final int UNNOWN_EXCEPTION = -1; diff --git a/exist-core/src/main/java/org/exist/security/PermissionDeniedException.java b/exist-core/src/main/java/org/exist/security/PermissionDeniedException.java index 8d6df57b50d..33d7a85eac6 100644 --- a/exist-core/src/main/java/org/exist/security/PermissionDeniedException.java +++ b/exist-core/src/main/java/org/exist/security/PermissionDeniedException.java @@ -21,6 +21,8 @@ */ package org.exist.security; +import java.io.Serial; + /** * Description of the Class * @@ -29,6 +31,7 @@ */ public class PermissionDeniedException extends Exception { + @Serial private static final long serialVersionUID = 8832813230189409267L; /** Constructor for the PermissionDeniedException object */ @@ -52,4 +55,4 @@ public PermissionDeniedException(String message, Throwable cause) { public PermissionDeniedException(Throwable cause) { super(cause); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/security/PermissionFactory.java b/exist-core/src/main/java/org/exist/security/PermissionFactory.java index fbf5b236966..d0bfa2628b8 100644 --- a/exist-core/src/main/java/org/exist/security/PermissionFactory.java +++ b/exist-core/src/main/java/org/exist/security/PermissionFactory.java @@ -227,7 +227,7 @@ public static void chown(final DBBroker broker, final DocumentImpl document, fin } public static void chown(final DBBroker broker, final Permission permission, final Optional owner, final Optional group) throws PermissionDeniedException { - if ((!owner.isPresent()) && !group.isPresent()) { + if ((owner.isEmpty()) && group.isEmpty()) { throw new IllegalArgumentException("Either owner or group must be provided"); } @@ -435,7 +435,7 @@ public static void chmod(final DBBroker broker, final Permission permissions, fi } private static void chmod_impl(final DBBroker broker, final Permission permission, final Optional> mode, final Optional> acl) throws PermissionDeniedException { - if ((!mode.isPresent()) && !acl.isPresent()) { + if ((mode.isEmpty()) && acl.isEmpty()) { throw new IllegalArgumentException("Either mode or acl must be provided"); } @@ -513,8 +513,8 @@ private static void chmod_impl(final DBBroker broker, final Permission permissio * @throws PermissionDeniedException if the calling process has insufficient permissions. */ public static void chacl(final Permission permission, final ConsumerE permissionModifier) throws PermissionDeniedException { - if(permission instanceof SimpleACLPermission) { - chacl((SimpleACLPermission)permission, permissionModifier); + if(permission instanceof SimpleACLPermission lPermission) { + chacl(lPermission, permissionModifier); } else { throw new PermissionDeniedException("ACL like permissions have not been enabled"); } @@ -533,8 +533,8 @@ public static void chacl(final Permission permission, final ConsumerE permissionModifier) throws PermissionDeniedException { updatePermissions(broker, transaction, pathUri, permission -> { - if(permission instanceof SimpleACLPermission) { - chacl((SimpleACLPermission)permission, permissionModifier); + if(permission instanceof SimpleACLPermission lPermission) { + chacl(lPermission, permissionModifier); } else { throw new PermissionDeniedException("ACL like permissions have not been enabled"); } diff --git a/exist-core/src/main/java/org/exist/security/PermissionRequiredAspect.java b/exist-core/src/main/java/org/exist/security/PermissionRequiredAspect.java index a14ef90fa03..dd6e7c29296 100644 --- a/exist-core/src/main/java/org/exist/security/PermissionRequiredAspect.java +++ b/exist-core/src/main/java/org/exist/security/PermissionRequiredAspect.java @@ -114,8 +114,8 @@ public void enforcePermissions(JoinPoint joinPoint, Permission permission, Permi } //4) check for acl mode access - if(permission instanceof ACLPermission && permissionRequired.mode() != UNDEFINED) { - if((permissionRequired.mode() & ACL_WRITE) == ACL_WRITE && ((ACLPermission)permission).isCurrentSubjectCanWriteACL()) { + if(permission instanceof ACLPermission lPermission && permissionRequired.mode() != UNDEFINED) { + if((permissionRequired.mode() & ACL_WRITE) == ACL_WRITE && lPermission.isCurrentSubjectCanWriteACL()) { return; } } @@ -133,4 +133,4 @@ public void methodWithPermissionRequired(Permission permission, int mode, int us public void enforcePermissions(JoinPoint joinPoint, Permission permission, int mode, int user, int group) { System.out.println("POINTCUT"); }*/ -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/security/SimpleACLPermission.java b/exist-core/src/main/java/org/exist/security/SimpleACLPermission.java index 860fb63c3b2..04a255881cc 100644 --- a/exist-core/src/main/java/org/exist/security/SimpleACLPermission.java +++ b/exist-core/src/main/java/org/exist/security/SimpleACLPermission.java @@ -439,9 +439,9 @@ public boolean aclEquals(final ACLPermission other) { return false; } - if (other instanceof SimpleACLPermission) { + if (other instanceof SimpleACLPermission permission) { // optimisation for when both are the same type - return Arrays.equals(acl, ((SimpleACLPermission) other).acl); + return Arrays.equals(acl, permission.acl); } else { if (getACECount() != other.getACECount()) { return false; diff --git a/exist-core/src/main/java/org/exist/security/internal/Password.java b/exist-core/src/main/java/org/exist/security/internal/Password.java index 342ef233eb7..2745ec3f7d0 100644 --- a/exist-core/src/main/java/org/exist/security/internal/Password.java +++ b/exist-core/src/main/java/org/exist/security/internal/Password.java @@ -139,8 +139,8 @@ public boolean check(Object credentials) { return equals(credentials); } - if(credentials instanceof char[]) { - return equals(String.valueOf((char[]) credentials)); + if(credentials instanceof char[] chars) { + return equals(String.valueOf(chars)); } return false; diff --git a/exist-core/src/main/java/org/exist/security/internal/web/HttpAccount.java b/exist-core/src/main/java/org/exist/security/internal/web/HttpAccount.java index c851147bc98..7bb4d9ed9b1 100644 --- a/exist-core/src/main/java/org/exist/security/internal/web/HttpAccount.java +++ b/exist-core/src/main/java/org/exist/security/internal/web/HttpAccount.java @@ -36,8 +36,8 @@ public class HttpAccount { public static Subject getUserFromServletRequest(final HttpServletRequest request) { final Principal principal = request.getUserPrincipal(); - if(principal instanceof Subject) { - return (Subject) principal; + if(principal instanceof Subject subject2) { + return subject2; } else if(principal != null && "org.eclipse.jetty.plus.jaas.JAASUserPrincipal".equals(principal.getClass().getName())) { //workaroud strange jetty authentication method, why encapsulate user object??? -shabanovd @@ -47,8 +47,8 @@ public static Subject getUserFromServletRequest(final HttpServletRequest request final Object obj = method.invoke(principal); if(obj instanceof javax.security.auth.Subject subject) { for(final Principal _principal_ : subject.getPrincipals()) { - if(_principal_ instanceof Subject) { - return (Subject) _principal_; + if(_principal_ instanceof Subject subject1) { + return subject1; } } } diff --git a/exist-core/src/main/java/org/exist/source/AbstractSource.java b/exist-core/src/main/java/org/exist/source/AbstractSource.java index 24bbdf9ebbb..475975eabd0 100644 --- a/exist-core/src/main/java/org/exist/source/AbstractSource.java +++ b/exist-core/src/main/java/org/exist/source/AbstractSource.java @@ -69,8 +69,8 @@ public void validate(final Subject subject, final int perm) throws PermissionDen @Override public boolean equals(final Object obj) { - if (obj != null && obj instanceof Source) { - return key == (((Source)obj).getKey()); + if (obj != null && obj instanceof Source source) { + return key == (source.getKey()); } return false; } diff --git a/exist-core/src/main/java/org/exist/source/SourceFactory.java b/exist-core/src/main/java/org/exist/source/SourceFactory.java index 1efc60ad01a..91ea7274dcc 100644 --- a/exist-core/src/main/java/org/exist/source/SourceFactory.java +++ b/exist-core/src/main/java/org/exist/source/SourceFactory.java @@ -29,7 +29,6 @@ import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; -import java.nio.file.Paths; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -108,8 +107,8 @@ public class SourceFactory { /* /db */ if (source == null - && ((location.startsWith("/db") && !Files.exists(Paths.get(firstPathSegment(location)))) - || (contextPath != null && contextPath.startsWith("/db") && !Files.exists(Paths.get(firstPathSegment(contextPath)))))) { + && ((location.startsWith("/db") && !Files.exists(Path.of(firstPathSegment(location)))) + || (contextPath != null && contextPath.startsWith("/db") && !Files.exists(Path.of(firstPathSegment(contextPath)))))) { final XmldbURI pathUri; if (contextPath == null || ".".equals(contextPath)) { pathUri = XmldbURI.create(location); @@ -156,7 +155,7 @@ private static Source getSource_fromClasspath(final String contextPath, final St return new ClassLoaderSource(location); } - final Path rootPath = Paths.get(contextPath.substring(ClassLoaderSource.PROTOCOL.length())); + final Path rootPath = Path.of(contextPath.substring(ClassLoaderSource.PROTOCOL.length())); // 1) try resolving location as child final Path childLocation = rootPath.resolve(location); @@ -219,9 +218,9 @@ private static Source getSource_fromClasspath(final String contextPath, final St try { final Path p; if (contextPath == null) { - p = Paths.get(locationPath); + p = Path.of(locationPath); } else { - p = Paths.get(contextPath, locationPath); + p = Path.of(contextPath, locationPath); } if (Files.isReadable(p)) { @@ -234,7 +233,7 @@ private static Source getSource_fromClasspath(final String contextPath, final St if (source == null) { try { - final Path p2 = Paths.get(locationPath); + final Path p2 = Path.of(locationPath); if (Files.isReadable(p2)) { locationPath = p2.toUri().toASCIIString(); source = new FileSource(p2, checkXQEncoding); @@ -246,7 +245,7 @@ private static Source getSource_fromClasspath(final String contextPath, final St if (source == null && contextPath != null) { try { - final Path p3 = Paths.get(contextPath).toAbsolutePath().resolve(locationPath); + final Path p3 = Path.of(contextPath).toAbsolutePath().resolve(locationPath); if (Files.isReadable(p3)) { locationPath = p3.toUri().toASCIIString(); source = new FileSource(p3, checkXQEncoding); @@ -261,7 +260,7 @@ private static Source getSource_fromClasspath(final String contextPath, final St * Try to load as an absolute path */ try { - final Path p4 = Paths.get("/" + locationPath); + final Path p4 = Path.of("/" + locationPath); if (Files.isReadable(p4)) { locationPath = p4.toUri().toASCIIString(); source = new FileSource(p4, checkXQEncoding); @@ -276,7 +275,7 @@ private static Source getSource_fromClasspath(final String contextPath, final St * Try to load from the folder of the contextPath */ try { - final Path p5 = Paths.get(contextPath).resolveSibling(locationPath); + final Path p5 = Path.of(contextPath).resolveSibling(locationPath); if (Files.isReadable(p5)) { locationPath = p5.toUri().toASCIIString(); source = new FileSource(p5, checkXQEncoding); @@ -294,14 +293,14 @@ private static Source getSource_fromClasspath(final String contextPath, final St Path p6 = null; if(contextPath.startsWith("file:/")) { try { - p6 = Paths.get(new URI(contextPath)).resolveSibling(locationPath); + p6 = Path.of(new URI(contextPath)).resolveSibling(locationPath); } catch (final URISyntaxException e) { // continue trying } } if(p6 == null) { - p6 = Paths.get(contextPath.replaceFirst("^file:/*(/.*)$", "$1")).resolveSibling(locationPath); + p6 = Path.of(contextPath.replaceFirst("^file:/*(/.*)$", "$1")).resolveSibling(locationPath); } if (Files.isReadable(p6)) { @@ -321,14 +320,14 @@ private static Source getSource_fromClasspath(final String contextPath, final St Path p7 = null; if(contextPath.startsWith("file:/")) { try { - p7 = Paths.get(new URI(contextPath)).resolve(locationPath); + p7 = Path.of(new URI(contextPath)).resolve(locationPath); } catch (final URISyntaxException e) { // continue trying } } if(p7 == null) { - p7 = Paths.get(contextPath.replaceFirst("^file:/*(/.*)$", "$1")).resolve(locationPath); + p7 = Path.of(contextPath.replaceFirst("^file:/*(/.*)$", "$1")).resolve(locationPath); } if (Files.isReadable(p7)) { diff --git a/exist-core/src/main/java/org/exist/source/URLSource.java b/exist-core/src/main/java/org/exist/source/URLSource.java index bad2f27cf1c..74764521439 100644 --- a/exist-core/src/main/java/org/exist/source/URLSource.java +++ b/exist-core/src/main/java/org/exist/source/URLSource.java @@ -138,14 +138,14 @@ public Reader getReader() throws IOException { try { if (connection == null) { connection = url.openConnection(); - if (connection instanceof HttpURLConnection) { - ((HttpURLConnection) connection).setRequestProperty("Accept", ACCEPT_HEADER); + if (connection instanceof HttpURLConnection lConnection) { + lConnection.setRequestProperty("Accept", ACCEPT_HEADER); } lastModified = connection.getLastModified(); - if (connection instanceof HttpURLConnection) { - responseCode = ((HttpURLConnection) connection).getResponseCode(); + if (connection instanceof HttpURLConnection lConnection) { + responseCode = lConnection.getResponseCode(); } } Reader reader = null; @@ -165,14 +165,14 @@ public InputStream getInputStream() throws IOException { try { if (connection == null) { connection = url.openConnection(); - if (connection instanceof HttpURLConnection) { - ((HttpURLConnection) connection).setRequestProperty("Accept", ACCEPT_HEADER); + if (connection instanceof HttpURLConnection lConnection) { + lConnection.setRequestProperty("Accept", ACCEPT_HEADER); } lastModified = connection.getLastModified(); - if (connection instanceof HttpURLConnection) { - responseCode = ((HttpURLConnection) connection).getResponseCode(); + if (connection instanceof HttpURLConnection lConnection) { + responseCode = lConnection.getResponseCode(); } } InputStream is = null; @@ -197,14 +197,14 @@ public String getContent() { try { if (connection == null) { connection = url.openConnection(); - if (connection instanceof HttpURLConnection) { - ((HttpURLConnection) connection).setRequestProperty("Accept", ACCEPT_HEADER); + if (connection instanceof HttpURLConnection lConnection) { + lConnection.setRequestProperty("Accept", ACCEPT_HEADER); } lastModified = connection.getLastModified(); - if (connection instanceof HttpURLConnection) { - responseCode = ((HttpURLConnection) connection).getResponseCode(); + if (connection instanceof HttpURLConnection lConnection) { + responseCode = lConnection.getResponseCode(); } } final String content = connection.getContent().toString(); diff --git a/exist-core/src/main/java/org/exist/storage/BackupSystemTask.java b/exist-core/src/main/java/org/exist/storage/BackupSystemTask.java index 41c7fb3f25e..10ee6881c59 100644 --- a/exist-core/src/main/java/org/exist/storage/BackupSystemTask.java +++ b/exist-core/src/main/java/org/exist/storage/BackupSystemTask.java @@ -35,7 +35,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.*; @@ -115,7 +114,7 @@ public void configure(final Configuration config, final Properties properties) t prefix = properties.getProperty("prefix", ""); final String dir = properties.getProperty("dir", "backup"); - directory = Paths.get(dir); + directory = Path.of(dir); if (!directory.isAbsolute()) { directory = ((Path)config.getProperty(BrokerPool.PROPERTY_DATA_DIR)).resolve(dir); } diff --git a/exist-core/src/main/java/org/exist/storage/BrokerPool.java b/exist-core/src/main/java/org/exist/storage/BrokerPool.java index 9fc13a16fac..8556bf08f1c 100644 --- a/exist-core/src/main/java/org/exist/storage/BrokerPool.java +++ b/exist-core/src/main/java/org/exist/storage/BrokerPool.java @@ -451,12 +451,10 @@ void initialize() throws EXistException, DatabaseConfigurationException { dataLock.release(); } - if (e instanceof EXistException existException) { - throw existException; - } else if(e instanceof DatabaseConfigurationException databaseConfigurationException) { - throw databaseConfigurationException; - } else { - throw new EXistException(e); + switch (e) { + case EXistException existException -> throw existException; + case DatabaseConfigurationException databaseConfigurationException -> throw databaseConfigurationException; + default -> throw new EXistException(e); } } } diff --git a/exist-core/src/main/java/org/exist/storage/BrokerPools.java b/exist-core/src/main/java/org/exist/storage/BrokerPools.java index 23a74d5a566..72540a255c8 100644 --- a/exist-core/src/main/java/org/exist/storage/BrokerPools.java +++ b/exist-core/src/main/java/org/exist/storage/BrokerPools.java @@ -182,8 +182,8 @@ public static void configure(final String instanceName, final int minBrokers, fi // Catch all possible issues and report. LOG.error("Unable to initialize database instance '{}': {}", instanceName, e.getMessage(), e); final EXistException ee; - if(e instanceof EXistException) { - ee = (EXistException)e; + if(e instanceof EXistException exception) { + ee = exception; } else { ee = new EXistException(e); } diff --git a/exist-core/src/main/java/org/exist/storage/ConsistencyCheckTask.java b/exist-core/src/main/java/org/exist/storage/ConsistencyCheckTask.java index 92cf4284d83..70f309169e4 100644 --- a/exist-core/src/main/java/org/exist/storage/ConsistencyCheckTask.java +++ b/exist-core/src/main/java/org/exist/storage/ConsistencyCheckTask.java @@ -25,7 +25,6 @@ import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import java.util.Properties; @@ -86,7 +85,7 @@ public String getName() { @Override public void configure(final Configuration config, final Properties properties) throws EXistException { exportDir = properties.getProperty(OUTPUT_PROP_NAME, "export"); - Path dir = Paths.get(exportDir); + Path dir = Path.of(exportDir); if (!dir.isAbsolute()) { dir = ((Path) config.getProperty(BrokerPool.PROPERTY_DATA_DIR)).resolve(exportDir); } diff --git a/exist-core/src/main/java/org/exist/storage/DataBackup.java b/exist-core/src/main/java/org/exist/storage/DataBackup.java index 92c05e59a16..a588a3ca158 100644 --- a/exist-core/src/main/java/org/exist/storage/DataBackup.java +++ b/exist-core/src/main/java/org/exist/storage/DataBackup.java @@ -34,7 +34,6 @@ import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Optional; @@ -72,7 +71,7 @@ public String getName() { @Override public void configure(final Configuration config, final Properties properties) throws EXistException { - dest = Paths.get(properties.getProperty("output-dir", "backup")); + dest = Path.of(properties.getProperty("output-dir", "backup")); if (!dest.isAbsolute()) { dest = ((Path)config.getProperty(BrokerPool.PROPERTY_DATA_DIR)).resolve(dest); } diff --git a/exist-core/src/main/java/org/exist/storage/NativeBroker.java b/exist-core/src/main/java/org/exist/storage/NativeBroker.java index 7a1219a4c83..1cd3eb4d6f7 100644 --- a/exist-core/src/main/java/org/exist/storage/NativeBroker.java +++ b/exist-core/src/main/java/org/exist/storage/NativeBroker.java @@ -87,7 +87,6 @@ import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.text.NumberFormat; import java.util.*; import java.util.function.Function; @@ -227,7 +226,7 @@ public NativeBroker(final BrokerPool pool, final Configuration config) throws EX this.lockManager = pool.getLockManager(); LOG.debug("Initializing broker {}", hashCode()); - this.dataDir = config.getProperty(BrokerPool.PROPERTY_DATA_DIR, Paths.get(DEFAULT_DATA_DIR)); + this.dataDir = config.getProperty(BrokerPool.PROPERTY_DATA_DIR, Path.of(DEFAULT_DATA_DIR)); nodesCountThreshold = config.getInteger(BrokerPool.PROPERTY_NODES_BUFFER); if(nodesCountThreshold > 0) { @@ -724,7 +723,7 @@ private XmldbURI prepend(final XmldbURI uri) { // 1) try and load from etc/ dir final Path fInitCollectionConfig = pool.getConfiguration().getExistHome() .map(h -> h.resolve("etc").resolve(INIT_COLLECTION_CONFIG)) - .orElse(Paths.get("etc").resolve(INIT_COLLECTION_CONFIG)); + .orElse(Path.of("etc").resolve(INIT_COLLECTION_CONFIG)); if (Files.exists(fInitCollectionConfig)) { return Files.readString(fInitCollectionConfig, UTF_8); } @@ -1178,7 +1177,7 @@ public void readCollectionEntry(final SubCollectionEntry entry) throws IOExcepti } else { if(!collection.getURI().equalsInternal(uri)) { - throw new IOException(String.format("readCollectionEntry: The Collection received from the cache: %s is not the requested: %s", collection.getURI(), uri)); + throw new IOException("readCollectionEntry: The Collection received from the cache: %s is not the requested: %s".formatted(collection.getURI(), uri)); } entry.read(collection); @@ -1899,8 +1898,8 @@ public Object start() { }.run(); // if it is a binary document remove the content from disk - if (doc instanceof BinaryDocument) { - removeCollectionBinary(transaction, (BinaryDocument)doc); + if (doc instanceof BinaryDocument document) { + removeCollectionBinary(transaction, document); } docTrigger.afterDeleteDocument(this, transaction, doc.getURI()); @@ -2479,8 +2478,8 @@ public void readBinaryResource(final Txn transaction, final BinaryDocument blob, final BlobStore blobStore = pool.getBlobStore(); try (final InputStream is = blobStore.get(transaction, blob.getBlobId())) { if (is != null) { - if (os instanceof UnsynchronizedByteArrayOutputStream) { - ((UnsynchronizedByteArrayOutputStream)os).write(is); + if (os instanceof UnsynchronizedByteArrayOutputStream stream) { + stream.write(is); } else { copy(is, os); } @@ -2826,9 +2825,9 @@ public static void copyResource_preserve(final DBBroker broker, final DocumentIm */ private static void copyModeAcl(final DBBroker broker, final Permission srcPermissions, final Permission destPermissions) throws PermissionDeniedException { PermissionFactory.chmod(broker, destPermissions, Optional.of(srcPermissions.getMode()), Optional.empty()); - if (srcPermissions instanceof SimpleACLPermission && destPermissions instanceof SimpleACLPermission) { + if (srcPermissions instanceof SimpleACLPermission permission && destPermissions instanceof SimpleACLPermission) { PermissionFactory.chacl(destPermissions, newAcl -> - ((SimpleACLPermission)newAcl).copyAclOf((SimpleACLPermission)srcPermissions) + ((SimpleACLPermission)newAcl).copyAclOf(permission) ); } } @@ -3097,8 +3096,8 @@ public void removeResourceMetadata(final Txn transaction, @Override public void removeResource(final Txn tx, final DocumentImpl doc) throws IOException, PermissionDeniedException { - if (doc instanceof BinaryDocument) { - removeBinaryResource(tx, (BinaryDocument) doc); + if (doc instanceof BinaryDocument document) { + removeBinaryResource(tx, document); } else { removeXMLResource(tx, doc); } diff --git a/exist-core/src/main/java/org/exist/storage/ProcessMonitor.java b/exist-core/src/main/java/org/exist/storage/ProcessMonitor.java index c2fb7e7a78b..47a5456edb7 100644 --- a/exist-core/src/main/java/org/exist/storage/ProcessMonitor.java +++ b/exist-core/src/main/java/org/exist/storage/ProcessMonitor.java @@ -378,7 +378,7 @@ public static String getRequestURI(final XQueryWatchDog watchdog) { .map(XQueryContext::getHttpContext) .map(XQueryContext.HttpContext::getRequest); - if (!maybeRequest.isPresent()) { + if (maybeRequest.isEmpty()) { return null; } diff --git a/exist-core/src/main/java/org/exist/storage/XQueryPool.java b/exist-core/src/main/java/org/exist/storage/XQueryPool.java index 1de4599e98d..ef85010090c 100644 --- a/exist-core/src/main/java/org/exist/storage/XQueryPool.java +++ b/exist-core/src/main/java/org/exist/storage/XQueryPool.java @@ -169,8 +169,8 @@ public CompiledXQuery borrowCompiledXQuery(final DBBroker broker, final Source s } //check execution permission - if (source instanceof DBSource) { - ((DBSource) source).validate(Permission.EXECUTE); + if (source instanceof DBSource bSource) { + bSource.validate(Permission.EXECUTE); } return borrowedCompiledQuery.value; diff --git a/exist-core/src/main/java/org/exist/storage/blob/BlobStoreImpl.java b/exist-core/src/main/java/org/exist/storage/blob/BlobStoreImpl.java index 4cf9ec48bac..23935374a05 100644 --- a/exist-core/src/main/java/org/exist/storage/blob/BlobStoreImpl.java +++ b/exist-core/src/main/java/org/exist/storage/blob/BlobStoreImpl.java @@ -1707,8 +1707,8 @@ public String toString() { @Override public int compareTo(final Request other) { - if (other instanceof RequestDeleteBlobFile) { - return ((RequestDeleteBlobFile) other).blobReference.readers.get() - blobReference.readers.get(); + if (other instanceof RequestDeleteBlobFile file) { + return file.blobReference.readers.get() - blobReference.readers.get(); } else { // This class has higher priority than other classes return 1; @@ -1770,8 +1770,8 @@ public String toString() { @Override public int compareTo(final Request other) { - if (other instanceof RequestDeleteStagedBlobFile) { - return stagedBlobUuid.compareTo(((RequestDeleteStagedBlobFile)other).stagedBlobUuid); + if (other instanceof RequestDeleteStagedBlobFile file) { + return stagedBlobUuid.compareTo(file.stagedBlobUuid); } else { // This class has lower priority than other classes return -1; diff --git a/exist-core/src/main/java/org/exist/storage/btree/BTreeException.java b/exist-core/src/main/java/org/exist/storage/btree/BTreeException.java index 3128a9a7608..3ac4a32193b 100644 --- a/exist-core/src/main/java/org/exist/storage/btree/BTreeException.java +++ b/exist-core/src/main/java/org/exist/storage/btree/BTreeException.java @@ -72,6 +72,8 @@ */ package org.exist.storage.btree; +import java.io.Serial; + /** * A BTreeException is thrown by the BTree if an exception occurs in the * managing of the BTree. @@ -79,7 +81,8 @@ public class BTreeException extends DBException { - private static final long serialVersionUID = -9164807722775875790L; + @Serial + private static final long serialVersionUID = -9164807722775875790L; public BTreeException() { } diff --git a/exist-core/src/main/java/org/exist/storage/btree/DBException.java b/exist-core/src/main/java/org/exist/storage/btree/DBException.java index d03526f847c..bfe462f5fe7 100644 --- a/exist-core/src/main/java/org/exist/storage/btree/DBException.java +++ b/exist-core/src/main/java/org/exist/storage/btree/DBException.java @@ -72,14 +72,17 @@ */ package org.exist.storage.btree; +import java.io.Serial; + /** * A DBException is thrown by the database if an exception occurs in the * managing (creating, dropping) database objects such as Collections, Indexes, * and XMLObjects. */ public class DBException extends Exception { - - private static final long serialVersionUID = 952318931514282901L; + + @Serial + private static final long serialVersionUID = 952318931514282901L; public int faultCode; diff --git a/exist-core/src/main/java/org/exist/storage/btree/Value.java b/exist-core/src/main/java/org/exist/storage/btree/Value.java index 8e40f849280..99cf6d69c59 100644 --- a/exist-core/src/main/java/org/exist/storage/btree/Value.java +++ b/exist-core/src/main/java/org/exist/storage/btree/Value.java @@ -179,8 +179,8 @@ public boolean equals(final Object obj) { if (this == obj) { return true; } - if (obj instanceof Value) { - return equals((Value) obj); + if (obj instanceof Value value) { + return equals(value); } else { return equals(new Value(obj.toString())); } @@ -206,8 +206,8 @@ public final int compareTo(final Value value) { @Override public final int compareTo(final Object obj) { - if (obj instanceof Value) { - return compareTo((Value) obj); + if (obj instanceof Value value) { + return compareTo(value); } else { return compareTo(new Value(obj.toString())); } diff --git a/exist-core/src/main/java/org/exist/storage/index/BFile.java b/exist-core/src/main/java/org/exist/storage/index/BFile.java index b1913dd0d77..6c34cbc8de2 100644 --- a/exist-core/src/main/java/org/exist/storage/index/BFile.java +++ b/exist-core/src/main/java/org/exist/storage/index/BFile.java @@ -218,8 +218,8 @@ public long append(final Txn transaction, final Value key, final ByteArray value final long pnum = StorageAddress.pageFromPointer(p); final short tid = StorageAddress.tidFromPointer(p); final DataPage page = getDataPage(pnum); - if (page instanceof OverflowPage) { - ((OverflowPage) page).append(transaction, value); + if (page instanceof OverflowPage overflowPage) { + overflowPage.append(transaction, value); } else { final int valueLen = value.size(); final byte[] data = page.getData(); diff --git a/exist-core/src/main/java/org/exist/storage/journal/Journal.java b/exist-core/src/main/java/org/exist/storage/journal/Journal.java index 054399dd9c4..e34c252f436 100644 --- a/exist-core/src/main/java/org/exist/storage/journal/Journal.java +++ b/exist-core/src/main/java/org/exist/storage/journal/Journal.java @@ -781,7 +781,7 @@ static String getFileName(final short fileNum) throws IllegalArgumentException { if (fileNum < 0) { throw new IllegalArgumentException("File Number: " + fileNum + " is out of range (0-" + Short.MAX_VALUE + ")"); } - return String.format("%010x", fileNum) + '.' + LOG_FILE_SUFFIX; + return "%010x".formatted(fileNum) + '.' + LOG_FILE_SUFFIX; } private static class RemoveRunnable implements Runnable { diff --git a/exist-core/src/main/java/org/exist/storage/journal/LogException.java b/exist-core/src/main/java/org/exist/storage/journal/LogException.java index f67300f3c79..8f65c0c3372 100644 --- a/exist-core/src/main/java/org/exist/storage/journal/LogException.java +++ b/exist-core/src/main/java/org/exist/storage/journal/LogException.java @@ -23,9 +23,12 @@ import org.exist.EXistException; +import java.io.Serial; + public class LogException extends EXistException { - private static final long serialVersionUID = 555708654980577412L; + @Serial + private static final long serialVersionUID = 555708654980577412L; public LogException(String message) { super(message); diff --git a/exist-core/src/main/java/org/exist/storage/lock/EnsureLockingAspect.java b/exist-core/src/main/java/org/exist/storage/lock/EnsureLockingAspect.java index 0c82ac2da55..ec0c77bd36b 100644 --- a/exist-core/src/main/java/org/exist/storage/lock/EnsureLockingAspect.java +++ b/exist-core/src/main/java/org/exist/storage/lock/EnsureLockingAspect.java @@ -806,8 +806,8 @@ private Tuple2 getLockMode(final Lock.LockMode specified final short idx = specifiedLockModeParam; if(idx < args.length) { final Object arg = args[idx]; - if(arg instanceof Lock.LockMode) { - mode = new Tuple2<>((Lock.LockMode)arg, true); + if(arg instanceof Lock.LockMode lockMode) { + mode = new Tuple2<>(lockMode, true); } else { throw new IllegalArgumentException("modeParam was specified on @EnsureLocked but its index was not a Lock.LockMode parameter, found: " + arg.getClass().getName()); } @@ -831,8 +831,8 @@ private Tuple2 getLockMode(final Lock.LockMode specified private List getLockModeArgs(final Object[] args) { final List lockModeArgs = new ArrayList<>(); for(final Object arg : args) { - if(arg instanceof Lock.LockMode) { - lockModeArgs.add((Lock.LockMode)arg); + if(arg instanceof Lock.LockMode lockMode) { + lockModeArgs.add(lockMode); } } return lockModeArgs; diff --git a/exist-core/src/main/java/org/exist/storage/lock/FileLockService.java b/exist-core/src/main/java/org/exist/storage/lock/FileLockService.java index 064e5ca45d9..e28dd27a70e 100644 --- a/exist-core/src/main/java/org/exist/storage/lock/FileLockService.java +++ b/exist-core/src/main/java/org/exist/storage/lock/FileLockService.java @@ -44,7 +44,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import java.util.concurrent.atomic.AtomicReference; @@ -71,7 +70,7 @@ public FileLockService(final String lockFileName, final String confDirPropName, @Override public void configure(final Configuration configuration) throws BrokerPoolServiceException { dataDir = Optional.ofNullable((Path) configuration.getProperty(confDirPropName)) - .orElse(Paths.get(defaultDirName)); + .orElse(Path.of(defaultDirName)); if(!Files.exists(dataDir)) { try { diff --git a/exist-core/src/main/java/org/exist/storage/serializers/ChainOfReceiversFactory.java b/exist-core/src/main/java/org/exist/storage/serializers/ChainOfReceiversFactory.java index b67eb1e24b1..68f5bf60eea 100644 --- a/exist-core/src/main/java/org/exist/storage/serializers/ChainOfReceiversFactory.java +++ b/exist-core/src/main/java/org/exist/storage/serializers/ChainOfReceiversFactory.java @@ -43,7 +43,7 @@ public ChainOfReceiversFactory(List classes) { try { final Class listenerClass = Class.forName(className); if (ChainOfReceivers.class.isAssignableFrom(listenerClass)) { - listener = (ChainOfReceivers) listenerClass.newInstance(); + listener = (ChainOfReceivers) listenerClass.getDeclaredConstructor().newInstance(); if (first == null) { first = listener; last = listener; @@ -67,4 +67,4 @@ public ChainOfReceivers getFirst() { public ChainOfReceivers getLast() { return last; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/storage/serializers/CustomMatchListenerFactory.java b/exist-core/src/main/java/org/exist/storage/serializers/CustomMatchListenerFactory.java index 0d831df4fdb..146016ba880 100644 --- a/exist-core/src/main/java/org/exist/storage/serializers/CustomMatchListenerFactory.java +++ b/exist-core/src/main/java/org/exist/storage/serializers/CustomMatchListenerFactory.java @@ -75,7 +75,7 @@ public CustomMatchListenerFactory(final DBBroker broker, final Configuration con try { final Class listenerClass = Class.forName(className); if (CustomMatchListener.class.isAssignableFrom(listenerClass)) { - final CustomMatchListener listener = (CustomMatchListener) listenerClass.newInstance(); + final CustomMatchListener listener = (CustomMatchListener) listenerClass.getDeclaredConstructor().newInstance(); listener.setBroker(broker); if (first == null) { first = listener; @@ -103,4 +103,4 @@ public MatchListener getFirst() { public MatchListener getLast() { return last; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/storage/serializers/Serializer.java b/exist-core/src/main/java/org/exist/storage/serializers/Serializer.java index e2f2166443b..90c90ef5a14 100644 --- a/exist-core/src/main/java/org/exist/storage/serializers/Serializer.java +++ b/exist-core/src/main/java/org/exist/storage/serializers/Serializer.java @@ -789,8 +789,8 @@ public void setStylesheet(final Document doc, final @Nullable String stylesheet) } else { // if stylesheet is relative, add path to the // current collection and normalize - if (doc != null && doc instanceof DocumentImpl) { - stylesheetUri = ((DocumentImpl) doc).getCollection().getURI().resolveCollectionPath(stylesheetUri).normalizeCollectionPath(); + if (doc != null && doc instanceof DocumentImpl impl) { + stylesheetUri = impl.getCollection().getURI().resolveCollectionPath(stylesheetUri).normalizeCollectionPath(); } // load stylesheet from eXist @@ -862,8 +862,8 @@ protected void setXSLHandler(@Nullable final NodeProxy root, final boolean apply final ReceiverToSAX filter; if (processXInclude) { final Receiver xincludeReceiver = xinclude.getReceiver(); - if (xincludeReceiver != null && xincludeReceiver instanceof SAXSerializer) { - filter = new ReceiverToSAX((SAXSerializer) xincludeReceiver); + if (xincludeReceiver != null && xincludeReceiver instanceof SAXSerializer serializer) { + filter = new ReceiverToSAX(serializer); } else { filter = (ReceiverToSAX) xincludeReceiver; } diff --git a/exist-core/src/main/java/org/exist/storage/serializers/XIncludeFilter.java b/exist-core/src/main/java/org/exist/storage/serializers/XIncludeFilter.java index 0be95fbe55d..f26d333c0bf 100644 --- a/exist-core/src/main/java/org/exist/storage/serializers/XIncludeFilter.java +++ b/exist-core/src/main/java/org/exist/storage/serializers/XIncludeFilter.java @@ -68,7 +68,6 @@ import java.net.URLConnection; import java.net.URLDecoder; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import java.util.Optional; @@ -360,7 +359,7 @@ protected Optional processXInclude(final String href, String xpoi // XQuery context. if (scheme == null && moduleLoadPath != null) { final String path = externalUri.getSchemeSpecificPart(); - Path f = Paths.get(path); + Path f = Path.of(path); if (!f.isAbsolute()) { if (moduleLoadPath.startsWith(XmldbURI.XMLDB_URI_PREFIX)) { final XmldbURI parentUri = XmldbURI.create(moduleLoadPath); @@ -370,7 +369,7 @@ protected Optional processXInclude(final String href, String xpoi throw new PermissionDeniedException("Permission denied to read XInclude'd resource"); } } else { - f = Paths.get(moduleLoadPath, path); + f = Path.of(moduleLoadPath, path); externalUri = f.toUri(); } } diff --git a/exist-core/src/main/java/org/exist/storage/txn/TransactionException.java b/exist-core/src/main/java/org/exist/storage/txn/TransactionException.java index cdf95c79873..093b1a1468b 100644 --- a/exist-core/src/main/java/org/exist/storage/txn/TransactionException.java +++ b/exist-core/src/main/java/org/exist/storage/txn/TransactionException.java @@ -23,11 +23,14 @@ import org.exist.EXistException; +import java.io.Serial; + /** * @author wolf * */ public class TransactionException extends EXistException { + @Serial private static final long serialVersionUID = 3617572708582437173L; public TransactionException(final String message) { diff --git a/exist-core/src/main/java/org/exist/storage/txn/TransactionManager.java b/exist-core/src/main/java/org/exist/storage/txn/TransactionManager.java index d501892fbbd..1cdc5b583be 100644 --- a/exist-core/src/main/java/org/exist/storage/txn/TransactionManager.java +++ b/exist-core/src/main/java/org/exist/storage/txn/TransactionManager.java @@ -424,7 +424,7 @@ public void close(final Txn txn) { // TODO(AR) ultimately we should be doing away with DBBroker#addCurrentTransaction try(final DBBroker broker = pool.getBroker()) { - broker.removeCurrentTransaction(txn instanceof Txn.ReusableTxn ? ((Txn.ReusableTxn)txn).getUnderlyingTransaction() : txn); + broker.removeCurrentTransaction(txn instanceof Txn.ReusableTxn rt ? rt.getUnderlyingTransaction() : txn); } catch(final EXistException ee) { LOG.fatal(ee.getMessage(), ee); throw new RuntimeException(ee); diff --git a/exist-core/src/main/java/org/exist/test/DiffMatcher.java b/exist-core/src/main/java/org/exist/test/DiffMatcher.java index f00d2cc34f6..03ad04f62b4 100644 --- a/exist-core/src/main/java/org/exist/test/DiffMatcher.java +++ b/exist-core/src/main/java/org/exist/test/DiffMatcher.java @@ -98,8 +98,8 @@ public boolean matches(final Object item, final Description mismatch) { } final Item actualItem; - if (item instanceof NodeValue) { - actualItem = (NodeValue) item; + if (item instanceof NodeValue value) { + actualItem = value; } else if (item instanceof final Sequence actual) { diff --git a/exist-core/src/main/java/org/exist/test/ExistEmbeddedServer.java b/exist-core/src/main/java/org/exist/test/ExistEmbeddedServer.java index 8737786a5e9..421995678d5 100644 --- a/exist-core/src/main/java/org/exist/test/ExistEmbeddedServer.java +++ b/exist-core/src/main/java/org/exist/test/ExistEmbeddedServer.java @@ -38,7 +38,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Map; import java.util.Optional; import java.util.Properties; @@ -123,7 +122,7 @@ public void startDb() throws DatabaseConfigurationException, EXistException, IOE final String name = instanceName.orElse(BrokerPool.DEFAULT_INSTANCE_NAME); - final Optional home = Optional.ofNullable(System.getProperty("exist.home", System.getProperty("user.dir"))).map(Paths::get); + final Optional home = Optional.ofNullable(System.getProperty("exist.home", System.getProperty("user.dir"))).map(Path::of); final Path confFile = configFile.orElseGet(() -> ConfigurationHelper.lookup("conf.xml", home)); final Configuration config; diff --git a/exist-core/src/main/java/org/exist/test/runner/AbstractTestRunner.java b/exist-core/src/main/java/org/exist/test/runner/AbstractTestRunner.java index 4f5b40d79c4..a79a1cb3ce0 100644 --- a/exist-core/src/main/java/org/exist/test/runner/AbstractTestRunner.java +++ b/exist-core/src/main/java/org/exist/test/runner/AbstractTestRunner.java @@ -43,7 +43,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import java.util.Optional; import java.util.function.Function; @@ -97,8 +96,8 @@ protected static Sequence executeQuery(final BrokerPool brokerPool, final Source context.setBaseURI(new AnyURIValue("/db")); if (moduleLoadPath != null) { context.setModuleLoadPath(moduleLoadPath.toAbsolutePath().toString()); - } else if (query instanceof FileSource) { - final Path queryPath = Paths.get(((FileSource) query).getPath().toAbsolutePath().toString()); + } else if (query instanceof FileSource source) { + final Path queryPath = Path.of(source.getPath().toAbsolutePath().toString()); if (Files.isDirectory(queryPath)) { context.setModuleLoadPath(queryPath.toString()); } else { diff --git a/exist-core/src/main/java/org/exist/test/runner/ExtTestFailureFunction.java b/exist-core/src/main/java/org/exist/test/runner/ExtTestFailureFunction.java index 404c4d69906..2b8c2b370ac 100644 --- a/exist-core/src/main/java/org/exist/test/runner/ExtTestFailureFunction.java +++ b/exist-core/src/main/java/org/exist/test/runner/ExtTestFailureFunction.java @@ -42,7 +42,6 @@ import java.io.IOException; import java.io.StringWriter; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Properties; import static org.exist.xquery.FunctionDSL.param; @@ -121,7 +120,7 @@ private static String lastPathSegment(final String path) { return path; } try { - final Path p = Paths.get(path); + final Path p = Path.of(path); return p.getFileName() != null ? p.getFileName().toString() : path; } catch (final Exception ignored) { return path; @@ -147,8 +146,8 @@ private int getLineFromActual(final MapType actual) throws XPathException { final Sequence seqLine = actual.get(new StringValue(this, "line")); if (!seqLine.isEmpty()) { final Item item = seqLine.itemAt(0); - if (item instanceof IntegerValue) { - return (int) ((IntegerValue) item).getLong(); + if (item instanceof IntegerValue value) { + return (int) value.getLong(); } try { return Integer.parseInt(item.getStringValue()); diff --git a/exist-core/src/main/java/org/exist/test/runner/XQueryFailureLog.java b/exist-core/src/main/java/org/exist/test/runner/XQueryFailureLog.java index 0ec99562b81..883e3929ea7 100644 --- a/exist-core/src/main/java/org/exist/test/runner/XQueryFailureLog.java +++ b/exist-core/src/main/java/org/exist/test/runner/XQueryFailureLog.java @@ -25,7 +25,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardOpenOption; /** @@ -53,7 +52,7 @@ public static void log(final String message) { } final String firstLine = message.contains("\n") ? message.substring(0, message.indexOf('\n')) : message; try { - final Path dir = Paths.get(System.getProperty("user.dir", "."), "target", "surefire-reports"); + final Path dir = Path.of(System.getProperty("user.dir", "."), "target", "surefire-reports"); if (!Files.isDirectory(dir)) { Files.createDirectories(dir); } diff --git a/exist-core/src/main/java/org/exist/test/runner/XQueryTestRunner.java b/exist-core/src/main/java/org/exist/test/runner/XQueryTestRunner.java index 23e532432f8..1044aebfb7f 100644 --- a/exist-core/src/main/java/org/exist/test/runner/XQueryTestRunner.java +++ b/exist-core/src/main/java/org/exist/test/runner/XQueryTestRunner.java @@ -55,7 +55,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import static java.nio.charset.StandardCharsets.UTF_8; @@ -108,7 +107,7 @@ private static XQueryTestInfo discoverOrExtractTestInfo(final Path path) throws } private static Configuration getConfiguration() throws DatabaseConfigurationException { - final Optional home = Optional.ofNullable(System.getProperty("exist.home", System.getProperty("user.dir"))).map(Paths::get); + final Optional home = Optional.ofNullable(System.getProperty("exist.home", System.getProperty("user.dir"))).map(Path::of); final Path confFile = ConfigurationHelper.lookup("conf.xml", home); if (confFile.isAbsolute() && Files.exists(confFile)) { diff --git a/exist-core/src/main/java/org/exist/test/runner/XSuite.java b/exist-core/src/main/java/org/exist/test/runner/XSuite.java index 97591b6d888..46f1145bd1c 100644 --- a/exist-core/src/main/java/org/exist/test/runner/XSuite.java +++ b/exist-core/src/main/java/org/exist/test/runner/XSuite.java @@ -40,7 +40,6 @@ import java.lang.annotation.*; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -112,7 +111,7 @@ public static Runner emptySuite() { private static String[] getAnnotatedDirectories(final Class klass) throws InitializationError { final XSuite.XSuiteFiles annotation = klass.getAnnotation(XSuite.XSuiteFiles.class); if (annotation == null) { - throw new InitializationError(String.format("class '%s' must have a XSuiteFiles annotation", klass.getName())); + throw new InitializationError("class '%s' must have a XSuiteFiles annotation".formatted(klass.getName())); } return annotation.value(); } @@ -205,7 +204,7 @@ private static boolean hasAnyXQueryFiles(final String[] suites) throws IOExcepti } final java.util.function.Predicate isXQueryFile = XQueryFilenameFilter.asPredicate(); for (final String suite : suites) { - final Path path = Paths.get(suite); + final Path path = Path.of(suite); if (!Files.exists(path)) { continue; } @@ -260,7 +259,7 @@ private static List getRunners(final String[] suites, final boolean para for (final String suite : suites) { // if directory/file does not exist - throw an exception - final Path path = Paths.get(suite); + final Path path = Path.of(suite); if (!Files.exists(path)) { throw new InitializationError("XSuite does not exist: " + suite + ". path=" + path.toAbsolutePath()); } @@ -556,8 +555,8 @@ void setCurrentRunner(final Description description) { void runnerStarted(final Description runnerDesc, final Runner runner) { lastActivityByRunner.put(runnerDesc, System.currentTimeMillis()); - if (runner instanceof AbstractTestRunner) { - runnerLabelByDescription.put(runnerDesc, ((AbstractTestRunner) runner).getSourcePath().toAbsolutePath().toString()); + if (runner instanceof AbstractTestRunner testRunner) { + runnerLabelByDescription.put(runnerDesc, testRunner.getSourcePath().toAbsolutePath().toString()); } else { runnerLabelByDescription.put(runnerDesc, runnerDesc.getDisplayName()); } diff --git a/exist-core/src/main/java/org/exist/util/CharSlice.java b/exist-core/src/main/java/org/exist/util/CharSlice.java index ff2ac84d8da..8175eb76ab1 100644 --- a/exist-core/src/main/java/org/exist/util/CharSlice.java +++ b/exist-core/src/main/java/org/exist/util/CharSlice.java @@ -23,6 +23,7 @@ import net.jcip.annotations.ThreadSafe; +import java.io.Serial; import java.io.Serializable; import java.io.Writer; @@ -42,7 +43,8 @@ @ThreadSafe public final class CharSlice implements CharSequence, Serializable { - private static final long serialVersionUID = -2668084569793755681L; + @Serial + private static final long serialVersionUID = -2668084569793755681L; private final char[] array; private final int offset; diff --git a/exist-core/src/main/java/org/exist/util/Collations.java b/exist-core/src/main/java/org/exist/util/Collations.java index 2d03138a291..2f19103093d 100644 --- a/exist-core/src/main/java/org/exist/util/Collations.java +++ b/exist-core/src/main/java/org/exist/util/Collations.java @@ -293,7 +293,7 @@ public class Collations { logger.error(msg); throw new XPathException(expression, ErrorCodes.FOCH0002, msg); } - collator = (Collator) collatorClass.newInstance(); + collator = (Collator) collatorClass.getDeclaredConstructor().newInstance(); } catch (final Exception e) { final String msg = "The specified collator class " + uriClassName + " could not be found"; logger.error(msg); diff --git a/exist-core/src/main/java/org/exist/util/CompressedWhitespace.java b/exist-core/src/main/java/org/exist/util/CompressedWhitespace.java index 6dae46c40b4..b7f3d1a20a2 100644 --- a/exist-core/src/main/java/org/exist/util/CompressedWhitespace.java +++ b/exist-core/src/main/java/org/exist/util/CompressedWhitespace.java @@ -190,8 +190,8 @@ public CharSequence subSequence(int start, int end) { * Indicates whether some other object is "equal to" this one. */ public boolean equals(Object obj) { - if (obj instanceof CompressedWhitespace) { - return value == ((CompressedWhitespace)obj).value; + if (obj instanceof CompressedWhitespace whitespace) { + return value == whitespace.value; } return uncompress(null).equals(obj); } diff --git a/exist-core/src/main/java/org/exist/util/Configuration.java b/exist-core/src/main/java/org/exist/util/Configuration.java index 81f776dbaf8..7afcda049b8 100644 --- a/exist-core/src/main/java/org/exist/util/Configuration.java +++ b/exist-core/src/main/java/org/exist/util/Configuration.java @@ -71,7 +71,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -271,7 +270,7 @@ public Configuration(@Nullable String configFilename, Optional existHomeDi if (is != null) { LOG.info("Reading configuration from classloader"); - configFilePath = Optional.of(Paths.get(Configuration.class.getClassLoader().getResource(configFilename).toURI())); + configFilePath = Optional.of(Path.of(Configuration.class.getClassLoader().getResource(configFilename).toURI())); } } catch (final Exception e) { // EB: ignore and go forward, e.g. in case there is an absolute @@ -291,7 +290,7 @@ public Configuration(@Nullable String configFilename, Optional existHomeDi // EB: try to create existHome based on location of config file // when config file points to absolute file location - final Path absoluteConfigFile = Paths.get(configFilename); + final Path absoluteConfigFile = Path.of(configFilename); if (absoluteConfigFile.isAbsolute() && Files.exists(absoluteConfigFile) && Files.isReadable(absoluteConfigFile)) { existHome = Optional.of(absoluteConfigFile.getParent()); @@ -299,7 +298,7 @@ public Configuration(@Nullable String configFilename, Optional existHomeDi } } - Path configFile = Paths.get(configFilename); + Path configFile = Path.of(configFilename); if (!configFile.isAbsolute() && existHome.isPresent()) { @@ -1276,7 +1275,7 @@ private static Path getWebappHome(final Optional dbHome, final NodeList ca return h.getParent().toAbsolutePath(); } return h.resolve("webapp").toAbsolutePath(); - }).orElse(Paths.get("webapp").toAbsolutePath()); + }).orElse(Path.of("webapp").toAbsolutePath()); if (LOG.isDebugEnabled()) { LOG.debug("Found {} catalog uri entries.", catalogElements.getLength()); diff --git a/exist-core/src/main/java/org/exist/util/ConfigurationHelper.java b/exist-core/src/main/java/org/exist/util/ConfigurationHelper.java index 87ad4916d24..4dce2b7604d 100644 --- a/exist-core/src/main/java/org/exist/util/ConfigurationHelper.java +++ b/exist-core/src/main/java/org/exist/util/ConfigurationHelper.java @@ -28,7 +28,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import java.util.Properties; @@ -105,7 +104,7 @@ public static Optional getExistHome(final String config) { } // try user.home - final Path userHome = Paths.get(System.getProperty("user.home")); + final Path userHome = Path.of(System.getProperty("user.home")); final Path userHomeRelativeConfig = userHome.resolve(config); if (Files.isDirectory(userHome) && Files.isRegularFile(userHomeRelativeConfig)) { final Path existHome = userHomeRelativeConfig.getParent().normalize(); @@ -115,7 +114,7 @@ public static Optional getExistHome(final String config) { // try user.dir - final Path userDir = Paths.get(System.getProperty("user.dir")); + final Path userDir = Path.of(System.getProperty("user.dir")); final Path userDirRelativeConfig = userDir.resolve(config); if (Files.isDirectory(userDir) && Files.isRegularFile(userDirRelativeConfig)) { final Path existHome = userDirRelativeConfig.getParent().normalize(); @@ -129,10 +128,10 @@ public static Optional getExistHome(final String config) { try { Path existHome; if ("jar".equals(configUrl.getProtocol())) { - existHome = Paths.get(new URI(configUrl.getPath())).getParent().getParent().normalize(); + existHome = Path.of(new URI(configUrl.getPath())).getParent().getParent().normalize(); LOG.warn("{} file was found on the classpath, but inside a Jar file! Derived EXIST_HOME from Jar's parent folder: {}", config, existHome); } else { - existHome = Paths.get(configUrl.toURI()).getParent().normalize(); + existHome = Path.of(configUrl.toURI()).getParent().normalize(); if ("etc".equals(FileUtils.fileName(existHome))) { existHome = existHome.getParent().normalize(); } @@ -149,7 +148,7 @@ public static Optional getExistHome(final String config) { } public static Optional getFromSystemProperty() { - return Optional.ofNullable(System.getProperty(PROP_EXIST_CONFIGURATION_FILE)).map(Paths::get); + return Optional.ofNullable(System.getProperty(PROP_EXIST_CONFIGURATION_FILE)).map(Path::of); } /** @@ -183,7 +182,7 @@ public static Path lookup(final String path, final Optional parent) { Path p = decodeUserHome(path); if (!p.isAbsolute()) { p = parent - .orElse(getExistHome().orElse(Paths.get(System.getProperty("user.dir")))) + .orElse(getExistHome().orElse(Path.of(System.getProperty("user.dir")))) .resolve(path); } return p.normalize().toAbsolutePath(); @@ -199,9 +198,9 @@ public static Path lookup(final String path, final Optional parent) { */ public static Path decodeUserHome(final String path) { if (path != null && path.startsWith("~") && path.length() > 1) { - return Paths.get(System.getProperty("user.home")).resolve(path.substring(1)); + return Path.of(System.getProperty("user.home")).resolve(path.substring(1)); } else { - return Paths.get(path); + return Path.of(path); } } diff --git a/exist-core/src/main/java/org/exist/util/DatabaseConfigurationException.java b/exist-core/src/main/java/org/exist/util/DatabaseConfigurationException.java index 84d421286eb..95321bde329 100644 --- a/exist-core/src/main/java/org/exist/util/DatabaseConfigurationException.java +++ b/exist-core/src/main/java/org/exist/util/DatabaseConfigurationException.java @@ -21,9 +21,12 @@ */ package org.exist.util; +import java.io.Serial; + public class DatabaseConfigurationException extends Exception { - private static final long serialVersionUID = 5583749487314182182L; + @Serial + private static final long serialVersionUID = 5583749487314182182L; public DatabaseConfigurationException() { super(); diff --git a/exist-core/src/main/java/org/exist/util/DeadlockException.java b/exist-core/src/main/java/org/exist/util/DeadlockException.java index f6481ba1953..0e4d0e7d0be 100644 --- a/exist-core/src/main/java/org/exist/util/DeadlockException.java +++ b/exist-core/src/main/java/org/exist/util/DeadlockException.java @@ -21,9 +21,12 @@ */ package org.exist.util; +import java.io.Serial; + public class DeadlockException extends LockException { - private static final long serialVersionUID = -4851225988714944368L; + @Serial + private static final long serialVersionUID = -4851225988714944368L; public DeadlockException() { super(); diff --git a/exist-core/src/main/java/org/exist/util/FileUtils.java b/exist-core/src/main/java/org/exist/util/FileUtils.java index 0e6d3eadd36..20fd89d71c9 100644 --- a/exist-core/src/main/java/org/exist/util/FileUtils.java +++ b/exist-core/src/main/java/org/exist/util/FileUtils.java @@ -341,7 +341,7 @@ public static boolean mkdirsQuietly(final Path dir) { * @return The resolved path */ public static Path resolve(final Optional parent, final String child) { - return parent.map(p -> p.resolve(child)).orElse(Paths.get(child)); + return parent.map(p -> p.resolve(child)).orElse(Path.of(child)); } /** diff --git a/exist-core/src/main/java/org/exist/util/LockException.java b/exist-core/src/main/java/org/exist/util/LockException.java index fb6bb6bcdd6..4e443cdb156 100644 --- a/exist-core/src/main/java/org/exist/util/LockException.java +++ b/exist-core/src/main/java/org/exist/util/LockException.java @@ -21,12 +21,15 @@ */ package org.exist.util; +import java.io.Serial; + /** * @author wolf */ public class LockException extends Exception { - private static final long serialVersionUID = -6273549212242606084L; + @Serial + private static final long serialVersionUID = -6273549212242606084L; public LockException() { super(); diff --git a/exist-core/src/main/java/org/exist/util/MimeTable.java b/exist-core/src/main/java/org/exist/util/MimeTable.java index 9739eef9902..8bb9240eb98 100644 --- a/exist-core/src/main/java/org/exist/util/MimeTable.java +++ b/exist-core/src/main/java/org/exist/util/MimeTable.java @@ -25,7 +25,6 @@ import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -224,7 +223,7 @@ public boolean isTextContent(String mimeType) { } private String getExtension(String fileName) { - final Path path = Paths.get(fileName); + final Path path = Path.of(fileName); fileName = FileUtils.fileName(path); final int p = fileName.lastIndexOf('.'); if(p < 0 || p + 1 == fileName.length()) { diff --git a/exist-core/src/main/java/org/exist/util/ReadOnlyException.java b/exist-core/src/main/java/org/exist/util/ReadOnlyException.java index d1132c9c80f..8b53f0682a3 100644 --- a/exist-core/src/main/java/org/exist/util/ReadOnlyException.java +++ b/exist-core/src/main/java/org/exist/util/ReadOnlyException.java @@ -21,9 +21,12 @@ */ package org.exist.util; +import java.io.Serial; + public class ReadOnlyException extends Exception { - private static final long serialVersionUID = 7077941517830242672L; + @Serial + private static final long serialVersionUID = 7077941517830242672L; /** * Constructor for ReadOnlyException. diff --git a/exist-core/src/main/java/org/exist/util/SaxonConfiguration.java b/exist-core/src/main/java/org/exist/util/SaxonConfiguration.java index bd2ccd22870..16fc989cd8b 100644 --- a/exist-core/src/main/java/org/exist/util/SaxonConfiguration.java +++ b/exist-core/src/main/java/org/exist/util/SaxonConfiguration.java @@ -32,7 +32,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; @ThreadSafe @@ -158,7 +157,7 @@ static private void reportLicensedFeatures(final net.sf.saxon.Configuration conf * @return the input file, if it is absolute. a file relative to conf.xml, if the input file is relative */ private static Path resolveConfigurationFile(final Configuration existConfiguration, final String filename) { - final var configurationFile = Paths.get(filename); + final var configurationFile = Path.of(filename); if (configurationFile.isAbsolute()) { return configurationFile; } diff --git a/exist-core/src/main/java/org/exist/util/SingleInstanceConfiguration.java b/exist-core/src/main/java/org/exist/util/SingleInstanceConfiguration.java index 2b28aae8914..55d46d7308e 100644 --- a/exist-core/src/main/java/org/exist/util/SingleInstanceConfiguration.java +++ b/exist-core/src/main/java/org/exist/util/SingleInstanceConfiguration.java @@ -64,7 +64,7 @@ public SingleInstanceConfiguration(String configFilename, Optional existHo * @return the path to the configuration file */ public static Optional getPath() { - if (!_configFile.isPresent()) { + if (_configFile.isEmpty()) { final Path f = ConfigurationHelper.lookup("conf.xml"); return Optional.of(f); } @@ -80,7 +80,7 @@ public static Optional getPath() { */ public static Optional getWebappHome(){ // if existHome is not set, try to do so. - if (!_existHome.isPresent()){ + if (_existHome.isEmpty()){ _existHome = ConfigurationHelper.getExistHome(); } diff --git a/exist-core/src/main/java/org/exist/util/SwapVals.java b/exist-core/src/main/java/org/exist/util/SwapVals.java index d0187263530..663ac04b077 100644 --- a/exist-core/src/main/java/org/exist/util/SwapVals.java +++ b/exist-core/src/main/java/org/exist/util/SwapVals.java @@ -24,15 +24,14 @@ import java.util.List; /** - This class only contains static - methods which help when the values - of two positions in a array or - list-like structure must be swapped. - - Based on previous implementations - found in eXist FastQSort original - code and internet -*/ + * Utility methods which help when the values + * of two positions in an array or list-like + * structure must be swapped. + * + * Based on previous implementations found in + * eXist FastQSort original code and internet. + */ + public final class SwapVals { public final static void swap(long[] a, int i, int j) //----------------------------------------------- diff --git a/exist-core/src/main/java/org/exist/util/SyntaxException.java b/exist-core/src/main/java/org/exist/util/SyntaxException.java index a606f99e96a..349636962d2 100644 --- a/exist-core/src/main/java/org/exist/util/SyntaxException.java +++ b/exist-core/src/main/java/org/exist/util/SyntaxException.java @@ -21,6 +21,8 @@ */ package org.exist.util; +import java.io.Serial; + /** * Description of the Class * @@ -29,7 +31,8 @@ */ public class SyntaxException extends Exception { - private static final long serialVersionUID = -4603471595319223797L; + @Serial + private static final long serialVersionUID = -4603471595319223797L; /** Constructor for the PermissionDeniedException object */ public SyntaxException() { diff --git a/exist-core/src/main/java/org/exist/util/io/AbstractFilterInputStreamCache.java b/exist-core/src/main/java/org/exist/util/io/AbstractFilterInputStreamCache.java index e8a7a8d854a..5fe53b68968 100644 --- a/exist-core/src/main/java/org/exist/util/io/AbstractFilterInputStreamCache.java +++ b/exist-core/src/main/java/org/exist/util/io/AbstractFilterInputStreamCache.java @@ -43,8 +43,8 @@ public AbstractFilterInputStreamCache(InputStream src) { incrementSharedReferences(); //if src is CachingFilterInputStream also register there so it can keep track of stream which rely on cache - if(src instanceof CachingFilterInputStream) { - final FilterInputStreamCache otherCache = ((CachingFilterInputStream) src).getCache(); + if(src instanceof CachingFilterInputStream stream) { + final FilterInputStreamCache otherCache = stream.getCache(); otherCache.incrementSharedReferences(); } } diff --git a/exist-core/src/main/java/org/exist/util/io/CachingFilterInputStream.java b/exist-core/src/main/java/org/exist/util/io/CachingFilterInputStream.java index fb48f0ff715..869b47414a9 100644 --- a/exist-core/src/main/java/org/exist/util/io/CachingFilterInputStream.java +++ b/exist-core/src/main/java/org/exist/util/io/CachingFilterInputStream.java @@ -66,8 +66,8 @@ public class CachingFilterInputStream extends FilterInputStream { public CachingFilterInputStream(final InputStream inputStream) throws InstantiationException { super(null); - if (inputStream instanceof CachingFilterInputStream) { - this.cache = ((CachingFilterInputStream) inputStream).shareCache(); // must be #shareCache not #getCache() to increment references + if (inputStream instanceof CachingFilterInputStream stream) { + this.cache = stream.shareCache(); // must be #shareCache not #getCache() to increment references } else { throw new InstantiationException("Only CachingFilterInputStream are supported as InputStream"); } diff --git a/exist-core/src/main/java/org/exist/util/io/TemporaryFileManager.java b/exist-core/src/main/java/org/exist/util/io/TemporaryFileManager.java index b8043ae4d31..ebcdd8c07a6 100644 --- a/exist-core/src/main/java/org/exist/util/io/TemporaryFileManager.java +++ b/exist-core/src/main/java/org/exist/util/io/TemporaryFileManager.java @@ -30,7 +30,6 @@ import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -151,7 +150,7 @@ public void returnTemporaryFile(final Path tempFile) { * from the last time this was run */ private void cleanupOldTempFolders() { - final Path tmpDir = Paths.get(System.getProperty("java.io.tmpdir")); + final Path tmpDir = Path.of(System.getProperty("java.io.tmpdir")); try { for (final Path dir : FileUtils.list(tmpDir, path -> Files.isDirectory(path) && path.startsWith(FOLDER_PREFIX))) { final Path lockPath = dir.resolve(LOCK_FILENAME); diff --git a/exist-core/src/main/java/org/exist/util/sanity/AssertFailure.java b/exist-core/src/main/java/org/exist/util/sanity/AssertFailure.java index c1665d712d5..a42960b576f 100644 --- a/exist-core/src/main/java/org/exist/util/sanity/AssertFailure.java +++ b/exist-core/src/main/java/org/exist/util/sanity/AssertFailure.java @@ -21,6 +21,8 @@ */ package org.exist.util.sanity; +import java.io.Serial; + /** * Exception indicating a failed assertion. Used by * class {@link org.exist.util.sanity.SanityCheck} to print @@ -30,7 +32,8 @@ */ public class AssertFailure extends RuntimeException { - private static final long serialVersionUID = -4753385398634599386L; + @Serial + private static final long serialVersionUID = -4753385398634599386L; public AssertFailure() { super(); diff --git a/exist-core/src/main/java/org/exist/util/serializer/ReceiverToSAX.java b/exist-core/src/main/java/org/exist/util/serializer/ReceiverToSAX.java index 836064fb08c..7e07675f898 100644 --- a/exist-core/src/main/java/org/exist/util/serializer/ReceiverToSAX.java +++ b/exist-core/src/main/java/org/exist/util/serializer/ReceiverToSAX.java @@ -52,8 +52,8 @@ public ReceiverToSAX(final ContentHandler handler) { super(); this.contentHandler = handler; - if (handler instanceof LexicalHandler) { - lexicalHandler = (LexicalHandler) handler; + if (handler instanceof LexicalHandler lexicalHandler1) { + lexicalHandler = lexicalHandler1; } } diff --git a/exist-core/src/main/java/org/exist/validation/resolver/SearchResourceResolver.java b/exist-core/src/main/java/org/exist/validation/resolver/SearchResourceResolver.java index 61f80070a36..a79a7aeb63d 100644 --- a/exist-core/src/main/java/org/exist/validation/resolver/SearchResourceResolver.java +++ b/exist-core/src/main/java/org/exist/validation/resolver/SearchResourceResolver.java @@ -183,12 +183,12 @@ public XMLInputSource resolveEntity(final XMLResourceIdentifier xri) throws XNIE } private String getXriDetails(final XMLResourceIdentifier xrid) { - return String.format("PublicId='%s' BaseSystemId='%s' ExpandedSystemId='%s' LiteralSystemId='%s' Namespace='%s' ", + return "PublicId='%s' BaseSystemId='%s' ExpandedSystemId='%s' LiteralSystemId='%s' Namespace='%s' ".formatted( xrid.getPublicId(), xrid.getBaseSystemId(), xrid.getExpandedSystemId(), xrid.getLiteralSystemId(), xrid.getNamespace()); } private String getXisDetails(final XMLInputSource xis) { - return String.format("PublicId='%s' SystemId='%s' BaseSystemId='%s' Encoding='%s' ", + return "PublicId='%s' SystemId='%s' BaseSystemId='%s' Encoding='%s' ".formatted( xis.getPublicId(), xis.getSystemId(), xis.getBaseSystemId(), xis.getEncoding()); } diff --git a/exist-core/src/main/java/org/exist/webstart/JnlpJarFiles.java b/exist-core/src/main/java/org/exist/webstart/JnlpJarFiles.java index 585dccc95fa..9aa06bc3db1 100644 --- a/exist-core/src/main/java/org/exist/webstart/JnlpJarFiles.java +++ b/exist-core/src/main/java/org/exist/webstart/JnlpJarFiles.java @@ -24,7 +24,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Comparator; import java.util.HashMap; import java.util.List; @@ -95,7 +94,7 @@ public class JnlpJarFiles { private Path getJarFromLocation(final Path folder, final String jarFileBaseName) { final String fileToFind = folder.normalize().toAbsolutePath().toString() + java.io.File.separatorChar + jarFileBaseName + ".jar"; final String resolvedFile = jarFileResolver.getResolvedFileName(fileToFind); - final Path jar = Paths.get(resolvedFile).normalize(); + final Path jar = Path.of(resolvedFile).normalize(); if (Files.exists(jar)) { LOGGER.debug("Found match: {} for file pattern: {}", resolvedFile, fileToFind); return jar; @@ -164,7 +163,7 @@ public Path getJarFile(final String key) { private Path getJarPackGz(final Path jarName) { final String path = jarName.toAbsolutePath() + ".pack.gz"; - final Path pkgz = Paths.get(path); + final Path pkgz = Path.of(path); if (Files.exists(pkgz)) { return pkgz; diff --git a/exist-core/src/main/java/org/exist/webstart/JnlpServlet.java b/exist-core/src/main/java/org/exist/webstart/JnlpServlet.java index 20492450d34..b3c5194c7f3 100644 --- a/exist-core/src/main/java/org/exist/webstart/JnlpServlet.java +++ b/exist-core/src/main/java/org/exist/webstart/JnlpServlet.java @@ -24,10 +24,10 @@ import java.io.EOFException; import java.io.IOException; +import java.io.Serial; import java.net.SocketException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import java.util.function.Supplier; import jakarta.servlet.ServletException; @@ -45,6 +45,7 @@ */ public class JnlpServlet extends HttpServlet { + @Serial private static final long serialVersionUID = 1238966115449192258L; private static final Logger LOGGER = LogManager.getLogger(JnlpServlet.class); @@ -59,17 +60,17 @@ public void init() throws ServletException { LOGGER.info("Initializing JNLP servlet"); final Optional libDir = or( - Optional.ofNullable(System.getProperty("app.repo")).map(Paths::get).filter(Files::exists), + Optional.ofNullable(System.getProperty("app.repo")).map(Path::of).filter(Files::exists), (Supplier>) () -> or ( // using explicit type declaration in order to circumvent AspectJ compiler bug, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=553623 - Optional.ofNullable(System.getProperty("app.home")).map(Paths::get).map(p -> p.resolve("lib")).filter(Files::exists), + Optional.ofNullable(System.getProperty("app.home")).map(Path::of).map(p -> p.resolve("lib")).filter(Files::exists), (Supplier>) () -> or ( // using explicit type declaration in order to circumvent AspectJ compiler bug, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=553623 - Optional.ofNullable(System.getProperty("exist.home")).map(Paths::get).map(p -> p.resolve("lib")).filter(Files::exists), - () -> Optional.ofNullable(getServletContext().getRealPath("/")).map(Paths::get).map(p -> p.resolve("lib")).filter(Files::exists) + Optional.ofNullable(System.getProperty("exist.home")).map(Path::of).map(p -> p.resolve("lib")).filter(Files::exists), + () -> Optional.ofNullable(getServletContext().getRealPath("/")).map(Path::of).map(p -> p.resolve("lib")).filter(Files::exists) ) ) ); - if (!libDir.isPresent()) { + if (libDir.isEmpty()) { final String txt = "Could not locate lib directory. Webstart is not available."; LOGGER.error(txt); throw new ServletException(txt); diff --git a/exist-core/src/main/java/org/exist/webstart/JnlpWriter.java b/exist-core/src/main/java/org/exist/webstart/JnlpWriter.java index d3894e4f740..cf5c12257dc 100644 --- a/exist-core/src/main/java/org/exist/webstart/JnlpWriter.java +++ b/exist-core/src/main/java/org/exist/webstart/JnlpWriter.java @@ -80,7 +80,7 @@ void writeJnlpXML(JnlpJarFiles jnlpFiles, HttpServletRequest request, for (final Path jar : jnlpFiles.getAllWebstartJars()) { counter++; // debugging if (jar == null || !Files.exists(jar)) { - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, String.format("Missing Jar file! (%s)", counter)); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing Jar file! (%s)".formatted(counter)); return; } } @@ -275,7 +275,7 @@ void sendImage(JnlpJarFiles jf, String filename, HttpServletResponse response) t try(final InputStream imageInputStream = this.getClass().getResourceAsStream("resources/"+filename)) { if (imageInputStream == null) { - response.sendError(HttpServletResponse.SC_NOT_FOUND, String.format("Image file '%s' not found.", filename)); + response.sendError(HttpServletResponse.SC_NOT_FOUND, "Image file '%s' not found.".formatted(filename)); return; } diff --git a/exist-core/src/main/java/org/exist/webstart/LatestFileResolver.java b/exist-core/src/main/java/org/exist/webstart/LatestFileResolver.java index 56e2113fcc1..c43b8ef11ca 100644 --- a/exist-core/src/main/java/org/exist/webstart/LatestFileResolver.java +++ b/exist-core/src/main/java/org/exist/webstart/LatestFileResolver.java @@ -28,7 +28,6 @@ import java.io.File; import java.io.IOException; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -75,7 +74,7 @@ public String getResolvedFileName(final String filename) { // Directory that should contain our jar. final String containerDirName = uptoToken.substring(0, uptoToken.lastIndexOf(File.separatorChar)); - final Path containerDir = Paths.get(containerDirName); + final Path containerDir = Path.of(containerDirName); final String artifactId = Pattern.quote(uptoToken.substring(uptoToken.lastIndexOf(File.separatorChar) + 1)); final String suffix = Pattern.quote(fileinfo[1]); diff --git a/exist-core/src/main/java/org/exist/xmldb/AbstractLocal.java b/exist-core/src/main/java/org/exist/xmldb/AbstractLocal.java index b9dab92599e..08d50e8e1d8 100644 --- a/exist-core/src/main/java/org/exist/xmldb/AbstractLocal.java +++ b/exist-core/src/main/java/org/exist/xmldb/AbstractLocal.java @@ -68,8 +68,8 @@ protected XmldbURI resolve(final XmldbURI name) { protected XmldbURI getCollectionUri(final DBBroker broker, final Txn transaction, final Collection collection) throws XMLDBException { final String name; - if(collection instanceof LocalCollection) { - name = ((LocalCollection)collection).getName(broker, transaction); + if(collection instanceof LocalCollection localCollection) { + name = localCollection.getName(broker, transaction); } else { name = collection.getName(); } diff --git a/exist-core/src/main/java/org/exist/xmldb/AbstractRemoteResource.java b/exist-core/src/main/java/org/exist/xmldb/AbstractRemoteResource.java index 7e9a5d19503..8d9120d4ba0 100644 --- a/exist-core/src/main/java/org/exist/xmldb/AbstractRemoteResource.java +++ b/exist-core/src/main/java/org/exist/xmldb/AbstractRemoteResource.java @@ -170,32 +170,40 @@ protected boolean setContentInternal(final Object value) throws XMLDBException { boolean wasSet = false; try { freeResources(); - if (value instanceof ContentFile) { - contentFile = (ContentFile)value; - setExtendendContentLength(contentFile.size()); - wasSet = true; - } else if (value instanceof Path) { - file = (Path) value; - setExtendendContentLength(Files.size(file)); - wasSet = true; - } else if (value instanceof java.io.File) { - file = ((java.io.File) value).toPath(); - setExtendendContentLength(Files.size(file)); - wasSet = true; - } else if (value instanceof InputSource) { - inputSource = (InputSource) value; - if (inputSource instanceof EXistInputSource) { - setExtendendContentLength(((EXistInputSource) inputSource).getByteStreamLength()); + switch (value) { + case ContentFile contentFile1 -> { + contentFile = contentFile1; + setExtendendContentLength(contentFile.size()); + wasSet = true; } - wasSet = true; - } else if (value instanceof byte[]) { - contentFile = ByteArrayContent.of((byte[]) value); - setExtendendContentLength(contentFile.size()); - wasSet = true; - } else if (value instanceof String) { - contentFile = ByteArrayContent.of((String) value); - setExtendendContentLength(contentFile.size()); - wasSet = true; + case Path path1 -> { + file = path1; + setExtendendContentLength(Files.size(file)); + wasSet = true; + } + case java.io.File file1 -> { + file = file1.toPath(); + setExtendendContentLength(Files.size(file)); + wasSet = true; + } + case InputSource source1 -> { + inputSource = source1; + if (inputSource instanceof EXistInputSource source) { + setExtendendContentLength(source.getByteStreamLength()); + } + wasSet = true; + } + case byte[] bytes -> { + contentFile = ByteArrayContent.of(bytes); + setExtendendContentLength(contentFile.size()); + wasSet = true; + } + case String string -> { + contentFile = ByteArrayContent.of(string); + setExtendendContentLength(contentFile.size()); + wasSet = true; + } + default -> {} } } catch (final IOException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e); @@ -344,10 +352,10 @@ protected final int getInMemorySize(Properties properties) { protected static InputStream getAnyStream(final Object obj) throws XMLDBException { - if (obj instanceof String) { - return new UnsynchronizedByteArrayInputStream(((String) obj).getBytes(UTF_8)); - } else if (obj instanceof byte[]) { - return new UnsynchronizedByteArrayInputStream((byte[]) obj); + if (obj instanceof String string) { + return new UnsynchronizedByteArrayInputStream(string.getBytes(UTF_8)); + } else if (obj instanceof byte[] bytes) { + return new UnsynchronizedByteArrayInputStream(bytes); } else { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "don't know how to handle value of type " + obj.getClass().getName()); } @@ -446,15 +454,13 @@ protected long getStreamLengthInternal(final Object obj) final long retval; if (file != null) { retval = FileUtils.sizeQuietly(file); - } else if (inputSource != null && inputSource instanceof EXistInputSource) { - retval = ((EXistInputSource) inputSource).getByteStreamLength(); + } else if (inputSource != null && inputSource instanceof EXistInputSource source) { + retval = source.getByteStreamLength(); } else if (obj != null) { - if (obj instanceof String) { - retval = ((String) obj).getBytes(UTF_8).length; - } else if (obj instanceof byte[]) { - retval = ((byte[]) obj).length; - } else { - throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "don't know how to handle value of type " + obj.getClass().getName()); + switch (obj) { + case String string -> retval = string.getBytes(UTF_8).length; + case byte[] bytes -> retval = bytes.length; + default -> throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "don't know how to handle value of type " + obj.getClass().getName()); } } else if (contentFile != null) { retval = contentFile.size(); @@ -465,8 +471,8 @@ protected long getStreamLengthInternal(final Object obj) final Map table = (Map) collection.execute("describeResource", params); if (table.containsKey("content-length-64bit")) { final Object o = table.get("content-length-64bit"); - if (o instanceof Long) { - retval = ((Long) o); + if (o instanceof Long long1) { + retval = long1; } else { retval = Long.parseLong((String) o); } diff --git a/exist-core/src/main/java/org/exist/xmldb/DatabaseImpl.java b/exist-core/src/main/java/org/exist/xmldb/DatabaseImpl.java index 783fb5b0d7f..8dccd8729ac 100644 --- a/exist-core/src/main/java/org/exist/xmldb/DatabaseImpl.java +++ b/exist-core/src/main/java/org/exist/xmldb/DatabaseImpl.java @@ -45,7 +45,7 @@ import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; -import java.nio.file.Paths; +import java.nio.file.Path; import java.util.HashMap; import java.util.Map; import java.util.Optional; @@ -116,10 +116,10 @@ private void configure(final String instanceName) throws XMLDBException { try { final Configuration config = new Configuration(configuration, Optional.empty()); if (dataDir != null) { - config.setProperty(BrokerPool.PROPERTY_DATA_DIR, Paths.get(dataDir)); + config.setProperty(BrokerPool.PROPERTY_DATA_DIR, Path.of(dataDir)); } if (journalDir != null) { - config.setProperty(Journal.PROPERTY_RECOVERY_JOURNAL_DIR, Paths.get(journalDir)); + config.setProperty(Journal.PROPERTY_RECOVERY_JOURNAL_DIR, Path.of(journalDir)); } BrokerPool.configure(instanceName, 1, 5, config); diff --git a/exist-core/src/main/java/org/exist/xmldb/LocalBinaryResource.java b/exist-core/src/main/java/org/exist/xmldb/LocalBinaryResource.java index 34558b42d36..4df05030953 100644 --- a/exist-core/src/main/java/org/exist/xmldb/LocalBinaryResource.java +++ b/exist-core/src/main/java/org/exist/xmldb/LocalBinaryResource.java @@ -247,8 +247,8 @@ public long getStreamLength() throws XMLDBException { if(file != null) { retval = FileUtils.sizeQuietly(file); - } else if(inputSource != null && inputSource instanceof EXistInputSource) { - retval = ((EXistInputSource)inputSource).getByteStreamLength(); + } else if(inputSource != null && inputSource instanceof EXistInputSource source) { + retval = source.getByteStreamLength(); } else if(rawData != null) { retval = rawData.length; } else if(binaryValue != null) { diff --git a/exist-core/src/main/java/org/exist/xmldb/LocalResourceSet.java b/exist-core/src/main/java/org/exist/xmldb/LocalResourceSet.java index 97370bfd67a..973c4d386bf 100644 --- a/exist-core/src/main/java/org/exist/xmldb/LocalResourceSet.java +++ b/exist-core/src/main/java/org/exist/xmldb/LocalResourceSet.java @@ -185,14 +185,14 @@ public Resource getResource(final long pos) throws XMLDBException { coll.setProperties(outputProperties); } res = new LocalXMLResource(user, brokerPool, coll, p); - } else if (r instanceof Node) { + } else if (r instanceof Node node) { res = new LocalXMLResource(user, brokerPool, collection, XmldbURI.EMPTY_URI); - ((LocalXMLResource)res).setContentAsDOM((Node) r); + ((LocalXMLResource)res).setContentAsDOM(node); } else if (r instanceof AtomicValue) { if(r instanceof BinaryValue) { final XmldbURI docId; - if(r instanceof Base64BinaryDocument) { - docId = Optional.ofNullable(((Base64BinaryDocument)r).getUrl()).filter(s -> !s.isEmpty()).map(XmldbURI::create).orElse(XmldbURI.EMPTY_URI); + if(r instanceof Base64BinaryDocument document) { + docId = Optional.ofNullable(document.getUrl()).filter(s -> !s.isEmpty()).map(XmldbURI::create).orElse(XmldbURI.EMPTY_URI); } else { docId = XmldbURI.EMPTY_URI; } @@ -201,8 +201,8 @@ public Resource getResource(final long pos) throws XMLDBException { res = new LocalXMLResource(user, brokerPool, collection, XmldbURI.EMPTY_URI); } res.setContent(r); - } else if (r instanceof Resource) { - return (Resource)r; + } else if (r instanceof Resource resource) { + return resource; } res.setProperties(outputProperties); diff --git a/exist-core/src/main/java/org/exist/xmldb/LocalRestoreService.java b/exist-core/src/main/java/org/exist/xmldb/LocalRestoreService.java index ed24b631fb7..7dfc20bcede 100644 --- a/exist-core/src/main/java/org/exist/xmldb/LocalRestoreService.java +++ b/exist-core/src/main/java/org/exist/xmldb/LocalRestoreService.java @@ -31,7 +31,8 @@ import org.xmldb.api.base.XMLDBException; import javax.annotation.Nullable; -import java.nio.file.Paths; + +import java.nio.file.Path; public class LocalRestoreService extends AbstractLocalService implements EXistRestoreService { @@ -55,7 +56,7 @@ public void restore(final String backup, final @Nullable String newAdminPassword final Restore restore = new Restore(); withDb((broker, transaction) -> { try { - restore.restore(broker, transaction, newAdminPassword, Paths.get(backup), + restore.restore(broker, transaction, newAdminPassword, Path.of(backup), new RestoreListenerAdapter(restoreListener), overwriteApps); } catch (final SAXException e) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, e.getMessage()); diff --git a/exist-core/src/main/java/org/exist/xmldb/LocalXMLResource.java b/exist-core/src/main/java/org/exist/xmldb/LocalXMLResource.java index 5ed3a1b9b43..82dc9948480 100644 --- a/exist-core/src/main/java/org/exist/xmldb/LocalXMLResource.java +++ b/exist-core/src/main/java/org/exist/xmldb/LocalXMLResource.java @@ -293,9 +293,9 @@ private String serialize(final DBBroker broker, final ConsumerE { - ((NodeImpl)root).expand(); + impl.expand(); return null; }); } @@ -327,7 +327,7 @@ public Node getContentAsDOM() throws XMLDBException { */ private Node exportInternalNode(final Node node) { final Optional> domClazz = getW3cNodeInterface(node.getClass()); - if(!domClazz.isPresent()) { + if(domClazz.isEmpty()) { throw new IllegalArgumentException("Provided node does not implement org.w3c.dom"); } @@ -415,8 +415,8 @@ public Object invoke(final Object proxy, final Method method, final Object[] arg } else if("getNodeId".equals(method.getName())) { if (proxy instanceof StoredNodeIdentity && (args == null || args.length == 0) - && node instanceof StoredNode) { - domResult = Optional.of(((StoredNode) node).getNodeId()); + && node instanceof StoredNode storedNode) { + domResult = Optional.of(storedNode.getNodeId()); } else if (proxy instanceof MemtreeNodeIdentity && (args == null || args.length == 0) && node instanceof NodeImpl memtreeNode) { diff --git a/exist-core/src/main/java/org/exist/xmldb/LocalXPathQueryService.java b/exist-core/src/main/java/org/exist/xmldb/LocalXPathQueryService.java index 02c92b3def2..ab3ee8e7521 100644 --- a/exist-core/src/main/java/org/exist/xmldb/LocalXPathQueryService.java +++ b/exist-core/src/main/java/org/exist/xmldb/LocalXPathQueryService.java @@ -135,9 +135,9 @@ public ResourceSet query(final XMLResource res, final String query, final String final Node n = ((LocalXMLResource) res).root; return withDb((broker, transaction) -> { - if (n != null && n instanceof org.exist.dom.memtree.NodeImpl) { + if (n != null && n instanceof org.exist.dom.memtree.NodeImpl impl) { final XmldbURI[] docs = new XmldbURI[]{ getCollectionUri(broker, transaction, res.getParentCollection()) }; - return doQuery(broker, transaction, query, docs, (org.exist.dom.memtree.NodeImpl) n, sortBy); + return doQuery(broker, transaction, query, docs, impl, sortBy); } final NodeProxy node = ((LocalXMLResource) res).getNode(broker, transaction); if (node == null) { @@ -367,10 +367,10 @@ protected void setupContext(final Source source, final XQueryContext context) th context.setModuleLoadPath(moduleLoadPath); } else if (source != null) { String modulePath = null; - if (source instanceof DBSource) { - modulePath = ((DBSource) source).getDocumentPath().removeLastSegment().toString(); - } else if (source instanceof FileSource) { - modulePath = ((FileSource) source).getPath().getParent().toString(); + if (source instanceof DBSource bSource) { + modulePath = bSource.getDocumentPath().removeLastSegment().toString(); + } else if (source instanceof FileSource fileSource) { + modulePath = fileSource.getPath().getParent().toString(); } if (modulePath != null) { diff --git a/exist-core/src/main/java/org/exist/xmldb/MapResourceSet.java b/exist-core/src/main/java/org/exist/xmldb/MapResourceSet.java index c0826e13962..fa9178c6e35 100644 --- a/exist-core/src/main/java/org/exist/xmldb/MapResourceSet.java +++ b/exist-core/src/main/java/org/exist/xmldb/MapResourceSet.java @@ -146,8 +146,8 @@ public Resource getResource(final long pos) throws XMLDBException { return null; } final Object r = resourcesVector.get((int) pos); - if (r instanceof Resource) { - return (Resource) r; + if (r instanceof Resource resource) { + return resource; } return null; } diff --git a/exist-core/src/main/java/org/exist/xmldb/RemoteBinaryResource.java b/exist-core/src/main/java/org/exist/xmldb/RemoteBinaryResource.java index 9d349c26933..2751d3f4025 100644 --- a/exist-core/src/main/java/org/exist/xmldb/RemoteBinaryResource.java +++ b/exist-core/src/main/java/org/exist/xmldb/RemoteBinaryResource.java @@ -100,8 +100,8 @@ protected String getStreamSymbolicPath() { if (file != null) { retval = file.toAbsolutePath().toString(); - } else if (inputSource != null && inputSource instanceof EXistInputSource) { - retval = ((EXistInputSource) inputSource).getSymbolicPath(); + } else if (inputSource != null && inputSource instanceof EXistInputSource source) { + retval = source.getSymbolicPath(); } return retval; diff --git a/exist-core/src/main/java/org/exist/xmldb/RemoteCollection.java b/exist-core/src/main/java/org/exist/xmldb/RemoteCollection.java index 1a0a712dc88..b7607c17a08 100644 --- a/exist-core/src/main/java/org/exist/xmldb/RemoteCollection.java +++ b/exist-core/src/main/java/org/exist/xmldb/RemoteCollection.java @@ -397,8 +397,8 @@ public Resource getResource(final String name) throws XMLDBException { long contentLen = 0; if (hash.containsKey("content-length-64bit")) { final Object o = hash.get("content-length-64bit"); - if (o instanceof Long) { - contentLen = (Long) o; + if (o instanceof Long long1) { + contentLen = long1; } else { contentLen = Long.parseLong((String) o); } @@ -433,10 +433,10 @@ public Resource getResource(final String name) throws XMLDBException { } private Instant toInstant(Object date) { - if (date instanceof Instant) { - return (Instant)date; - } else if (date instanceof Date) { - return ((Date)date).toInstant(); + if (date instanceof Instant instant) { + return instant; + } else if (date instanceof Date date1) { + return date1.toInstant(); } return null; } @@ -472,8 +472,8 @@ public void storeResource(final Resource res) throws XMLDBException { @Override public void storeResource(final Resource res, final Instant a, final Instant b) throws XMLDBException { - final Object content = (res instanceof ExtendedResource) - ? ((ExtendedResource) res).getExtendedContent() + final Object content = (res instanceof ExtendedResource er) + ? er.getExtendedContent() : res.getContent(); if (content instanceof Path || content instanceof File || content instanceof InputSource) { @@ -496,9 +496,9 @@ public void storeResource(final Resource res, final Instant a, final Instant b) default -> -1; }; - if (res instanceof AbstractRemoteResource) { - ((AbstractRemoteResource) res).dateCreated = a; - ((AbstractRemoteResource) res).dateModified = b; + if (res instanceof AbstractRemoteResource resource) { + resource.dateCreated = a; + resource.dateModified = b; } if (!BINARY_RESOURCE.equals(res.getResourceType()) && fileLength != -1 @@ -559,9 +559,9 @@ private void uploadAndStore(final Resource res) throws XMLDBException { InputStream is = null; String descString = ""; try { - if (res instanceof RemoteBinaryResource) { - is = ((RemoteBinaryResource) res).getStreamContent(); - descString = ((RemoteBinaryResource) res).getStreamSymbolicPath(); + if (res instanceof RemoteBinaryResource resource) { + is = resource.getStreamContent(); + descString = resource.getStreamSymbolicPath(); } else { final Object content = res.getContent(); switch (content) { @@ -577,8 +577,8 @@ private void uploadAndStore(final Resource res) throws XMLDBException { } case InputSource inputSource -> { is = inputSource.getByteStream(); - if (content instanceof EXistInputSource) { - descString = ((EXistInputSource) content).getSymbolicPath(); + if (content instanceof EXistInputSource source) { + descString = source.getSymbolicPath(); } } case String s -> @@ -590,8 +590,8 @@ private void uploadAndStore(final Resource res) throws XMLDBException { final byte[] chunk; if (res instanceof ExtendedResource) { - if(res instanceof AbstractRemoteResource) { - final long contentLen = ((AbstractRemoteResource)res).getContentLength(); + if(res instanceof AbstractRemoteResource resource) { + final long contentLen = resource.getContentLength(); if (contentLen != -1) { // content length is known chunk = new byte[(int)Math.min(contentLen, MAX_UPLOAD_CHUNK)]; diff --git a/exist-core/src/main/java/org/exist/xmldb/RemoteResourceIterator.java b/exist-core/src/main/java/org/exist/xmldb/RemoteResourceIterator.java index a246737f727..887649e9e13 100644 --- a/exist-core/src/main/java/org/exist/xmldb/RemoteResourceIterator.java +++ b/exist-core/src/main/java/org/exist/xmldb/RemoteResourceIterator.java @@ -71,7 +71,7 @@ public Resource nextResource() throws XMLDBException { if (resources.get(pos) instanceof List) { // node final List v = (List) resources.get(pos++); - final String doc = v.get(0); + final String doc = v.getFirst(); final String s_id = v.get(1); final List params = new ArrayList<>(); diff --git a/exist-core/src/main/java/org/exist/xmldb/RemoteRestoreService.java b/exist-core/src/main/java/org/exist/xmldb/RemoteRestoreService.java index dce7c02f0c6..ed2ee086f91 100644 --- a/exist-core/src/main/java/org/exist/xmldb/RemoteRestoreService.java +++ b/exist-core/src/main/java/org/exist/xmldb/RemoteRestoreService.java @@ -33,7 +33,10 @@ import javax.annotation.Nullable; import java.io.*; -import java.nio.file.*; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.List; @@ -72,7 +75,7 @@ public String getVersion() { @Override public void restore(final String backup, @Nullable final String newAdminPassword, final RestoreServiceTaskListener restoreListener, final boolean overwriteApps) throws XMLDBException { - final Path backupPath = Paths.get(backup).normalize().toAbsolutePath(); + final Path backupPath = Path.of(backup).normalize().toAbsolutePath(); if (!Files.exists(backupPath)) { throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "Backup does not exist: " + backupPath); } diff --git a/exist-core/src/main/java/org/exist/xmldb/RemoteXMLResource.java b/exist-core/src/main/java/org/exist/xmldb/RemoteXMLResource.java index b6c5a083b17..097dc47605b 100644 --- a/exist-core/src/main/java/org/exist/xmldb/RemoteXMLResource.java +++ b/exist-core/src/main/java/org/exist/xmldb/RemoteXMLResource.java @@ -182,8 +182,8 @@ public Object getContent() throws XMLDBException { } final Object res = super.getContent(); if (res != null) { - if (res instanceof byte[]) { - return new String((byte[]) res, UTF_8); + if (res instanceof byte[] bytes) { + return new String(bytes, UTF_8); } else { return res; @@ -280,13 +280,10 @@ public Object getExtendedContent() throws XMLDBException { public void setContent(final Object value) throws XMLDBException { content = null; if (!super.setContentInternal(value)) { - if (value instanceof String) { - content = (String) value; - } else if (value instanceof byte[]) { - content = new String((byte[]) value, UTF_8); - - } else { - content = value.toString(); + switch (value) { + case String string -> content = string; + case byte[] bytes -> content = new String(bytes, UTF_8); + default -> content = value.toString(); } } } diff --git a/exist-core/src/main/java/org/exist/xmldb/RemoteXPathQueryService.java b/exist-core/src/main/java/org/exist/xmldb/RemoteXPathQueryService.java index 76477f02593..54b5be6685c 100644 --- a/exist-core/src/main/java/org/exist/xmldb/RemoteXPathQueryService.java +++ b/exist-core/src/main/java/org/exist/xmldb/RemoteXPathQueryService.java @@ -269,7 +269,7 @@ public ResourceSet queryResource(final String resource, final String query) thro return query((XMLResource) res, query); } finally { - if (res!=null && res instanceof AbstractRemoteResource) ((AbstractRemoteResource)res).freeResources(); + if (res!=null && res instanceof AbstractRemoteResource remoteResource) remoteResource.freeResources(); } } diff --git a/exist-core/src/main/java/org/exist/xmldb/XmldbURI.java b/exist-core/src/main/java/org/exist/xmldb/XmldbURI.java index 2d87eb6a3f3..62e8ea93fce 100644 --- a/exist-core/src/main/java/org/exist/xmldb/XmldbURI.java +++ b/exist-core/src/main/java/org/exist/xmldb/XmldbURI.java @@ -615,17 +615,17 @@ public static String recoverPseudoURIs(final String pseudoURI) throws URISyntaxE } public boolean equals(final Object ob) { - if (ob instanceof XmldbURI) { - return getXmldbURI().equals(((XmldbURI) ob).getXmldbURI()); + if (ob instanceof XmldbURI rI) { + return getXmldbURI().equals(rI.getXmldbURI()); } if (ob instanceof URI) { return getXmldbURI().equals(ob); } - if (ob instanceof String) { + if (ob instanceof String string) { try { - return getXmldbURI().equals(new URI((String) ob)); + return getXmldbURI().equals(new URI(string)); } catch (final URISyntaxException e) { return false; } diff --git a/exist-core/src/main/java/org/exist/xmlrpc/ACEAiderParser.java b/exist-core/src/main/java/org/exist/xmlrpc/ACEAiderParser.java index d67494525ea..af8d4fc4381 100644 --- a/exist-core/src/main/java/org/exist/xmlrpc/ACEAiderParser.java +++ b/exist-core/src/main/java/org/exist/xmlrpc/ACEAiderParser.java @@ -130,14 +130,14 @@ public void startElement(final String uri, final String localName, final String private static ACEAider toAceAider(final List list) throws SAXException { if (list.size() != 4) { - throw new SAXException("Inavlis list size for ACEAider"); + throw new SAXException("Invalid list size for ACEAider"); } Object object = list.getFirst(); final ACE_ACCESS_TYPE aceAccessType; - if (object instanceof String) { + if (object instanceof String s) { try { - aceAccessType = ACE_ACCESS_TYPE.valueOf((String) object); + aceAccessType = ACE_ACCESS_TYPE.valueOf(s); } catch (final IllegalArgumentException e) { throw new SAXException(e); } @@ -147,9 +147,9 @@ private static ACEAider toAceAider(final List list) throws SAXException object = list.get(1); final ACE_TARGET aceTarget; - if (object instanceof String) { + if (object instanceof String s1) { try { - aceTarget = ACE_TARGET.valueOf((String) object); + aceTarget = ACE_TARGET.valueOf(s1); } catch (final IllegalArgumentException e) { throw new SAXException(e); } @@ -159,16 +159,16 @@ private static ACEAider toAceAider(final List list) throws SAXException object = list.get(2); final String aceWho; - if (object instanceof String) { - aceWho = (String) object; + if (object instanceof String string) { + aceWho = string; } else { throw new SAXException("Expected String"); } object = list.get(3); final int aceMode; - if (object instanceof Integer) { - aceMode = (Integer) object; + if (object instanceof Integer integer) { + aceMode = integer; } else { throw new SAXException("Expected Integer"); } diff --git a/exist-core/src/main/java/org/exist/xmlrpc/QueryResult.java b/exist-core/src/main/java/org/exist/xmlrpc/QueryResult.java index 4465f00d83f..890a6df96df 100644 --- a/exist-core/src/main/java/org/exist/xmlrpc/QueryResult.java +++ b/exist-core/src/main/java/org/exist/xmlrpc/QueryResult.java @@ -82,9 +82,9 @@ protected void doClose() { if (result != null) { //cleanup any binary values - if (result instanceof BinaryValue) { + if (result instanceof BinaryValue value) { try { - ((BinaryValue) result).close(); + value.close(); } catch (final IOException ioe) { LOG.warn("Unable to cleanup BinaryValue: {}", result.hashCode(), ioe); } diff --git a/exist-core/src/main/java/org/exist/xmlrpc/RpcConnection.java b/exist-core/src/main/java/org/exist/xmlrpc/RpcConnection.java index 11512c9005f..db5c94e948b 100644 --- a/exist-core/src/main/java/org/exist/xmlrpc/RpcConnection.java +++ b/exist-core/src/main/java/org/exist/xmlrpc/RpcConnection.java @@ -104,7 +104,10 @@ import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; -import java.nio.file.*; +import java.nio.file.Files; +import java.nio.file.OpenOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.Lock; @@ -595,8 +598,8 @@ public Map getContentDigest(final String path, final String dige try { final DigestType digestType = DigestType.forCommonName(digestAlgorithm); final MessageDigest messageDigest = this.readDocument(XmldbURI.xmldbUriFor(path)).apply((document, broker, transaction) -> { - if (document instanceof BinaryDocument) { - return broker.getBinaryResourceContentDigest(transaction, (BinaryDocument) document, digestType); + if (document instanceof BinaryDocument binaryDocument) { + return broker.getBinaryResourceContentDigest(transaction, binaryDocument, digestType); } else { throw new EXistException("Only supported for binary documents"); } @@ -937,7 +940,7 @@ public boolean sync() { @Override public boolean dataBackup(final String dest) { - factory.getBrokerPool().triggerSystemTask(new DataBackup(Paths.get(dest))); + factory.getBrokerPool().triggerSystemTask(new DataBackup(Path.of(dest))); return true; } @@ -1485,7 +1488,7 @@ private boolean parseLocal(final String localFile, final XmldbURI docUri, final // As this file can be a non-temporal one, we should not // blindly erase it! - final Path path = Paths.get(localFile); + final Path path = Path.of(localFile); if (!Files.isReadable(path)) { // NOTE: early release of Collection lock inline with Asymmetrical Locking scheme collection.close(); @@ -1954,8 +1957,8 @@ private Map queryResultToTypedRpcResponse(final long startTime, private @Nullable Map nodeMap(final Item item) { final Map result; - if (item instanceof NodeValue && - ((NodeValue)item).getImplementationType() == NodeValue.PERSISTENT_NODE) { + if (item instanceof NodeValue value && + value.getImplementationType() == NodeValue.PERSISTENT_NODE) { final NodeProxy p = (NodeProxy) item; result = new HashMap<>(); @@ -3099,7 +3102,7 @@ public void inc() { @Override public byte[] getDocumentChunk(final String name, final int start, final int len) throws EXistException, PermissionDeniedException, IOException { - final Path file = Paths.get(System.getProperty("java.io.tmpdir")).resolve(name); + final Path file = Path.of(System.getProperty("java.io.tmpdir")).resolve(name); if (!Files.isReadable(file)) { throw new EXistException("unable to read file " + name); } @@ -3249,7 +3252,7 @@ public boolean backup(final String userbackup, final String password, final Backup backup = new Backup( userbackup, password, - Paths.get(destcollection + "-backup"), + Path.of(destcollection + "-backup"), XmldbURI.xmldbUriFor(XmldbURI.EMBEDDED_SERVER_URI.toString() + collection)); backup.backup(false, null); diff --git a/exist-core/src/main/java/org/exist/xmlrpc/RpcServlet.java b/exist-core/src/main/java/org/exist/xmlrpc/RpcServlet.java index fcd039bec03..2bfcf98b67c 100644 --- a/exist-core/src/main/java/org/exist/xmlrpc/RpcServlet.java +++ b/exist-core/src/main/java/org/exist/xmlrpc/RpcServlet.java @@ -43,6 +43,7 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; +import java.io.Serial; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collections; @@ -55,7 +56,8 @@ public class RpcServlet extends XmlRpcServlet { - private static final long serialVersionUID = -1003413291835771186L; + @Serial + private static final long serialVersionUID = -1003413291835771186L; private static final Logger LOG = LogManager.getLogger(RpcServlet.class); private static final boolean DEFAULT_USE_DEFAULT_USER = true; @@ -102,8 +104,8 @@ public void doPost(HttpServletRequest request, final HttpServletResponse respons } catch (final Throwable e) { LOG.error("Problem during XmlRpc execution", e); final String exceptionMessage; - if (e instanceof XmlRpcException) { - final Throwable linkedException = ((XmlRpcException) e).linkedException; + if (e instanceof XmlRpcException exception) { + final Throwable linkedException = exception.linkedException; LOG.error(linkedException.getMessage(), linkedException); exceptionMessage = "An error occurred: " + e.getMessage() + ": " + linkedException.getMessage(); } else { @@ -114,8 +116,8 @@ public void doPost(HttpServletRequest request, final HttpServletResponse respons } catch (final EXistException e) { throw new ServletException(e); } finally { - if (request != null && request instanceof HttpServletRequestWrapper) { - ((HttpServletRequestWrapper)request).close(); + if (request != null && request instanceof HttpServletRequestWrapper wrapper) { + wrapper.close(); } } } diff --git a/exist-core/src/main/java/org/exist/xmlrpc/TupleParser.java b/exist-core/src/main/java/org/exist/xmlrpc/TupleParser.java index 881d3649a9f..8eaa943f5a7 100644 --- a/exist-core/src/main/java/org/exist/xmlrpc/TupleParser.java +++ b/exist-core/src/main/java/org/exist/xmlrpc/TupleParser.java @@ -119,11 +119,11 @@ public void startElement(final String uri, final String localName, final String private Tuple toTuple(final List list) throws SAXException { return switch (list.size()) { - case 2 -> new Tuple2<>(list.get(0), list.get(1)); - case 3 -> new Tuple3<>(list.get(0), list.get(1), list.get(2)); - case 4 -> new Tuple4<>(list.get(0), list.get(1), list.get(2), list.get(3)); - case 5 -> new Tuple5<>(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4)); - case 6 -> new Tuple6<>(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4), list.get(5)); + case 2 -> new Tuple2<>(list.getFirst(), list.get(1)); + case 3 -> new Tuple3<>(list.getFirst(), list.get(1), list.get(2)); + case 4 -> new Tuple4<>(list.getFirst(), list.get(1), list.get(2), list.get(3)); + case 5 -> new Tuple5<>(list.getFirst(), list.get(1), list.get(2), list.get(3), list.get(4)); + case 6 -> new Tuple6<>(list.getFirst(), list.get(1), list.get(2), list.get(3), list.get(4), list.get(5)); default -> throw new SAXException("Unsupported Tuple arity: " + list.size()); }; } diff --git a/exist-core/src/main/java/org/exist/xquery/AbstractFLWORClause.java b/exist-core/src/main/java/org/exist/xquery/AbstractFLWORClause.java index c088561e08b..ad72416a90d 100644 --- a/exist-core/src/main/java/org/exist/xquery/AbstractFLWORClause.java +++ b/exist-core/src/main/java/org/exist/xquery/AbstractFLWORClause.java @@ -48,8 +48,8 @@ public LocalVariable createVariable(final QName name) throws XPathException { @Override public Sequence preEval(Sequence seq) throws XPathException { - if (returnExpr instanceof FLWORClause) { - return ((FLWORClause)returnExpr).preEval(seq); + if (returnExpr instanceof FLWORClause clause) { + return clause.preEval(seq); } // just return the input sequence by default return seq; @@ -107,4 +107,4 @@ public void resetState(boolean postOptimization) { public int getDependencies() { return returnExpr.getDependencies(); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/xquery/Annotations.java b/exist-core/src/main/java/org/exist/xquery/Annotations.java index 691922fbe7e..609a2f8638b 100644 --- a/exist-core/src/main/java/org/exist/xquery/Annotations.java +++ b/exist-core/src/main/java/org/exist/xquery/Annotations.java @@ -36,7 +36,7 @@ public abstract class Annotations { static { try { final Class clazz = Class.forName("org.exist.xquery.xUnit.Annotations"); - clazz.newInstance(); + clazz.getDeclaredConstructor().newInstance(); } catch (final Exception e) { } } diff --git a/exist-core/src/main/java/org/exist/xquery/AttributeConstructor.java b/exist-core/src/main/java/org/exist/xquery/AttributeConstructor.java index bb1720e67d9..83087a0a0fa 100644 --- a/exist-core/src/main/java/org/exist/xquery/AttributeConstructor.java +++ b/exist-core/src/main/java/org/exist/xquery/AttributeConstructor.java @@ -76,8 +76,8 @@ public void analyze(AnalyzeContextInfo contextInfo) throws XPathException { super.analyze(contextInfo); contextInfo.setParent(this); for(final Object next : contents) { - if(next instanceof Expression) - {((Expression)next).analyze(contextInfo);} + if(next instanceof Expression expression) + {expression.analyze(contextInfo);} } } @@ -91,8 +91,8 @@ public Sequence eval( final StringBuilder buf = new StringBuilder(); for(final Object next : contents) { - if(next instanceof Expression) - {evalEnclosedExpr(((Expression)next).eval(contextSequence, contextItem), buf);} + if(next instanceof Expression expression) + {evalEnclosedExpr(expression.eval(contextSequence, contextItem), buf);} else {buf.append(next);} } @@ -140,8 +140,8 @@ public void dump(ExpressionDumper dumper) { dumper.startIndent(); for(final Object next : contents) { - if(next instanceof Expression) - {((Expression)next).dump(dumper);} + if(next instanceof Expression expression) + {expression.dump(dumper);} else {dumper.display(next);} } @@ -173,8 +173,8 @@ public void resetState(boolean postOptimization) { super.resetState(postOptimization); for(final Object object : contents) { - if(object instanceof Expression) - {((Expression)object).resetState(postOptimization);} + if(object instanceof Expression expression) + {expression.resetState(postOptimization);} } } diff --git a/exist-core/src/main/java/org/exist/xquery/BasicExpressionVisitor.java b/exist-core/src/main/java/org/exist/xquery/BasicExpressionVisitor.java index 95a1e239079..f4901f52e07 100644 --- a/exist-core/src/main/java/org/exist/xquery/BasicExpressionVisitor.java +++ b/exist-core/src/main/java/org/exist/xquery/BasicExpressionVisitor.java @@ -123,8 +123,8 @@ protected void processWrappers(final Expression expr) { } public static LocationStep findFirstStep(final Expression expr) { - if (expr instanceof LocationStep) { - return (LocationStep) expr; + if (expr instanceof LocationStep step) { + return step; } final FirstStepVisitor visitor = new FirstStepVisitor(); expr.accept(visitor); @@ -133,8 +133,8 @@ public static LocationStep findFirstStep(final Expression expr) { public static List findLocationSteps(final Expression expr) { final List steps = new ArrayList<>(5); - if (expr instanceof LocationStep) { - steps.add((LocationStep) expr); + if (expr instanceof LocationStep step) { + steps.add(step); return steps; } expr.accept( diff --git a/exist-core/src/main/java/org/exist/xquery/BindingExpression.java b/exist-core/src/main/java/org/exist/xquery/BindingExpression.java index 57ea725e6c3..7af460414d6 100644 --- a/exist-core/src/main/java/org/exist/xquery/BindingExpression.java +++ b/exist-core/src/main/java/org/exist/xquery/BindingExpression.java @@ -101,14 +101,14 @@ public void resetState(final boolean postOptimization) { } public static void setContext(final int contextId, final Sequence seq) throws XPathException { - if (seq instanceof VirtualNodeSet) { - ((VirtualNodeSet)seq).setInPredicate(true); - ((VirtualNodeSet)seq).setSelfIsContext(); + if (seq instanceof VirtualNodeSet set) { + set.setInPredicate(true); + set.setSelfIsContext(); } else { for (final SequenceIterator i = seq.unorderedIterator(); i.hasNext(); ) { final Item next = i.nextItem(); - if (next instanceof NodeProxy) { - ((NodeProxy) next).addContextNode(contextId, (NodeProxy) next); + if (next instanceof NodeProxy proxy) { + proxy.addContextNode(contextId, proxy); } } } diff --git a/exist-core/src/main/java/org/exist/xquery/DefaultExpressionVisitor.java b/exist-core/src/main/java/org/exist/xquery/DefaultExpressionVisitor.java index d3c27bd8b69..ffebdacaa37 100644 --- a/exist-core/src/main/java/org/exist/xquery/DefaultExpressionVisitor.java +++ b/exist-core/src/main/java/org/exist/xquery/DefaultExpressionVisitor.java @@ -149,8 +149,8 @@ public void visitTextConstructor(DynamicTextConstructor constructor) { public void visitAttribConstructor(AttributeConstructor constructor) { for (final Iterator i = constructor.contentIterator(); i.hasNext(); ) { final Object next = i.next(); - if (next instanceof Expression) - {((Expression)next).accept(this);} + if (next instanceof Expression expression) + {expression.accept(this);} } } diff --git a/exist-core/src/main/java/org/exist/xquery/DynamicNameCheck.java b/exist-core/src/main/java/org/exist/xquery/DynamicNameCheck.java index 44340fa9769..b0fac23fdef 100644 --- a/exist-core/src/main/java/org/exist/xquery/DynamicNameCheck.java +++ b/exist-core/src/main/java/org/exist/xquery/DynamicNameCheck.java @@ -76,11 +76,11 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc if (itemType == Type.NODE) {itemType = seq.getItemType();} //Last chance... - if (item instanceof NodeProxy) { + if (item instanceof NodeProxy proxy) { itemType = item.getType(); if (itemType == NodeProxy.UNKNOWN_NODE_TYPE) { //Retrieve the actual node - itemType = Type.fromDomNodeType(((NodeProxy) item).getNode().getNodeType()); + itemType = Type.fromDomNodeType(proxy.getNode().getNodeType()); } } if (!Type.subTypeOf(itemType, test.getType())) { @@ -105,8 +105,8 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc } private String getPrefixedNodeName(final INode iNode) { - if (iNode instanceof Document) { - final Element documentElement = ((Document) iNode).getDocumentElement(); + if (iNode instanceof Document document) { + final Element documentElement = document.getDocumentElement(); if (documentElement != null) { return getPrefixedNodeName(true, ((INode) documentElement).getQName()); } diff --git a/exist-core/src/main/java/org/exist/xquery/ElementConstructor.java b/exist-core/src/main/java/org/exist/xquery/ElementConstructor.java index 20b94537797..c7a96031a55 100644 --- a/exist-core/src/main/java/org/exist/xquery/ElementConstructor.java +++ b/exist-core/src/main/java/org/exist/xquery/ElementConstructor.java @@ -272,8 +272,8 @@ public Sequence eval(final Sequence contextSequence, final Item contextItem) thr final Item qnitem = qnameSeq.itemAt(0); QName qn; - if (qnitem instanceof QNameValue) { - qn = ((QNameValue) qnitem).getQName(); + if (qnitem instanceof QNameValue value) { + qn = value.getQName(); } else { //Do we have the same result than Atomize there ? -pb try { diff --git a/exist-core/src/main/java/org/exist/xquery/EnclosedExpr.java b/exist-core/src/main/java/org/exist/xquery/EnclosedExpr.java index b11a10e06f4..255b86b6f15 100644 --- a/exist-core/src/main/java/org/exist/xquery/EnclosedExpr.java +++ b/exist-core/src/main/java/org/exist/xquery/EnclosedExpr.java @@ -116,7 +116,7 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc //It is possible for a text node constructor to construct a text node containing a zero-length string. //However, if used in the content of a constructed element or document node, //such a text node will be deleted or merged with another text node. - if (next instanceof TextImpl && ((TextImpl) next).getStringValue().isEmpty()) { + if (next instanceof TextImpl impl && impl.getStringValue().isEmpty()) { next = i.nextItem(); continue; } diff --git a/exist-core/src/main/java/org/exist/xquery/ErrorCodes.java b/exist-core/src/main/java/org/exist/xquery/ErrorCodes.java index 23226a155f2..8dccfa16b1e 100644 --- a/exist-core/src/main/java/org/exist/xquery/ErrorCodes.java +++ b/exist-core/src/main/java/org/exist/xquery/ErrorCodes.java @@ -127,12 +127,13 @@ public class ErrorCodes { public static final ErrorCode XQST0094 = new W3CErrorCode("XQST0094", "The name of each grouping variable must be equal (by the eq operator on expanded QNames) to the name of a variable in the input tuple stream."); - public static final ErrorCode XQDY0101 = new W3CErrorCode("XQDY0101", "An error is raised if a computed namespace constructor attempts to do any of the following:\n" + - "Bind the prefix xml to some namespace URI other than http://www.w3.org/XML/1998/namespace.\n" + - "Bind a prefix other than xml to the namespace URI http://www.w3.org/XML/1998/namespace.\n" + - "Bind the prefix xmlns to any namespace URI.\n" + - "Bind a prefix to the namespace URI http://www.w3.org/2000/xmlns/.\n" + - "Bind any prefix (including the empty prefix) to a zero-length namespace URI."); + public static final ErrorCode XQDY0101 = new W3CErrorCode("XQDY0101", """ + An error is raised if a computed namespace constructor attempts to do any of the following: + Bind the prefix xml to some namespace URI other than http://www.w3.org/XML/1998/namespace. + Bind a prefix other than xml to the namespace URI http://www.w3.org/XML/1998/namespace. + Bind the prefix xmlns to any namespace URI. + Bind a prefix to the namespace URI http://www.w3.org/2000/xmlns/. + Bind any prefix (including the empty prefix) to a zero-length namespace URI."""); public static final ErrorCode XQDY0102 = new W3CErrorCode("XQDY0102", "If the name of an element in an element constructor is in no namespace, creating a default namespace for that element using a computed namespace constructor is an error."); public static final ErrorCode XQST0103 = new W3CErrorCode("XQST0103", "All variables in a window clause must have distinct names."); public static final ErrorCode XQDY0137 = new W3CErrorCode("XQDY0137", "No two keys in a map may have the same key value"); diff --git a/exist-core/src/main/java/org/exist/xquery/ForExpr.java b/exist-core/src/main/java/org/exist/xquery/ForExpr.java index 1a5eab2f4dd..31cf260f60e 100644 --- a/exist-core/src/main/java/org/exist/xquery/ForExpr.java +++ b/exist-core/src/main/java/org/exist/xquery/ForExpr.java @@ -151,12 +151,12 @@ public Sequence eval(Sequence contextSequence, Item contextItem) // This is possible if the input sequence is a node set and has no // dependencies on the current context item. if (isOuterFor) { - if (returnExpr instanceof WhereClause) { + if (returnExpr instanceof WhereClause clause1) { if (at == null) { - in = ((WhereClause) returnExpr).preEval(in); + in = clause1.preEval(in); } - } else if (returnExpr instanceof FLWORClause) { - in = ((FLWORClause) returnExpr).preEval(in); + } else if (returnExpr instanceof FLWORClause clause) { + in = clause.preEval(in); } } diff --git a/exist-core/src/main/java/org/exist/xquery/FunctionCall.java b/exist-core/src/main/java/org/exist/xquery/FunctionCall.java index 466739d798f..5f037f78e71 100644 --- a/exist-core/src/main/java/org/exist/xquery/FunctionCall.java +++ b/exist-core/src/main/java/org/exist/xquery/FunctionCall.java @@ -287,8 +287,8 @@ public Sequence evalFunction(Sequence contextSequence, Item contextItem, Sequenc try { returnSeq = expression.eval(contextSequence, contextItem); - while(returnSeq instanceof DeferredFunctionCall && - functionDef.getSignature().equals(((DeferredFunctionCall)returnSeq).getSignature())) { + while(returnSeq instanceof DeferredFunctionCall dfc && + functionDef.getSignature().equals(dfc.getSignature())) { if (LOG.isTraceEnabled()) { LOG.trace("Executing function: {}", functionDef.getSignature()); } diff --git a/exist-core/src/main/java/org/exist/xquery/FunctionFactory.java b/exist-core/src/main/java/org/exist/xquery/FunctionFactory.java index adcf7d3d5cb..1a1d0a3b315 100644 --- a/exist-core/src/main/java/org/exist/xquery/FunctionFactory.java +++ b/exist-core/src/main/java/org/exist/xquery/FunctionFactory.java @@ -126,7 +126,7 @@ private static GeneralComparison startsWith(XQueryContext context, throw new XPathException(ast.getLine(), ast.getColumn(), ErrorCodes.XPST0017, "Function starts-with() requires two or three arguments"); } - final PathExpr p0 = (PathExpr) params.get(0); + final PathExpr p0 = (PathExpr) params.getFirst(); final PathExpr p1 = (PathExpr) params.get(1); if (p1.getLength() == 0) { throw new XPathException(ast.getLine(), ast.getColumn(), @@ -157,7 +157,7 @@ private static GeneralComparison endsWith(XQueryContext context, XQueryAST ast, throw new XPathException(ast.getLine(), ast.getColumn(), ErrorCodes.XPST0017, "Function ends-with() requires two or three arguments"); } - final PathExpr p0 = (PathExpr) params.get(0); + final PathExpr p0 = (PathExpr) params.getFirst(); final PathExpr p1 = (PathExpr) params.get(1); if (p1.getLength() == 0) { throw new XPathException(ast.getLine(), ast.getColumn(), @@ -187,7 +187,7 @@ private static GeneralComparison contains(XQueryContext context, XQueryAST ast, throw new XPathException(ast.getLine(), ast.getColumn(), ErrorCodes.XPST0017, "Function contains() requires two or three arguments"); } - final PathExpr p0 = (PathExpr) params.get(0); + final PathExpr p0 = (PathExpr) params.getFirst(); final PathExpr p1 = (PathExpr) params.get(1); if (p1.getLength() == 0) { throw new XPathException(ast.getLine(), ast.getColumn(), @@ -218,7 +218,7 @@ private static GeneralComparison equals(XQueryContext context, XQueryAST ast, throw new XPathException(ast.getLine(), ast.getColumn(), ErrorCodes.XPST0017, "Function equals() requires two or three arguments"); } - final PathExpr p0 = (PathExpr) params.get(0); + final PathExpr p0 = (PathExpr) params.getFirst(); final PathExpr p1 = (PathExpr) params.get(1); if (p1.getLength() == 0) { throw new XPathException(ast.getLine(), ast.getColumn(), @@ -399,8 +399,8 @@ private static FunctionCall getXQueryModuleFunction(final XQueryContext context, final StringBuilder msg = new StringBuilder("Function ") .append(qname.getStringValue()).append('#').append(params.size()) .append(" is not defined in namespace '").append(qname.getNamespaceURI()).append('\''); - if (module instanceof ExternalModule) { - final Source moduleSource = ((ExternalModule) module).getSource(); + if (module instanceof ExternalModule externalModule) { + final Source moduleSource = externalModule.getSource(); msg.append(" for module: ").append(moduleSource.pathOrShortIdentifier()); } if (throwOnNotFound) { diff --git a/exist-core/src/main/java/org/exist/xquery/GeneralComparison.java b/exist-core/src/main/java/org/exist/xquery/GeneralComparison.java index 0a79c22c733..4bb2348094c 100644 --- a/exist-core/src/main/java/org/exist/xquery/GeneralComparison.java +++ b/exist-core/src/main/java/org/exist/xquery/GeneralComparison.java @@ -128,14 +128,14 @@ public GeneralComparison( XQueryContext context, Expression left, Expression rig this.relation = relation; this.truncation = truncation; - if( ( left instanceof PathExpr ) && ( ( ( PathExpr )left ).getLength() == 1 ) ) { - left = ( ( PathExpr )left ).getExpression( 0 ); + if( ( left instanceof PathExpr expr ) && ( expr.getLength() == 1 ) ) { + left = expr.getExpression( 0 ); didLeftSimplification = true; } add( left ); - if( ( right instanceof PathExpr ) && ( ( ( PathExpr )right ).getLength() == 1 ) ) { - right = ( ( PathExpr )right ).getExpression( 0 ); + if( ( right instanceof PathExpr expr ) && ( expr.getLength() == 1 ) ) { + right = expr.getExpression( 0 ); didRightSimplification = true; } add( right ); @@ -190,7 +190,7 @@ public void visitCastExpr( CastExpression expression ) final List steps = BasicExpressionVisitor.findLocationSteps( getLeft() ); if( !steps.isEmpty() ) { - LocationStep firstStep = steps.get( 0 ); + LocationStep firstStep = steps.getFirst(); LocationStep lastStep = steps.getLast(); if( firstStep != null && steps.size() == 1 && firstStep.getAxis() == Constants.SELF_AXIS) { @@ -364,7 +364,7 @@ else if( key.getType() != indexType ) { } // If key implements org.exist.storage.Indexable, we can use the index - if( key instanceof Indexable ) { + if( key instanceof Indexable indexable ) { if( LOG.isTraceEnabled() ) { LOG.trace("Using QName range index for key: {}", key.getStringValue()); @@ -375,7 +375,7 @@ else if( key.getType() != indexType ) { final Collator collator = ( ( collationArg != null ) ? getCollator( contextSequence ) : null ); if( truncation == StringTruncationOperator.NONE ) { - temp = context.getBroker().getValueIndex().find(context.getWatchDog(), relation, contextSequence.getDocumentSet(), contextSet, NodeSet.DESCENDANT, contextQName, ( Indexable )key); + temp = context.getBroker().getValueIndex().find(context.getWatchDog(), relation, contextSequence.getDocumentSet(), contextSet, NodeSet.DESCENDANT, contextQName, indexable); hasUsedIndex = true; } else { @@ -803,7 +803,7 @@ else if( key.getType() != indexType ) { } // If key implements org.exist.storage.Indexable, we can use the index - if( key instanceof Indexable ) { + if( key instanceof Indexable indexable ) { if( LOG.isTraceEnabled() ) { LOG.trace("Checking if range index can be used for key: {}", key.getStringValue()); @@ -825,10 +825,10 @@ else if( key.getType() != indexType ) { NodeSet ns; if( indexScan ) { - ns = context.getBroker().getValueIndex().findAll( context.getWatchDog(), relation, docs, nodes, NodeSet.ANCESTOR, ( Indexable )key); + ns = context.getBroker().getValueIndex().findAll( context.getWatchDog(), relation, docs, nodes, NodeSet.ANCESTOR, indexable); } else { ns = context.getBroker().getValueIndex().find( context.getWatchDog(), relation, docs, nodes, NodeSet.ANCESTOR, myContextQName, - ( Indexable )key, indexMixed ); + indexable, indexMixed ); } hasUsedIndex = true; @@ -1246,10 +1246,10 @@ protected Collator getCollator( Sequence contextSequence ) throws XPathException String collationURI; - if( collationArg instanceof Expression ) { - collationURI = ( ( Expression )collationArg ).eval(contextSequence, null).getStringValue(); - } else if( collationArg instanceof StringValue ) { - collationURI = ( ( StringValue )collationArg ).getStringValue(); + if( collationArg instanceof Expression expression ) { + collationURI = expression.eval(contextSequence, null).getStringValue(); + } else if( collationArg instanceof StringValue value ) { + collationURI = value.getStringValue(); } else { return( context.getDefaultCollator() ); } diff --git a/exist-core/src/main/java/org/exist/xquery/GroupSpec.java b/exist-core/src/main/java/org/exist/xquery/GroupSpec.java index e8e30e95fbb..a14626c2d7d 100644 --- a/exist-core/src/main/java/org/exist/xquery/GroupSpec.java +++ b/exist-core/src/main/java/org/exist/xquery/GroupSpec.java @@ -101,7 +101,7 @@ public void replace(final Expression oldExpr, final Expression newExpr) { @Override public boolean equals(final Object obj) { - return obj instanceof GroupSpec && ((GroupSpec)obj).keyVarName.equals(keyVarName); + return obj instanceof GroupSpec gs && gs.keyVarName.equals(keyVarName); } @Override diff --git a/exist-core/src/main/java/org/exist/xquery/JavaCall.java b/exist-core/src/main/java/org/exist/xquery/JavaCall.java index 0712a240b03..18b392f3f77 100644 --- a/exist-core/src/main/java/org/exist/xquery/JavaCall.java +++ b/exist-core/src/main/java/org/exist/xquery/JavaCall.java @@ -204,8 +204,8 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc // LOG.debug("calling method " + bestMethod.toString()); Class paramTypes[] = null; boolean isStatic = true; - if (bestMethod instanceof Constructor) - {paramTypes = ((Constructor) bestMethod).getParameterTypes();} + if (bestMethod instanceof Constructor constructor) + {paramTypes = constructor.getParameterTypes();} else { paramTypes = ((Method) bestMethod).getParameterTypes(); isStatic = Modifier.isStatic(((Method) bestMethod).getModifiers()); @@ -223,9 +223,9 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc } Sequence result; - if (bestMethod instanceof Constructor) { + if (bestMethod instanceof Constructor constructor) { try { - final Object object = ((Constructor) bestMethod).newInstance(params); + final Object object = constructor.newInstance(params); result = new JavaObjectValue(this, object); } catch (final IllegalArgumentException e) { throw new XPathException(this, @@ -235,8 +235,8 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc + e.getMessage(), e); } catch (final Exception e) { - if (e instanceof XPathException) - {throw (XPathException) e;} + if (e instanceof XPathException exception) + {throw exception;} else {throw new XPathException(this, "exception while calling constructor " @@ -265,8 +265,8 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc + e.getMessage(), e); } catch (final Exception e) { - if (e instanceof XPathException) - {throw (XPathException) e;} + if (e instanceof XPathException exception) + {throw exception;} else {throw new XPathException(this, "exception while calling method " @@ -297,8 +297,8 @@ private int[] getConversionPreferences(AccessibleObject method, Sequence[] args) final int prefs[] = new int[args.length]; Class paramTypes[] = null; boolean isStatic = true; - if (method instanceof Constructor) - {paramTypes = ((Constructor) method).getParameterTypes();} + if (method instanceof Constructor constructor) + {paramTypes = constructor.getParameterTypes();} else { paramTypes = ((Method) method).getParameterTypes(); isStatic = Modifier.isStatic(((Method) method).getModifiers()); diff --git a/exist-core/src/main/java/org/exist/xquery/LetExpr.java b/exist-core/src/main/java/org/exist/xquery/LetExpr.java index 278e7d18295..6dea5a5ef5a 100644 --- a/exist-core/src/main/java/org/exist/xquery/LetExpr.java +++ b/exist-core/src/main/java/org/exist/xquery/LetExpr.java @@ -141,8 +141,8 @@ public Sequence eval(Sequence contextSequence, Item contextItem) // it's a document... we need to get the document element's name final NodeValue nvItem = (NodeValue) value.itemAt(0); final Document doc; - if (nvItem instanceof Document) { - doc = (Document) nvItem; + if (nvItem instanceof Document document) { + doc = document; } else { doc = nvItem.getOwnerDocument(); } @@ -162,7 +162,7 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throw new XPathException( this, ErrorCodes.XPTY0004, - String.format("Invalid type for variable $%s. Expected %s, got %s", varName, sequenceType.toString(), valueType), in); + "Invalid type for variable $%s. Expected %s, got %s".formatted(varName, sequenceType.toString(), valueType), in); } } } @@ -247,4 +247,4 @@ public Set getTupleStreamVariables() { return variables; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/xquery/LocationStep.java b/exist-core/src/main/java/org/exist/xquery/LocationStep.java index 624795add20..0d009263017 100644 --- a/exist-core/src/main/java/org/exist/xquery/LocationStep.java +++ b/exist-core/src/main/java/org/exist/xquery/LocationStep.java @@ -509,8 +509,8 @@ private Sequence getSelf(final XQueryContext context, final Sequence contextSequ if (hasPreloadedData()) { @Nullable final NodeSet ns; - if (contextSequence instanceof NodeSet) { - ns = (NodeSet) contextSequence; + if (contextSequence instanceof NodeSet set) { + ns = set; } else { ns = null; } @@ -553,10 +553,10 @@ private Sequence getSelf(final XQueryContext context, final Sequence contextSequ if (Type.subTypeOf(nodeTestType, Type.NODE)) { if (Expression.NO_CONTEXT_ID != contextId) { - if (contextSet instanceof VirtualNodeSet) { - ((VirtualNodeSet) contextSet).setInPredicate(true); - ((VirtualNodeSet) contextSet).setContextId(contextId); - ((VirtualNodeSet) contextSet).setSelfIsContext(); + if (contextSet instanceof VirtualNodeSet set) { + set.setInPredicate(true); + set.setContextId(contextId); + set.setSelfIsContext(); } else if (Type.subTypeOf(contextSet.getItemType(), Type.NODE)) { for (final NodeProxy p : contextSet) { if (test.matches(p)) { diff --git a/exist-core/src/main/java/org/exist/xquery/Lookup.java b/exist-core/src/main/java/org/exist/xquery/Lookup.java index 2640d16076d..38d3d33541f 100644 --- a/exist-core/src/main/java/org/exist/xquery/Lookup.java +++ b/exist-core/src/main/java/org/exist/xquery/Lookup.java @@ -115,8 +115,8 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc } } else if(item instanceof ArrayType) { result.addAll(item.keys()); - } else if(item instanceof AbstractMapType) { - for(final IEntry entry : ((AbstractMapType)item)) { + } else if(item instanceof AbstractMapType type) { + for(final IEntry entry : type) { result.addAll(entry.value()); } } diff --git a/exist-core/src/main/java/org/exist/xquery/NamedFunctionReference.java b/exist-core/src/main/java/org/exist/xquery/NamedFunctionReference.java index e3e222d0dcd..f95d8100ab2 100644 --- a/exist-core/src/main/java/org/exist/xquery/NamedFunctionReference.java +++ b/exist-core/src/main/java/org/exist/xquery/NamedFunctionReference.java @@ -80,8 +80,8 @@ public static FunctionCall lookupFunction(Expression self, XQueryContext context } case Function function -> { final InternalFunctionCall funcCall; - if (fun instanceof InternalFunctionCall) { - funcCall = (InternalFunctionCall) fun; + if (fun instanceof InternalFunctionCall call) { + funcCall = call; } else { funcCall = new InternalFunctionCall((Function) fun); } diff --git a/exist-core/src/main/java/org/exist/xquery/Optimizer.java b/exist-core/src/main/java/org/exist/xquery/Optimizer.java index 97404ce5691..e72defa4220 100644 --- a/exist-core/src/main/java/org/exist/xquery/Optimizer.java +++ b/exist-core/src/main/java/org/exist/xquery/Optimizer.java @@ -246,8 +246,8 @@ public void visitAndExpr(final OpAnd and) { final PathExpr path; final Predicate predicate; - if (parent instanceof Predicate) { - predicate = (Predicate) parent; + if (parent instanceof Predicate predicate1) { + predicate = predicate1; path = predicate; } else { path = (PathExpr) parent; diff --git a/exist-core/src/main/java/org/exist/xquery/Option.java b/exist-core/src/main/java/org/exist/xquery/Option.java index 27f8615dfdb..cf45f50169c 100644 --- a/exist-core/src/main/java/org/exist/xquery/Option.java +++ b/exist-core/src/main/java/org/exist/xquery/Option.java @@ -106,7 +106,7 @@ public static String[] tokenize(final String contents) { @Override public boolean equals(final Object other) { return other != null && - other instanceof Option && - qname.equals(((Option) other).qname); + other instanceof Option o && + qname.equals(o.qname); } } diff --git a/exist-core/src/main/java/org/exist/xquery/PathExpr.java b/exist-core/src/main/java/org/exist/xquery/PathExpr.java index 8e096376cc5..ec01723a541 100644 --- a/exist-core/src/main/java/org/exist/xquery/PathExpr.java +++ b/exist-core/src/main/java/org/exist/xquery/PathExpr.java @@ -96,8 +96,8 @@ public void addPath(final PathExpr path) { public void addPredicate(final Predicate predicate) { if (!steps.isEmpty()) { final Expression e = steps.getLast(); - if (e instanceof Step) { - ((Step) e).addPredicate(predicate); + if (e instanceof Step step) { + step.addPredicate(predicate); } } } @@ -216,8 +216,8 @@ public Sequence eval(Sequence contextSequence, final Item contextItem) throws XP Sequence currentContext = contextSequence; DocumentSet contextDocs = null; Expression expr = steps.getFirst(); - if (expr instanceof VariableReference) { - final Variable var = ((VariableReference) expr).getVariable(new AnalyzeContextInfo(parent, 0)); + if (expr instanceof VariableReference reference) { + final Variable var = reference.getVariable(new AnalyzeContextInfo(parent, 0)); //TOUNDERSTAND : how null could be possible here ? -pb if (var != null) { contextDocs = var.getContextDocs(); @@ -503,15 +503,15 @@ public String getLiteralValue() { return ""; } final Expression next = steps.getFirst(); - if (next instanceof LiteralValue) { + if (next instanceof LiteralValue value) { try { - return ((LiteralValue) next).getValue().getStringValue(); + return value.getValue().getStringValue(); } catch (final XPathException e) { //TODO : is there anything to do here ? } } - if (next instanceof PathExpr) { - return ((PathExpr) next).getLiteralValue(); + if (next instanceof PathExpr expr) { + return expr.getLiteralValue(); } return ""; } diff --git a/exist-core/src/main/java/org/exist/xquery/PerformanceStats.java b/exist-core/src/main/java/org/exist/xquery/PerformanceStats.java index a7910ef897f..9326b4ba601 100644 --- a/exist-core/src/main/java/org/exist/xquery/PerformanceStats.java +++ b/exist-core/src/main/java/org/exist/xquery/PerformanceStats.java @@ -43,7 +43,7 @@ enum OptimizationType { enum IndexOptimizationLevel { NONE, BASIC, - OPTIMIZED; + OPTIMIZED } /** diff --git a/exist-core/src/main/java/org/exist/xquery/Predicate.java b/exist-core/src/main/java/org/exist/xquery/Predicate.java index 986de11bb8a..e6f9edbdefe 100644 --- a/exist-core/src/main/java/org/exist/xquery/Predicate.java +++ b/exist-core/src/main/java/org/exist/xquery/Predicate.java @@ -237,8 +237,8 @@ private Tuple2 recomputeExecutionMode(final Sequence co // Hack : GeneralComparison lies on its dependencies // TODO : try to remove this since our dependency // computation should now be better - !((inner instanceof GeneralComparison) && - ((GeneralComparison) inner).invalidNodeEvaluation)) { + !((inner instanceof GeneralComparison comparison) && + comparison.invalidNodeEvaluation)) { innerSeq = inner.eval(contextSequence, null); // Only if we have an actual *singleton* of numeric items if (innerSeq.hasOne() @@ -287,8 +287,8 @@ private Sequence evalBoolean(final Sequence contextSequence, final Expression in throws XPathException { final Sequence result = new ValueSequence(); int p; - if (contextSequence instanceof NodeSet - && ((NodeSet) contextSequence).getProcessInReverseOrder()) { + if (contextSequence instanceof NodeSet set + && set.getProcessInReverseOrder()) { // This one may be expensive... p = contextSequence.getItemCount(); for (final SequenceIterator i = contextSequence.iterate(); i.hasNext(); p--) { diff --git a/exist-core/src/main/java/org/exist/xquery/Profiler.java b/exist-core/src/main/java/org/exist/xquery/Profiler.java index aab76e1a050..ae80915f804 100644 --- a/exist-core/src/main/java/org/exist/xquery/Profiler.java +++ b/exist-core/src/main/java/org/exist/xquery/Profiler.java @@ -185,7 +185,7 @@ public final void traceQueryEnd(XQueryContext context) { public final void traceFunctionStart(Function function) { if (isLogEnabled()) { - log.trace(String.format("ENTER %-25s", function.getSignature().getName())); + log.trace("ENTER %-25s".formatted(function.getSignature().getName())); } } @@ -194,15 +194,15 @@ public final void traceFunctionEnd(Function function, long elapsed) { final Source source = function.getContext().getSource(); final String sourceMsg; if (source == null) { - sourceMsg = String.format("[unknown source] [%d:%d]", function.getLine(), function.getColumn()); + sourceMsg = "[unknown source] [%d:%d]".formatted(function.getLine(), function.getColumn()); } else { - sourceMsg = String.format("%s [%d:%d]", function.getContext().getSource().pathOrShortIdentifier(), + sourceMsg = "%s [%d:%d]".formatted(function.getContext().getSource().pathOrShortIdentifier(), function.getLine(), function.getColumn()); } stats.recordFunctionCall(function.getSignature().getName(), sourceMsg, elapsed); } if (isLogEnabled()) { - log.trace(String.format("EXIT %-25s %10d ms", function.getSignature().getName(), elapsed)); + log.trace("EXIT %-25s %10d ms".formatted(function.getSignature().getName(), elapsed)); } } diff --git a/exist-core/src/main/java/org/exist/xquery/RangeExpression.java b/exist-core/src/main/java/org/exist/xquery/RangeExpression.java index 3dece7515e2..cc701b4a865 100644 --- a/exist-core/src/main/java/org/exist/xquery/RangeExpression.java +++ b/exist-core/src/main/java/org/exist/xquery/RangeExpression.java @@ -48,7 +48,7 @@ public RangeExpression(XQueryContext context) { //TODO : remove and use the other constructor public void setArguments(List arguments) throws XPathException { - start = arguments.get(0); + start = arguments.getFirst(); end = arguments.get(1); } diff --git a/exist-core/src/main/java/org/exist/xquery/StaticXQueryException.java b/exist-core/src/main/java/org/exist/xquery/StaticXQueryException.java index 682be4dfff1..8c4e67be3ed 100644 --- a/exist-core/src/main/java/org/exist/xquery/StaticXQueryException.java +++ b/exist-core/src/main/java/org/exist/xquery/StaticXQueryException.java @@ -21,9 +21,12 @@ */ package org.exist.xquery; +import java.io.Serial; + public class StaticXQueryException extends XPathException { - private static final long serialVersionUID = -8229758099980343418L; + @Serial + private static final long serialVersionUID = -8229758099980343418L; public StaticXQueryException(String message) { this(null, message); @@ -57,4 +60,4 @@ public StaticXQueryException(final Expression expression, String message, Throwa public StaticXQueryException(int line, int column, String message, Throwable cause) { super(line, column, message, cause); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/xquery/TerminatedException.java b/exist-core/src/main/java/org/exist/xquery/TerminatedException.java index b78bb96c989..30e668a9dbb 100644 --- a/exist-core/src/main/java/org/exist/xquery/TerminatedException.java +++ b/exist-core/src/main/java/org/exist/xquery/TerminatedException.java @@ -22,12 +22,15 @@ package org.exist.xquery; +import java.io.Serial; + /** * @author wolf */ public class TerminatedException extends XPathException { - private static final long serialVersionUID = 6055587317214098592L; + @Serial + private static final long serialVersionUID = 6055587317214098592L; public TerminatedException(String message) { this(null, message); @@ -42,8 +45,9 @@ public TerminatedException(int line, int column, String message) { } public final static class TimeoutException extends TerminatedException { - - private static final long serialVersionUID = 1193758368058763151L; + + @Serial + private static final long serialVersionUID = 1193758368058763151L; public TimeoutException(int line, int column, String message) { super(line, column, message); @@ -51,8 +55,9 @@ public TimeoutException(int line, int column, String message) { } public final static class SizeLimitException extends TerminatedException { - - private static final long serialVersionUID = -697205233217384556L; + + @Serial + private static final long serialVersionUID = -697205233217384556L; public SizeLimitException(int line, int column, String message) { super(line, column, message); diff --git a/exist-core/src/main/java/org/exist/xquery/TryCatchExpression.java b/exist-core/src/main/java/org/exist/xquery/TryCatchExpression.java index c11a2acf065..de0d77c3a2e 100644 --- a/exist-core/src/main/java/org/exist/xquery/TryCatchExpression.java +++ b/exist-core/src/main/java/org/exist/xquery/TryCatchExpression.java @@ -267,8 +267,8 @@ private void addErrColumnNumber(final Throwable t) throws XPathException { err_column_nr.setSequenceType(new SequenceType(Type.INTEGER, Cardinality.ZERO_OR_ONE)); final Sequence colNum; - if (t != null && t instanceof XPathException) { - colNum = new IntegerValue(this, ((XPathException)t).getColumn()); + if (t != null && t instanceof XPathException exception) { + colNum = new IntegerValue(this, exception.getColumn()); } else { colNum = Sequence.EMPTY_SEQUENCE; } @@ -286,8 +286,8 @@ private void addErrLineNumber(final Throwable t) throws XPathException { err_line_nr.setSequenceType(new SequenceType(Type.INTEGER, Cardinality.ZERO_OR_ONE)); final Sequence lineNum; - if (t != null && t instanceof XPathException) { - lineNum = new IntegerValue(this, ((XPathException)t).getLine()); + if (t != null && t instanceof XPathException exception) { + lineNum = new IntegerValue(this, exception.getLine()); } else { lineNum = Sequence.EMPTY_SEQUENCE; } @@ -305,8 +305,8 @@ private void addErrModule(final Throwable t) throws XPathException { err_module.setSequenceType(new SequenceType(Type.STRING, Cardinality.ZERO_OR_ONE)); final Sequence module; - if (t != null && t instanceof XPathException && ((XPathException)t).getSource() != null) { - module = new StringValue(this, ((XPathException)t).getSource().pathOrShortIdentifier()); + if (t != null && t instanceof XPathException exception && exception.getSource() != null) { + module = new StringValue(this, exception.getSource().pathOrShortIdentifier()); } else { module = Sequence.EMPTY_SEQUENCE; } @@ -326,8 +326,8 @@ private void addErrValue(final Throwable t) throws XPathException { final Sequence errorValue; if (t != null) { // Get error value from exception - if(t instanceof XPathException && ((XPathException)t).getErrorVal() != null) { - errorValue = ((XPathException)t).getErrorVal(); + if(t instanceof XPathException exception && exception.getErrorVal() != null) { + errorValue = exception.getErrorVal(); } else { errorValue = Sequence.EMPTY_SEQUENCE; } @@ -346,7 +346,7 @@ private void addErrValue(final Throwable t) throws XPathException { // was called with one argument). private void addErrDescription(final Throwable t, final ErrorCode errorCode) throws XPathException { final Optional errorDesc = Optional.ofNullable(errorCode.getDescription()); - final Optional throwableDesc = Optional.ofNullable(t instanceof XPathException ? ((XPathException) t).getDetailMessage() : t.getMessage()); + final Optional throwableDesc = Optional.ofNullable(t instanceof XPathException xpe ? xpe.getDetailMessage() : t.getMessage()); final Expression expression = this; final Sequence description = errorDesc .map( @@ -505,8 +505,8 @@ private void addFunctionTrace(final Throwable t) throws XPathException { localVar.setSequenceType(new SequenceType(Type.STRING, Cardinality.ZERO_OR_MORE)); final Sequence trace; - if(t != null && t instanceof XPathException) { - final List callStack = ((XPathException)t).getCallStack(); + if(t != null && t instanceof XPathException exception) { + final List callStack = exception.getCallStack(); if(callStack == null){ trace = Sequence.EMPTY_SEQUENCE; } else { diff --git a/exist-core/src/main/java/org/exist/xquery/UnaryExpr.java b/exist-core/src/main/java/org/exist/xquery/UnaryExpr.java index b593a099ce8..cc43f8f024e 100644 --- a/exist-core/src/main/java/org/exist/xquery/UnaryExpr.java +++ b/exist-core/src/main/java/org/exist/xquery/UnaryExpr.java @@ -71,8 +71,8 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc final NumericValue value; if (Type.subTypeOfUnion(item.getItemType(), Type.NUMERIC)) { - if (item instanceof NumericValue) { - value = (NumericValue) item; + if (item instanceof NumericValue numericValue) { + value = numericValue; } else { value = (NumericValue) item.convertTo(item.getItemType()); } diff --git a/exist-core/src/main/java/org/exist/xquery/UntypedValueCheck.java b/exist-core/src/main/java/org/exist/xquery/UntypedValueCheck.java index 5e0775574f7..39d9c708c5b 100644 --- a/exist-core/src/main/java/org/exist/xquery/UntypedValueCheck.java +++ b/exist-core/src/main/java/org/exist/xquery/UntypedValueCheck.java @@ -55,8 +55,8 @@ public UntypedValueCheck(XQueryContext context, int requiredType, Error error) { public UntypedValueCheck(XQueryContext context, int requiredType, final Expression expression, Error error) { super(context); this.requiredType = requiredType; - if (expression instanceof Atomize && !Type.subTypeOf(requiredType, Type.ANY_ATOMIC_TYPE)) { - this.expression = ((Atomize)expression).getExpression(); + if (expression instanceof Atomize atomize1 && !Type.subTypeOf(requiredType, Type.ANY_ATOMIC_TYPE)) { + this.expression = atomize1.getExpression(); this.atomize = true; } else { this.expression = expression; diff --git a/exist-core/src/main/java/org/exist/xquery/ValueComparison.java b/exist-core/src/main/java/org/exist/xquery/ValueComparison.java index 80c916a3f26..089070c8e69 100644 --- a/exist-core/src/main/java/org/exist/xquery/ValueComparison.java +++ b/exist-core/src/main/java/org/exist/xquery/ValueComparison.java @@ -140,16 +140,12 @@ public static boolean compareAtomic(@Nullable final Collator collator, AtomicVal lv = comparableLvRv._1; rv = comparableLvRv._2; - switch (truncation) { - case RIGHT: - return lv.startsWith(collator, rv); - case LEFT: - return lv.endsWith(collator, rv); - case BOTH: - return lv.contains(collator, rv); - default: - return lv.compareTo(collator, relation, rv); - } + return switch (truncation) { + case RIGHT -> lv.startsWith(collator, rv); + case LEFT -> lv.endsWith(collator, rv); + case BOTH -> lv.contains(collator, rv); + default -> lv.compareTo(collator, relation, rv); + }; } /** diff --git a/exist-core/src/main/java/org/exist/xquery/VariableImpl.java b/exist-core/src/main/java/org/exist/xquery/VariableImpl.java index c5a600c8ae2..0fefba1f91d 100644 --- a/exist-core/src/main/java/org/exist/xquery/VariableImpl.java +++ b/exist-core/src/main/java/org/exist/xquery/VariableImpl.java @@ -245,8 +245,8 @@ public void checkType() throws XPathException { // it's a document... we need to get the document element's name final NodeValue nvItem = (NodeValue)value.itemAt(0); final Document doc; - if (nvItem instanceof Document) { - doc = (Document) nvItem; + if (nvItem instanceof Document document) { + doc = document; } else { doc = nvItem.getOwnerDocument(); } diff --git a/exist-core/src/main/java/org/exist/xquery/WindowExpr.java b/exist-core/src/main/java/org/exist/xquery/WindowExpr.java index 6456274565c..5cd2d0f1300 100644 --- a/exist-core/src/main/java/org/exist/xquery/WindowExpr.java +++ b/exist-core/src/main/java/org/exist/xquery/WindowExpr.java @@ -630,7 +630,7 @@ private static class Window { private enum State { STARTED, - ENDED; + ENDED } public void start(@Nullable final WindowContextVariables startVariables) { diff --git a/exist-core/src/main/java/org/exist/xquery/XPathException.java b/exist-core/src/main/java/org/exist/xquery/XPathException.java index 707918f9795..48a9941865f 100644 --- a/exist-core/src/main/java/org/exist/xquery/XPathException.java +++ b/exist-core/src/main/java/org/exist/xquery/XPathException.java @@ -21,6 +21,7 @@ */ package org.exist.xquery; +import java.io.Serial; import java.util.ArrayList; import java.util.Iterator; import java.util.List; @@ -37,6 +38,7 @@ */ public class XPathException extends Exception implements XPathErrorProvider { + @Serial private static final long serialVersionUID = 212844692232650666L; private int line = 0; private int column = 0; @@ -191,8 +193,8 @@ public XPathException(final XQueryAST ast, final ErrorCode errorCode, final Stri @Deprecated public XPathException(final Throwable cause) { super(cause); - if (cause instanceof XPathErrorProvider) { - this.errorCode = ((XPathErrorProvider)cause).getErrorCode(); + if (cause instanceof XPathErrorProvider provider) { + this.errorCode = provider.getErrorCode(); } } @@ -209,8 +211,8 @@ public XPathException(final String message, final Throwable cause) { public XPathException(final Expression expr, final String message, final Throwable cause) { super(cause); this.message = message; - if (cause instanceof XPathErrorProvider) { - this.errorCode = ((XPathErrorProvider)cause).getErrorCode(); + if (cause instanceof XPathErrorProvider provider) { + this.errorCode = provider.getErrorCode(); } if (expr != null) { @@ -227,7 +229,7 @@ public XPathException(final Expression expr, final String message, final Throwab */ @Deprecated public XPathException(final Expression expr, final Throwable cause) { - this(expr, cause instanceof XPathErrorProvider ? ((XPathErrorProvider)cause).getErrorCode() : ErrorCodes.ERROR, cause == null ? "" : cause.getMessage(), null, cause); + this(expr, cause instanceof XPathErrorProvider xpep ? xpep.getErrorCode() : ErrorCodes.ERROR, cause == null ? "" : cause.getMessage(), null, cause); } /** @@ -304,8 +306,8 @@ protected XPathException(final int line, final int column, final String message, this.message = message; this.line = line; this.column = column; - if (cause instanceof XPathErrorProvider) { - this.errorCode = ((XPathErrorProvider)cause).getErrorCode(); + if (cause instanceof XPathErrorProvider provider) { + this.errorCode = provider.getErrorCode(); } } @@ -321,8 +323,8 @@ public XPathException(final int line, final int column, final Throwable cause) { super(cause); this.line = line; this.column = column; - if(cause instanceof XPathErrorProvider) { - this.errorCode = ((XPathErrorProvider)cause).getErrorCode(); + if(cause instanceof XPathErrorProvider provider) { + this.errorCode = provider.getErrorCode(); } } diff --git a/exist-core/src/main/java/org/exist/xquery/XQuery.java b/exist-core/src/main/java/org/exist/xquery/XQuery.java index 5eba728708b..3244c671b37 100644 --- a/exist-core/src/main/java/org/exist/xquery/XQuery.java +++ b/exist-core/src/main/java/org/exist/xquery/XQuery.java @@ -423,10 +423,10 @@ public Sequence execute(final DBBroker broker, final CompiledXQuery expression, } final Sequence result; - if (expression instanceof LibraryModuleRoot) { + if (expression instanceof LibraryModuleRoot root) { if (functionCall == null) { if (expression != null) { - throw new XPathException(((LibraryModuleRoot) expression).getLine(), ((LibraryModuleRoot) expression).getColumn(), ErrorCodes.EXXQDY0005, "No function call details were provided when trying to execute a Library Module."); + throw new XPathException(root.getLine(), root.getColumn(), ErrorCodes.EXXQDY0005, "No function call details were provided when trying to execute a Library Module."); } else { throw new XPathException((Expression) null, ErrorCodes.EXXQDY0005, "No function call details were provided when trying to execute a Library Module."); } diff --git a/exist-core/src/main/java/org/exist/xquery/XQueryContext.java b/exist-core/src/main/java/org/exist/xquery/XQueryContext.java index 6e8105ec786..f1f045ca6bb 100644 --- a/exist-core/src/main/java/org/exist/xquery/XQueryContext.java +++ b/exist-core/src/main/java/org/exist/xquery/XQueryContext.java @@ -30,7 +30,6 @@ import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ThreadPoolExecutor; @@ -603,8 +602,8 @@ public Optional getRepository() { } else { // NOTE(AR) set the location of the module to import relative to this module's load path // - so that transient imports of the imported module will resolve correctly! - final Path collectionPath = Paths.get(XmldbURI.create(moduleLoadPath).getCollectionPath()); - final Path sourcePath = Paths.get(sourceCollection); + final Path collectionPath = Path.of(XmldbURI.create(moduleLoadPath).getCollectionPath()); + final Path sourcePath = Path.of(sourceCollection); location = collectionPath.relativize(sourcePath).toString(); } } @@ -629,8 +628,8 @@ public void prepareForReuse() throws XPathException { // prepare the variables of the internal modules (which were previously reset) for (final Module[] modules : allModules.values()) { for (final Module module : modules) { - if (module instanceof InternalModule) { - ((InternalModule) module).prepare(this); + if (module instanceof InternalModule internalModule) { + internalModule.prepare(this); } } } @@ -1788,8 +1787,8 @@ Module initBuiltInModule(final String namespaceURI, final String moduleClassName modules.compute(module.getNamespaceURI(), addToMapValueArray(module)); allModules.compute(module.getNamespaceURI(), addToMapValueArray(module)); - if (module instanceof InternalModule) { - ((InternalModule) module).prepare(this); + if (module instanceof InternalModule internalModule) { + internalModule.prepare(this); } return module; } catch (final InstantiationException | IllegalAccessException | InvocationTargetException | XPathException e) { @@ -2668,8 +2667,8 @@ public boolean tailRecursiveCall(final FunctionSignature signature) { try { //TODO: use URIs to ensure proper resolution of relative locations final String contextPath; - if (source instanceof FileSource) { - final Path sourcePath = ((FileSource) source).getPath(); + if (source instanceof FileSource fileSource) { + final Path sourcePath = fileSource.getPath(); contextPath = sourcePath.resolveSibling(moduleLoadPath).normalize().toString(); } else { contextPath = moduleLoadPath; diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FnFormatDates.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FnFormatDates.java index 2ade21d3117..f8e5b54eecd 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FnFormatDates.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FnFormatDates.java @@ -394,7 +394,7 @@ private void formatComponent(String component, AbstractDateTimeValue dt, final S private String formatTimeZone(final String timezonePicture, final int hour, final int minute, final TimeZone timeZone, final String language, final Optional place) { - final Locale locale = new Locale(language); + final Locale locale = Locale.of(language); final String format; switch(timezonePicture) { @@ -461,7 +461,7 @@ private String formatMilitaryTimeZone(final int hour, final int minute) { } return String.valueOf(MILITARY_TZ_CHARS[offset]); } else { - return String.format("%+03d:%02d", hour, minute); + return "%+03d:%02d".formatted(hour, minute); } } @@ -569,4 +569,4 @@ private int[] getWidths(String width) throws XPathException { {throw new XPathException(this, ErrorCodes.FOFD1350,"Minimum width > maximum width in component");} return new int[] { min, max }; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FnHasChildren.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FnHasChildren.java index 70816d21fe8..8e3cd3e2eec 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FnHasChildren.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FnHasChildren.java @@ -89,8 +89,8 @@ public Sequence eval(Sequence contextSequence, final Item contextItem) throws XP final Node w3cNode; if(node instanceof NodeProxy) { w3cNode = node.getNode(); - } else if(node instanceof org.exist.dom.memtree.NodeImpl) { - w3cNode = ((org.exist.dom.memtree.NodeImpl)node); + } else if(node instanceof org.exist.dom.memtree.NodeImpl impl) { + w3cNode = impl; } else { throw new XPathException(this, ErrorCodes.XPTY0004, "Context item is not a node()"); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunAbs.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunAbs.java index 81d29fb9b34..ee12a0baa12 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunAbs.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunAbs.java @@ -81,8 +81,8 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc else { final Item item = seq.itemAt(0); NumericValue value; - if (item instanceof NumericValue) { - value = (NumericValue) item; + if (item instanceof NumericValue numericValue) { + value = numericValue; } else { value = (NumericValue) item.convertTo(Type.NUMERIC); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunCeiling.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunCeiling.java index 910ca103a1a..58f72f1b88a 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunCeiling.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunCeiling.java @@ -80,8 +80,8 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc } else { final Item item = seq.itemAt(0); NumericValue value; - if (item instanceof NumericValue) { - value = (NumericValue) item; + if (item instanceof NumericValue numericValue) { + value = numericValue; } else { value = (NumericValue) item.convertTo(Type.NUMERIC); } @@ -91,4 +91,4 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc {context.getProfiler().end(this, "", result);} return result; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunDocumentURI.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunDocumentURI.java index b052164104e..837f3f7c1f1 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunDocumentURI.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunDocumentURI.java @@ -110,8 +110,8 @@ public Sequence eval(final Sequence contextSequence, final Item contextItem) thr } } else { - if (value instanceof DocumentImpl && ((DocumentImpl) value).getDocumentURI() != null) { - result = new AnyURIValue(this, ((DocumentImpl) value).getDocumentURI()); + if (value instanceof DocumentImpl impl && impl.getDocumentURI() != null) { + result = new AnyURIValue(this, impl.getDocumentURI()); } } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunFloor.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunFloor.java index 83a84f9084b..c80968971e2 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunFloor.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunFloor.java @@ -77,8 +77,8 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc else { final Item item = seq.itemAt(0); NumericValue value; - if (item instanceof NumericValue) { - value = (NumericValue) item; + if (item instanceof NumericValue numericValue) { + value = numericValue; } else { value = (NumericValue) item.convertTo(Type.NUMERIC); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunGenerateId.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunGenerateId.java index d96a51988dc..1f46d3593f2 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunGenerateId.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunGenerateId.java @@ -91,8 +91,8 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro String docId = null; final Document document; if (Type.DOCUMENT == node.getType()) { - if (node instanceof NodeProxy) { - document = (Document) ((NodeProxy) node).getNode(); + if (node instanceof NodeProxy proxy) { + document = (Document) proxy.getNode(); } else { document = (Document) node; } @@ -100,10 +100,10 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro document = node.getOwnerDocument(); } if (document != null) { - if (document instanceof org.exist.dom.memtree.DocumentImpl) { - docId = Long.toString(((org.exist.dom.memtree.DocumentImpl) document).getDocId()); - } else if (document instanceof org.exist.dom.persistent.DocumentImpl) { - docId = Integer.toString(((org.exist.dom.persistent.DocumentImpl) document).getDocId()); + if (document instanceof org.exist.dom.memtree.DocumentImpl impl1) { + docId = Long.toString(impl1.getDocId()); + } else if (document instanceof org.exist.dom.persistent.DocumentImpl impl) { + docId = Integer.toString(impl.getDocId()); } } if (docId == null) { diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunIRIToURI.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunIRIToURI.java index bb94db1500a..5aaba821a8e 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunIRIToURI.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunIRIToURI.java @@ -42,39 +42,44 @@ public class FunIRIToURI extends Function { protected static final String FUNCTION_DESCRIPTION = - "This function converts an xs:string containing an " + - "IRI into a URI according to the rules spelled out " + - "in Section 3.1 of [RFC 3987]. It is idempotent but " + - "not invertible.\n\n" + - "If $iri contains a character that is invalid in an " + - "IRI, such as the space character (see note below), " + - "the invalid character is replaced by its percent-encoded " + - "form as described in [RFC 3986] before the conversion is performed.\n\n" + - "If $iri is the empty sequence, returns the zero-length string.\n\n" + - "Since [RFC 3986] recommends that, for consistency, " + - "URI producers and normalizers should use uppercase " + - "hexadecimal digits for all percent-encodings, this " + - "function must always generate hexadecimal values " + - "using the upper-case letters A-F.\n\n" + - "Notes:\n\n" + + """ +This function converts an xs:string containing an \ +IRI into a URI according to the rules spelled out \ +in Section 3.1 of [RFC 3987]. It is idempotent but \ +not invertible. - "This function does not check whether $iri is a legal " + - "IRI. It treats it as an xs:string and operates on " + - "the characters in the xs:string.\n\n" + +If $iri contains a character that is invalid in an \ +IRI, such as the space character (see note below), \ +the invalid character is replaced by its percent-encoded \ +form as described in [RFC 3986] before the conversion is performed. - "The following printable ASCII characters are invalid " + - "in an IRI: \"<\", \">\", \" \" \" (double quote), " + - "space, \"{\", \"}\", \"|\", \"\\\", \"^\", and \"`\". " + - "Since these characters should not appear in an IRI, " + - "if they do appear in $iri they will be percent-encoded. " + - "In addition, characters outside the range x20-x126 " + - "will be percent-encoded because they are invalid in a URI.\n\n" + +If $iri is the empty sequence, returns the zero-length string. - "Since this function does not escape the PERCENT SIGN " + - "\"%\" and this character is not allowed in data within " + - "a URI, users wishing to convert character strings, " + - "such as file names, that include \"%\" to a URI " + - "should manually escape \"%\" by replacing it with \"%25\"."; +Since [RFC 3986] recommends that, for consistency, \ +URI producers and normalizers should use uppercase \ +hexadecimal digits for all percent-encodings, this \ +function must always generate hexadecimal values \ +using the upper-case letters A-F. + +Notes: + +This function does not check whether $iri is a legal \ +IRI. It treats it as an xs:string and operates on \ +the characters in the xs:string. + +The following printable ASCII characters are invalid \ +in an IRI: "<", ">", " " " (double quote), \ +space, "{", "}", "|", "\\", "^", and "`". \ +Since these characters should not appear in an IRI, \ +if they do appear in $iri they will be percent-encoded. \ +In addition, characters outside the range x20-x126 \ +will be percent-encoded because they are invalid in a URI. + +Since this function does not escape the PERCENT SIGN \ +"%" and this character is not allowed in data within \ +a URI, users wishing to convert character strings, \ +such as file names, that include "%" to a URI \ +should manually escape "%" by replacing it with "%25"."""; public final static FunctionSignature signature = new FunctionSignature( diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunInScopePrefixes.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunInScopePrefixes.java index a0a248dface..939d576d29f 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunInScopePrefixes.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunInScopePrefixes.java @@ -215,8 +215,8 @@ public static void collectNamespacePrefixes(final Element element, final Map arguments) throws XPathException { steps.clear(); - final Expression path = arguments.get(0); + final Expression path = arguments.getFirst(); steps.add(path); if (arguments.size() >= 2) { @@ -148,7 +157,7 @@ public void setArguments(final List arguments) throws XPathException final List steps = BasicExpressionVisitor.findLocationSteps(path); if (!steps.isEmpty()) { - final LocationStep firstStep = steps.get(0); + final LocationStep firstStep = steps.getFirst(); LocationStep lastStep = steps.getLast(); if (firstStep != null && lastStep != null) { final NodeTest test = lastStep.getTest(); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunMax.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunMax.java index 31fe3ee95b3..9c270ec1323 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunMax.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunMax.java @@ -53,37 +53,49 @@ public class FunMax extends CollatingFunction { protected static final String FUNCTION_DESCRIPTION_COMMON_1 = - "Selects an item from the input sequence $arg whose value is " + - "greater than or equal to the value of every other item in the " + - "input sequence. If there are two or more such items, then the " + - "specific item whose value is returned is implementation dependent.\n\n" + - "The following rules are applied to the input sequence:\n\n" + - "- Values of type xs:untypedAtomic in $arg are cast to xs:double.\n" + - "- Numeric and xs:anyURI values are converted to the least common " + - "type that supports the 'ge' operator by a combination of type " + - "promotion and subtype substitution. See Section B.1 Type " + - "PromotionXP and Section B.2 Operator MappingXP.\n\n" + - "The items in the resulting sequence may be reordered in an arbitrary " + - "order. The resulting sequence is referred to below as the converted " + - "sequence. This function returns an item from the converted sequence " + - "rather than the input sequence.\n\n" + - "If the converted sequence is empty, the empty sequence is returned.\n\n" + - "All items in $arg must be numeric or derived from a single base type " + - "for which the 'ge' operator is defined. In addition, the values in the " + - "sequence must have a total order. If date/time values do not have a " + - "timezone, they are considered to have the implicit timezone provided " + - "by the dynamic context for purposes of comparison. Duration values " + - "must either all be xs:yearMonthDuration values or must all be " + - "xs:dayTimeDuration values.\n\n" + - "If any of these conditions is not met, then a type error is raised [err:FORG0006].\n\n" + - "If the converted sequence contains the value NaN, the value NaN is returned.\n\n" + - "If the items in the value of $arg are of type xs:string or types " + - "derived by restriction from xs:string, then the determination of " + - "the item with the largest value is made according to the collation " + - "that is used."; + """ + Selects an item from the input sequence $arg whose value is \ + greater than or equal to the value of every other item in the \ + input sequence. If there are two or more such items, then the \ + specific item whose value is returned is implementation dependent. + + The following rules are applied to the input sequence: + + - Values of type xs:untypedAtomic in $arg are cast to xs:double. + - Numeric and xs:anyURI values are converted to the least common \ + type that supports the 'ge' operator by a combination of type \ + promotion and subtype substitution. See Section B.1 Type \ + PromotionXP and Section B.2 Operator MappingXP. + + The items in the resulting sequence may be reordered in an arbitrary \ + order. The resulting sequence is referred to below as the converted \ + sequence. This function returns an item from the converted sequence \ + rather than the input sequence. + + If the converted sequence is empty, the empty sequence is returned. + + All items in $arg must be numeric or derived from a single base type \ + for which the 'ge' operator is defined. In addition, the values in the \ + sequence must have a total order. If date/time values do not have a \ + timezone, they are considered to have the implicit timezone provided \ + by the dynamic context for purposes of comparison. Duration values \ + must either all be xs:yearMonthDuration values or must all be \ + xs:dayTimeDuration values. + + If any of these conditions is not met, then a type error is raised [err:FORG0006]. + + If the converted sequence contains the value NaN, the value NaN is returned. + + If the items in the value of $arg are of type xs:string or types \ + derived by restriction from xs:string, then the determination of \ + the item with the largest value is made according to the collation \ + that is used."""; protected static final String FUNCTION_DESCRIPTION_2_PARAM = - "If the type of the items in $arg is not xs:string " + - "and $collation-uri is specified, the collation is ignored.\n\n"; + """ + If the type of the items in $arg is not xs:string \ + and $collation-uri is specified, the collation is ignored. + + """; protected static final String FUNCTION_DESCRIPTION_COMMON_2 = "The collation used by the invocation of this function is " + "determined according to the rules in 7.3.1 Collations."; diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunMin.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunMin.java index c98ce39133a..79b635a776d 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunMin.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunMin.java @@ -54,42 +54,48 @@ public class FunMin extends CollatingFunction { protected static final String FUNCTION_DESCRIPTION_COMMON_1 = - "Selects an item from the input sequence $arg whose value is " + - "less than or equal to the value of every other item in the " + - "input sequence. If there are two or more such items, then " + - "the specific item whose value is returned is implementation dependent.\n\n" + - "The following rules are applied to the input sequence:\n\n" + - "- Values of type xs:untypedAtomic in $arg are cast to xs:double.\n" + - "- Numeric and xs:anyURI values are converted to the least common " + - "type that supports the 'le' operator by a combination of type promotion " + - "and subtype substitution. See Section B.1 Type PromotionXP and " + - "Section B.2 Operator MappingXP.\n\n" + - - "The items in the resulting sequence may be reordered in an arbitrary " + - "order. The resulting sequence is referred to below as the converted " + - "sequence. This function returns an item from the converted sequence " + - "rather than the input sequence.\n\n" + - - "If the converted sequence is empty, the empty sequence is returned.\n\n" + - - "All items in $arg must be numeric or derived from a single base type " + - "for which the 'le' operator is defined. In addition, the values in the " + - "sequence must have a total order. If date/time values do not have a " + - "timezone, they are considered to have the implicit timezone provided " + - "by the dynamic context for the purpose of comparison. Duration values " + - "must either all be xs:yearMonthDuration values or must all be " + - "xs:dayTimeDuration values.\n\n" + - - "If any of these conditions is not met, a type error is raised [err:FORG0006].\n\n" + - - "If the converted sequence contains the value NaN, the value NaN is returned.\n\n" + - - "If the items in the value of $arg are of type xs:string or types derived " + - "by restriction from xs:string, then the determination of the item with " + - "the smallest value is made according to the collation that is used. "; + """ +Selects an item from the input sequence $arg whose value is \ +less than or equal to the value of every other item in the \ +input sequence. If there are two or more such items, then \ +the specific item whose value is returned is implementation dependent. + +The following rules are applied to the input sequence: + +- Values of type xs:untypedAtomic in $arg are cast to xs:double. +- Numeric and xs:anyURI values are converted to the least common \ +type that supports the 'le' operator by a combination of type promotion \ +and subtype substitution. See Section B.1 Type PromotionXP and \ +Section B.2 Operator MappingXP. + +The items in the resulting sequence may be reordered in an arbitrary \ +order. The resulting sequence is referred to below as the converted \ +sequence. This function returns an item from the converted sequence \ +rather than the input sequence. + +If the converted sequence is empty, the empty sequence is returned. + +All items in $arg must be numeric or derived from a single base type \ +for which the 'le' operator is defined. In addition, the values in the \ +sequence must have a total order. If date/time values do not have a \ +timezone, they are considered to have the implicit timezone provided \ +by the dynamic context for the purpose of comparison. Duration values \ +must either all be xs:yearMonthDuration values or must all be \ +xs:dayTimeDuration values. + +If any of these conditions is not met, a type error is raised [err:FORG0006]. + +If the converted sequence contains the value NaN, the value NaN is returned. + +If the items in the value of $arg are of type xs:string or types derived \ +by restriction from xs:string, then the determination of the item with \ +the smallest value is made according to the collation that is used. """; protected static final String FUNCTION_DESCRIPTION_2_PARAM = - "If the type of the items in $arg is not xs:string and $collation is " + - "specified, the collation is ignored.\n\n"; + """ + If the type of the items in $arg is not xs:string and $collation is \ + specified, the collation is ignored. + + """; protected static final String FUNCTION_DESCRIPTION_COMMON_2 = "The collation used by the invocation of this function is determined " + "according to the rules in 7.3.1 Collations."; diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunName.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunName.java index 922cac959b4..9d32f9f432a 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunName.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunName.java @@ -47,27 +47,33 @@ public class FunName extends Function { private static final String FUNCTION_DESCRIPTION_0_PARAM = - "Returns the name of the context item as an xs:string that is either " + - "the zero-length string, or has the lexical form of an xs:QName.\n\n"; + """ + Returns the name of the context item as an xs:string that is either \ + the zero-length string, or has the lexical form of an xs:QName. + + """; private static final String FUNCTION_DESCRIPTION_1_PARAM = - "Returns the name of $arg as an xs:string that is either " + - "the zero-length string, or has the lexical form of an xs:QName.\n\n" + - "If the argument is omitted, it defaults to the context item (.). "; + """ + Returns the name of $arg as an xs:string that is either \ + the zero-length string, or has the lexical form of an xs:QName. + + If the argument is omitted, it defaults to the context item (.). """; private static final String FUNCTION_DESCRIPTION_COMMON = - "The behavior of the function if the argument is omitted is exactly " + - "the same as if the context item had been passed as the argument.\n\n" + + """ +The behavior of the function if the argument is omitted is exactly \ +the same as if the context item had been passed as the argument. - "The following errors may be raised: if the context item is undefined " + - "[err:XPDY0002]XP; if the context item is not a node [err:XPTY0004]XP.\n\n" + +The following errors may be raised: if the context item is undefined \ +[err:XPDY0002]XP; if the context item is not a node [err:XPTY0004]XP. - "If the argument is supplied and is the empty sequence, the function " + - "returns the zero-length string.\n\n" + +If the argument is supplied and is the empty sequence, the function \ +returns the zero-length string. - "If the target node has no name (that is, if it is a document node, a comment, " + - "a text node, or a namespace binding having no name), the function returns " + - "the zero-length string.\n\n" + +If the target node has no name (that is, if it is a document node, a comment, \ +a text node, or a namespace binding having no name), the function returns \ +the zero-length string. - "Otherwise, the value returned is fn:string(fn:node-name($arg))."; +Otherwise, the value returned is fn:string(fn:node-name($arg))."""; public final static FunctionSignature[] signatures = { new FunctionSignature( @@ -132,8 +138,8 @@ public Sequence eval(Sequence contextSequence, final Item contextItem) throws XP //TODO : how to improve performance ? final Node n = ((NodeValue) item).getNode(); - if (n instanceof INode) { - result = new StringValue(this, ((INode) n).getQName().getStringValue()); + if (n instanceof INode node) { + result = new StringValue(this, node.getQName().getStringValue()); } else { result = StringValue.EMPTY_STRING; } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNamespaceURI.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNamespaceURI.java index b89ea61f02f..09b579593c9 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNamespaceURI.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNamespaceURI.java @@ -50,21 +50,24 @@ public class FunNamespaceURI extends Function { private static final String FUNCTION_DESCRIPTION_0_PARAM = "Returns the namespace URI of the xs:QName of the context item.\n\n"; private static final String FUNCTION_DESCRIPTION_1_PARAM = - "Returns the namespace URI of the xs:QName of $arg.\n\n" + - "If the argument is omitted, it defaults to the context node (.). "; + """ + Returns the namespace URI of the xs:QName of $arg. + + If the argument is omitted, it defaults to the context node (.). """; private static final String FUNCTION_DESCRIPTION_COMMON = - "The behavior of the function if the argument is omitted is exactly " + - "the same as if the context item had been passed as the argument.\n\n" + - - "The following errors may be raised: if the context item is undefined " + - "[err:XPDY0002]XP; if the context item is not a node [err:XPTY0004]XP.\n\n" + - - "If $arg is neither an element nor an attribute node, or if it is an " + - "element or attribute node whose expanded-QName (as determined by the " + - "dm:node-name accessor in the Section 5.11 node-name AccessorDM) is " + - "in no namespace, then the function returns the xs:anyURI " + - "corresponding to the zero-length string."; + """ +The behavior of the function if the argument is omitted is exactly \ +the same as if the context item had been passed as the argument. + +The following errors may be raised: if the context item is undefined \ +[err:XPDY0002]XP; if the context item is not a node [err:XPTY0004]XP. + +If $arg is neither an element nor an attribute node, or if it is an \ +element or attribute node whose expanded-QName (as determined by the \ +dm:node-name accessor in the Section 5.11 node-name AccessorDM) is \ +in no namespace, then the function returns the xs:anyURI \ +corresponding to the zero-length string."""; public final static FunctionSignature[] signatures = { new FunctionSignature( diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNamespaceURIForPrefix.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNamespaceURIForPrefix.java index 2e01a811b09..1e5e0461a53 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNamespaceURIForPrefix.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNamespaceURIForPrefix.java @@ -45,15 +45,17 @@ public class FunNamespaceURIForPrefix extends BasicFunction { protected static final String FUNCTION_DESCRIPTION = - "Returns the namespace URI of one of the in-scope namespaces " + - "for $element, identified by its namespace prefix.\n\n" + - "If $element has an in-scope namespace whose namespace prefix " + - "is equal to $prefix, it returns the namespace URI of that namespace. " + - "If $prefix is the zero-length string or the empty sequence, it " + - "returns the namespace URI of the default (unnamed) namespace. " + - "Otherwise, it returns the empty sequence.\n\n" + + """ +Returns the namespace URI of one of the in-scope namespaces \ +for $element, identified by its namespace prefix. - "Prefixes are equal only if their Unicode code points match exactly."; +If $element has an in-scope namespace whose namespace prefix \ +is equal to $prefix, it returns the namespace URI of that namespace. \ +If $prefix is the zero-length string or the empty sequence, it \ +returns the namespace URI of the default (unnamed) namespace. \ +Otherwise, it returns the empty sequence. + +Prefixes are equal only if their Unicode code points match exactly."""; public final static FunctionSignature signature = diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNodeName.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNodeName.java index 0059f144872..d45bb74be1f 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNodeName.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNodeName.java @@ -116,8 +116,8 @@ public Sequence eval(Sequence contextSequence, final Item contextItem) throws XP //TODO : how to improve performance ? final Node n = ((NodeValue) item).getNode(); //Returns an expanded-QName for node kinds that can have names. - if (n instanceof INode) { - final QName qn = ((INode) n).getQName(); + if (n instanceof INode node) { + final QName qn = node.getQName(); if (qn.equals(QName.EMPTY_QNAME)) { result = Sequence.EMPTY_SEQUENCE; } else { diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNormalizeSpace.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNormalizeSpace.java index 8f4fb5e7808..cd922e65a86 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNormalizeSpace.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNormalizeSpace.java @@ -48,13 +48,19 @@ public class FunNormalizeSpace extends Function { protected static final String FUNCTION_DESCRIPTION_1_PARAM = "Returns the value of $arg with whitespace normalized by stripping leading "; private static final String FUNCTION_DESCRIPTION_COMMON_1 = - "and trailing whitespace and replacing sequences of one or more than one " + - "whitespace character with a single space, #x20.\n\n" + - "The whitespace characters are defined in the metasymbol S (Production 3) " + - "of [Extensible Markup Language (XML) 1.0 Recommendation (Third Edition)].\n\n" + - "Note:\n\n" + - "The definition of the metasymbol S (Production 3), is " + - "unchanged in [Extensible Markup Language (XML) 1.1 Recommendation].\n\n"; + """ + and trailing whitespace and replacing sequences of one or more than one \ + whitespace character with a single space, #x20. + + The whitespace characters are defined in the metasymbol S (Production 3) \ + of [Extensible Markup Language (XML) 1.0 Recommendation (Third Edition)]. + + Note: + + The definition of the metasymbol S (Production 3), is \ + unchanged in [Extensible Markup Language (XML) 1.1 Recommendation]. + + """; private static final String FUNCTION_DESCRIPTION_1_PARAM_1 = "If the value of $arg is the empty sequence, returns the zero-length string.\n\n"; diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNormalizeUnicode.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNormalizeUnicode.java index 5a6038037d2..dec8750c09c 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNormalizeUnicode.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNormalizeUnicode.java @@ -54,35 +54,42 @@ public class FunNormalizeUnicode extends Function { protected static final Logger logger = LogManager.getLogger(FunNormalizeUnicode.class); protected static final String FUNCTION_DESCRIPTION_0_PARAM = - "Returns the value of the context item normalized according to the " + - "nomalization form \"NFC\"\n\n"; + """ + Returns the value of the context item normalized according to the \ + nomalization form "NFC" + + """; protected static final String FUNCTION_DESCRIPTION_1_PARAM = - "Returns the value of $arg normalized according to the " + - "normalization criteria for a normalization form identified " + - "by the value of $normalization-form. The effective value of " + - "the $normalization-form is computed by removing leading and " + - "trailing blanks, if present, and converting to upper case.\n\n" + - "If the value of $arg is the empty sequence, returns the zero-length string.\n\n" + - "See [Character Model for the World Wide Web 1.0: Normalization] " + - "for a description of the normalization forms.\n\n" + + """ +Returns the value of $arg normalized according to the \ +normalization criteria for a normalization form identified \ +by the value of $normalization-form. The effective value of \ +the $normalization-form is computed by removing leading and \ +trailing blanks, if present, and converting to upper case. + +If the value of $arg is the empty sequence, returns the zero-length string. + +See [Character Model for the World Wide Web 1.0: Normalization] \ +for a description of the normalization forms. + +- If the effective value of $normalization-form is "NFC", then the value \ +returned by the function is the value of $arg in Unicode Normalization Form C (NFC). +- If the effective value of $normalization-form is "NFD", then the value \ +returned by the function is the value of $arg in Unicode Normalization Form D (NFD). +- If the effective value of $normalization-form is "NFKC", then the value \ +returned by the function is the value of $arg in Unicode Normalization Form KC (NFKC). +- If the effective value of $normalization-form is "NFKD", then the value \ +returned by the function is the value of $arg in Unicode Normalization Form KD (NFKD). +- If the effective value of $normalization-form is "FULLY-NORMALIZED", then the value \ +returned by the function is the value of $arg in the fully normalized form. +- If the effective value of $normalization-form is the zero-length string, \ +no normalization is performed and $arg is returned. - "- If the effective value of $normalization-form is \"NFC\", then the value " + - "returned by the function is the value of $arg in Unicode Normalization Form C (NFC).\n" + - "- If the effective value of $normalization-form is \"NFD\", then the value " + - "returned by the function is the value of $arg in Unicode Normalization Form D (NFD).\n" + - "- If the effective value of $normalization-form is \"NFKC\", then the value " + - "returned by the function is the value of $arg in Unicode Normalization Form KC (NFKC).\n" + - "- If the effective value of $normalization-form is \"NFKD\", then the value " + - "returned by the function is the value of $arg in Unicode Normalization Form KD (NFKD).\n" + - "- If the effective value of $normalization-form is \"FULLY-NORMALIZED\", then the value " + - "returned by the function is the value of $arg in the fully normalized form.\n" + - "- If the effective value of $normalization-form is the zero-length string, " + - "no normalization is performed and $arg is returned.\n\n" + - "Conforming implementations must support normalization form \"NFC\" and may " + - "support normalization forms \"NFD\", \"NFKC\", \"NFKD\", \"FULLY-NORMALIZED\". " + - "They may also support other normalization forms with implementation-defined semantics. " + - "If the effective value of the $normalization-form is other than one of the values " + - "supported by the implementation, then an error is raised [err:FOCH0003]."; +Conforming implementations must support normalization form "NFC" and may \ +support normalization forms "NFD", "NFKC", "NFKD", "FULLY-NORMALIZED". \ +They may also support other normalization forms with implementation-defined semantics. \ +If the effective value of the $normalization-form is other than one of the values \ +supported by the implementation, then an error is raised [err:FOCH0003]."""; protected static final FunctionParameterSequenceType ARG_PARAM = new FunctionParameterSequenceType("arg", Type.STRING, Cardinality.ZERO_OR_ONE, "The unicode string to normalize"); protected static final FunctionParameterSequenceType NF_PARAM = new FunctionParameterSequenceType("normalization-form", Type.STRING, Cardinality.EXACTLY_ONE, "The normalization form"); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNot.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNot.java index 64c1389563f..0054d9df228 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNot.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNot.java @@ -47,9 +47,12 @@ public class FunNot extends Function { public final static FunctionSignature signature = new FunctionSignature( new QName("not", Function.BUILTIN_FUNCTION_NS), - " Returns true if the effective boolean " + - "value is false, and false if the effective boolean value is true. \n\n $arg is reduced to an effective boolean value by applying " + - "the fn:boolean() function.", + """ + Returns true if the effective boolean \ + value is false, and false if the effective boolean value is true.\s + + $arg is reduced to an effective boolean value by applying \ + the fn:boolean() function.""", new SequenceType[] { new FunctionParameterSequenceType("arg", Type.ITEM, Cardinality.ZERO_OR_MORE, "The input items")}, new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE, "the negated effective boolean value (ebv) of $arg")); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNumber.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNumber.java index 3ceb116edd4..ca421938d3e 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNumber.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunNumber.java @@ -45,27 +45,35 @@ public class FunNumber extends Function { protected static final String FUNCTION_DESCRIPTION_0_PARAM = - "Returns the value of the context item after atomization, " + - "converted to an xs:double.\n\n" + - "If the context item cannot be " + - "converted to an xs:double, the xs:double value NaN is returned. " + - "If the context item is undefined an error is raised: " + - "[err:XPDY0002]XP.\n\n"; + """ + Returns the value of the context item after atomization, \ + converted to an xs:double. + + If the context item cannot be \ + converted to an xs:double, the xs:double value NaN is returned. \ + If the context item is undefined an error is raised: \ + [err:XPDY0002]XP. + + """; protected static final String FUNCTION_DESCRIPTION_1_PARAM = - "Returns the value indicated by $arg or, if $arg is not specified, " + - "the context item after atomization, converted to an xs:double.\n\n" + - "Calling the zero-argument version of the function is defined to " + - "give the same result as calling the single-argument version with " + - "the context item (.). That is, fn:number() is equivalent to fn:number(.).\n\n" + - "If $arg is the empty sequence or if $arg or the context item cannot be " + - "converted to an xs:double, the xs:double value NaN is returned. " + - "If the " + - "context item is undefined an error is raised: [err:XPDY0002]XP.\n\n" + - "If $arg is the empty sequence, NaN is returned. Otherwise, $arg, or " + - "the context item after atomization, is converted to an xs:double " + - "following the rules of 17.1.3.2 Casting to xs:double. If the conversion " + - "to xs:double fails, the xs:double value NaN is returned."; + """ + Returns the value indicated by $arg or, if $arg is not specified, \ + the context item after atomization, converted to an xs:double. + + Calling the zero-argument version of the function is defined to \ + give the same result as calling the single-argument version with \ + the context item (.). That is, fn:number() is equivalent to fn:number(.). + + If $arg is the empty sequence or if $arg or the context item cannot be \ + converted to an xs:double, the xs:double value NaN is returned. \ + If the \ + context item is undefined an error is raised: [err:XPDY0002]XP. + + If $arg is the empty sequence, NaN is returned. Otherwise, $arg, or \ + the context item after atomization, is converted to an xs:double \ + following the rules of 17.1.3.2 Casting to xs:double. If the conversion \ + to xs:double fails, the xs:double value NaN is returned."""; protected static final FunctionParameterSequenceType ARG_PARAM = new FunctionParameterSequenceType("arg", Type.ANY_ATOMIC_TYPE, Cardinality.ZERO_OR_ONE, "The input item"); protected static final FunctionReturnSequenceType RETURN_TYPE = new FunctionReturnSequenceType(Type.DOUBLE, Cardinality.EXACTLY_ONE, "the numerical value"); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunOnFunctions.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunOnFunctions.java index 6fd3e12e78f..62560bd806e 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunOnFunctions.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunOnFunctions.java @@ -108,8 +108,8 @@ public Sequence eval(Sequence[] args, Sequence contextSequence) return new IntegerValue(this, ref.getSignature().getArgumentCount()); } } catch (final Exception e) { - if (e instanceof XPathException) - {throw (XPathException)e;} + if (e instanceof XPathException exception) + {throw exception;} else {throw new XPathException(this, ErrorCodes.XPST0017, e.getMessage());} } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunParseIetfDate.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunParseIetfDate.java index 2f72af85b32..d414d756aa0 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunParseIetfDate.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunParseIetfDate.java @@ -56,8 +56,9 @@ public class FunParseIetfDate extends BasicFunction { public final static FunctionSignature FNS_PARSE_IETF_DATE = new FunctionSignature( new QName("parse-ietf-date", Function.BUILTIN_FUNCTION_NS), - "Parses a string containing the date and time in IETF format,\n" + - "returning the corresponding xs:dateTime value.", + """ + Parses a string containing the date and time in IETF format, + returning the corresponding xs:dateTime value.""", new SequenceType[]{IETF_DATE}, RETURN ); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunPath.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunPath.java index 5d05e48535e..a78600ea214 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunPath.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunPath.java @@ -93,7 +93,7 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro // This string is prefixed by "Q{http://www.w3.org/2005/xpath-functions}root()" // if the root node is not a document node. pathValues.removeFirst(); - result = new StringValue(this, String.format("Q{%s}root()", Namespaces.XPATH_FUNCTIONS_NS) + String.join("", pathValues)); + result = new StringValue(this, "Q{%s}root()".formatted(Namespaces.XPATH_FUNCTIONS_NS) + String.join("", pathValues)); } else { result = new StringValue(this, String.join("", pathValues)); } @@ -143,7 +143,7 @@ private static void getPathValues(final Node node, final List values) { // the node name, and local is the local part of the node name. value.append('/'); if (node.getNamespaceURI() != null) { - value.append(String.format("@Q{%s}", node.getNamespaceURI())); + value.append("@Q{%s}".formatted(node.getNamespaceURI())); } else { value.append('@'); } @@ -159,7 +159,7 @@ private static void getPathValues(final Node node, final List values) { // node siblings final int textNodePosition = getNodePosition(node); if (textNodePosition > 0) { - value.append(String.format("/text()[%d]", textNodePosition)); + value.append("/text()[%d]".formatted(textNodePosition)); } break; @@ -169,7 +169,7 @@ private static void getPathValues(final Node node, final List values) { // its comment node siblings. final int commentNodePosition = getNodePosition(node); if (commentNodePosition > 0) { - value.append(String.format("/comment()[%d]", commentNodePosition)); + value.append("/comment()[%d]".formatted(commentNodePosition)); } break; @@ -180,7 +180,7 @@ private static void getPathValues(final Node node, final List values) { // like-named processing-instruction node siblings. int processingInstructionNodePosition = getNodePosition(node); if (processingInstructionNodePosition > 0) { - value.append(String.format("/processing-instruction(%s)[%d]", node.getNodeName(), processingInstructionNodePosition)); + value.append("/processing-instruction(%s)[%d]".formatted(node.getNodeName(), processingInstructionNodePosition)); } break; @@ -191,7 +191,7 @@ private static void getPathValues(final Node node, final List values) { // has no name (that is, it represents the default namespace): // namespace::*[Q{http://www.w3.org/2005/xpath-functions}local-name()=""] if (node.getNamespaceURI() != null) { - value.append(String.format("namespace::{%s}", node.getLocalName())); + value.append("namespace::{%s}".formatted(node.getLocalName())); } else { value.append("namespace::*[Q{http://www.w3.org/2005/xpath-functions}local-name()=\"\"]"); } @@ -208,7 +208,7 @@ private static void getPathValues(final Node node, final List values) { value.append((node.getOwnerDocument() != null && node.getOwnerDocument().getDocumentElement() != null) ? "/Q" : "Q"); value.append(((INode) node).getQName().toURIQualifiedName()); if (nodePosition > 0) { - value.append(String.format("[%d]", nodePosition)); + value.append("[%d]".formatted(nodePosition)); } } break; diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunQName.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunQName.java index 5bf90f1b0a2..dfa5cf17691 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunQName.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunQName.java @@ -50,14 +50,18 @@ public class FunQName extends BasicFunction { public final static FunctionSignature signature = new FunctionSignature( new QName("QName", Function.BUILTIN_FUNCTION_NS), - "Returns an xs:QName with the namespace URI given in $uri. If $uri is " + - "the zero-length string or the empty sequence, it represents \"no namespace\"; in " + - "this case, if the value of $qname contains a colon (:), an error is " + - "raised [err:FOCA0002]. The prefix (or absence of a prefix) in $qname is " + - "retained in the returned xs:QName value. The local name in the result is " + - "taken from the local part of $qname.\n\nIf $qname does not have " + - "the correct lexical form for xs:QName an error is raised [err:FOCA0002].\n\n" + - "Note that unlike xs:QName this function does not require a xs:string literal as the argument.", + """ + Returns an xs:QName with the namespace URI given in $uri. If $uri is \ + the zero-length string or the empty sequence, it represents "no namespace"; in \ + this case, if the value of $qname contains a colon (:), an error is \ + raised [err:FOCA0002]. The prefix (or absence of a prefix) in $qname is \ + retained in the returned xs:QName value. The local name in the result is \ + taken from the local part of $qname. + + If $qname does not have \ + the correct lexical form for xs:QName an error is raised [err:FOCA0002]. + + Note that unlike xs:QName this function does not require a xs:string literal as the argument.""", new SequenceType[] { new FunctionParameterSequenceType("uri", Type.STRING, Cardinality.ZERO_OR_ONE, "The namespace URI"), new FunctionParameterSequenceType("qname", Type.STRING, Cardinality.EXACTLY_ONE, "The prefix") diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRemove.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRemove.java index 5dd15172254..aa64816acec 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRemove.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRemove.java @@ -50,13 +50,16 @@ public class FunRemove extends Function { public final static FunctionSignature signature = new FunctionSignature( new QName("remove", Function.BUILTIN_FUNCTION_NS), - "Returns a new sequence constructed from the value of $target with the item " + - "at $position removed.\n\nIf $position " + - "is less than 1 or greater than the number of items in $target, $target is returned. " + - "Otherwise, the value returned by the function consists of all items of $target " + - "whose index is less than $position, followed by all items of $target whose index " + - "is greater than $position. If $target is the empty sequence, the empty sequence " + - "is returned.", + """ + Returns a new sequence constructed from the value of $target with the item \ + at $position removed. + + If $position \ + is less than 1 or greater than the number of items in $target, $target is returned. \ + Otherwise, the value returned by the function consists of all items of $target \ + whose index is less than $position, followed by all items of $target whose index \ + is greater than $position. If $target is the empty sequence, the empty sequence \ + is returned.""", new SequenceType[] { new FunctionParameterSequenceType("target", Type.ITEM, Cardinality.ZERO_OR_MORE, "The input sequence"), new FunctionParameterSequenceType("position", Type.INTEGER, Cardinality.EXACTLY_ONE, "The position of the value to be removed") @@ -90,9 +93,9 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc {result= seq;} else { pos--; - if (seq instanceof NodeSet) { + if (seq instanceof NodeSet set) { result = new ExtArrayNodeSet(); - result.addAll((NodeSet) seq); + result.addAll(set); result = ((NodeSet)result).except((NodeSet) seq.itemAt(pos)); } else { result = new ValueSequence(); @@ -113,4 +116,4 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc public int getDependencies() { return Dependency.NO_DEPENDENCY; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunReplace.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunReplace.java index 6dea523469a..1d7359765eb 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunReplace.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunReplace.java @@ -46,29 +46,43 @@ public class FunReplace extends BasicFunction { private static final QName FS_REPLACE_NAME = new QName("replace", Function.BUILTIN_FUNCTION_NS); private static final String FS_REPLACE_DESCRIPTION = - "The function returns the xs:string that is obtained by replacing each non-overlapping substring " + - "of $input that matches the given $pattern with an occurrence of the $replacement string.\n\n" + - "The $flags argument is interpreted in the same manner as for the fn:matches() function.\n\n" + - "Calling the four argument version with the $flags argument set to a " + - "zero-length string gives the same effect as using the three argument version.\n\n" + - "If $input is the empty sequence, it is interpreted as the zero-length string.\n\nIf two overlapping " + - "substrings of $input both match the $pattern, then only the first one (that is, the one whose first " + - "character comes first in the $input string) is replaced.\n\nWithin the $replacement string, a variable " + - "$N may be used to refer to the substring captured by the Nth parenthesized sub-expression in the " + - "regular expression. For each match of the pattern, these variables are assigned the value of the " + - "content matched by the relevant sub-expression, and the modified replacement string is then " + - "substituted for the characters in $input that matched the pattern. $0 refers to the substring " + - "captured by the regular expression as a whole.\n\nMore specifically, the rules are as follows, " + - "where S is the number of parenthesized sub-expressions in the regular expression, and N is the " + - "decimal number formed by taking all the digits that consecutively follow the $ character:\n\n" + - "1. If N=0, then the variable is replaced by the substring matched by the regular expression as a whole.\n\n" + - "2. If 1<=N<=S, then the variable is replaced by the substring captured by the Nth parenthesized " + - "sub-expression. If the Nth parenthesized sub-expression was not matched, then the variable " + - "is replaced by the zero-length string.\n\n" + - "3. If SS and N>9), the last digit of N is taken to be a literal character to be " + - "included \"as is\" in the replacement string, and the rules are reapplied using the number N " + - "formed by stripping off this last digit."; + """ + The function returns the xs:string that is obtained by replacing each non-overlapping substring \ + of $input that matches the given $pattern with an occurrence of the $replacement string. + + The $flags argument is interpreted in the same manner as for the fn:matches() function. + + Calling the four argument version with the $flags argument set to a \ + zero-length string gives the same effect as using the three argument version. + + If $input is the empty sequence, it is interpreted as the zero-length string. + + If two overlapping \ + substrings of $input both match the $pattern, then only the first one (that is, the one whose first \ + character comes first in the $input string) is replaced. + + Within the $replacement string, a variable \ + $N may be used to refer to the substring captured by the Nth parenthesized sub-expression in the \ + regular expression. For each match of the pattern, these variables are assigned the value of the \ + content matched by the relevant sub-expression, and the modified replacement string is then \ + substituted for the characters in $input that matched the pattern. $0 refers to the substring \ + captured by the regular expression as a whole. + + More specifically, the rules are as follows, \ + where S is the number of parenthesized sub-expressions in the regular expression, and N is the \ + decimal number formed by taking all the digits that consecutively follow the $ character: + + 1. If N=0, then the variable is replaced by the substring matched by the regular expression as a whole. + + 2. If 1<=N<=S, then the variable is replaced by the substring captured by the Nth parenthesized \ + sub-expression. If the Nth parenthesized sub-expression was not matched, then the variable \ + is replaced by the zero-length string. + + 3. If SS and N>9), the last digit of N is taken to be a literal character to be \ + included "as is" in the replacement string, and the rules are reapplied using the number N \ + formed by stripping off this last digit."""; private static final FunctionParameterSequenceType FS_TOKENIZE_PARAM_INPUT = optParam("input", Type.STRING, "The input string"); private static final FunctionParameterSequenceType FS_TOKENIZE_PARAM_PATTERN = param("pattern", Type.STRING, "The pattern to match"); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunResolveQName.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunResolveQName.java index 6eb63ed7ff5..bbea9ae21ca 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunResolveQName.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunResolveQName.java @@ -54,19 +54,31 @@ public class FunResolveQName extends BasicFunction { public final static FunctionSignature signature = new FunctionSignature(new QName("resolve-QName", Function.BUILTIN_FUNCTION_NS), - "Returns an xs:QName value (that is, an expanded-QName) by taking an xs:string that has the lexical " + - "form of an xs:QName (a string in the form \"prefix:local-name\" or \"local-name\") and resolving it " + - "using the in-scope namespaces for a given element.\n\nIf $qname does not have the correct lexical " + - "form for xs:QName an error is raised [err:FOCA0002].\n\nIf $qname is the empty sequence, returns " + - "the empty sequence.\n\nMore specifically, the function searches the namespace bindings of " + - "$element for a binding whose name matches the prefix of $qname, or the zero-length string if " + - "it has no prefix, and constructs an expanded-QName whose local name is taken from the supplied " + - "$qname, and whose namespace URI is taken from the string value of the namespace binding.\n\n" + - "If the $qname has a prefix and if there is no namespace binding for $element that matches this " + - "prefix, then an error is raised [err:FONS0004].\n\nIf the $qname has no prefix, and there is " + - "no namespace binding for $element corresponding to the default (unnamed) namespace, then the " + - "resulting expanded-QName has no namespace part.\n\nThe prefix (or absence of a prefix) in the " + - "supplied $qname argument is retained in the returned expanded-QName.", + """ + Returns an xs:QName value (that is, an expanded-QName) by taking an xs:string that has the lexical \ + form of an xs:QName (a string in the form "prefix:local-name" or "local-name") and resolving it \ + using the in-scope namespaces for a given element. + + If $qname does not have the correct lexical \ + form for xs:QName an error is raised [err:FOCA0002]. + + If $qname is the empty sequence, returns \ + the empty sequence. + + More specifically, the function searches the namespace bindings of \ + $element for a binding whose name matches the prefix of $qname, or the zero-length string if \ + it has no prefix, and constructs an expanded-QName whose local name is taken from the supplied \ + $qname, and whose namespace URI is taken from the string value of the namespace binding. + + If the $qname has a prefix and if there is no namespace binding for $element that matches this \ + prefix, then an error is raised [err:FONS0004]. + + If the $qname has no prefix, and there is \ + no namespace binding for $element corresponding to the default (unnamed) namespace, then the \ + resulting expanded-QName has no namespace part. + + The prefix (or absence of a prefix) in the \ + supplied $qname argument is retained in the returned expanded-QName.""", new SequenceType[] { new FunctionParameterSequenceType("qname", Type.STRING, Cardinality.ZERO_OR_ONE, "The QName name"), new FunctionParameterSequenceType("element", Type.ELEMENT, Cardinality.EXACTLY_ONE, "The element") diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunResolveURI.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunResolveURI.java index 150963daad2..e9498acf118 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunResolveURI.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunResolveURI.java @@ -58,15 +58,19 @@ public class FunResolveURI extends Function { "Resolves $relative against $base "; protected static final String FUNCTION_DESCRIPTION_COMMON = - "using an algorithm such as the ones described " + - "in [RFC 2396] or [RFC 3986], and the resulting absolute " + - "URI reference is returned. An error may be raised " + - "[err:FORG0009] in the resolution process.\n\n" + - "If $relative is an absolute URI reference, it is returned " + - "unchanged.\n\n" + - "If $relative or $base is not a valid xs:anyURI an error " + - "is raised [err:FORG0002].\n\n" + - "If $relative is the empty sequence, the empty sequence is returned."; + """ + using an algorithm such as the ones described \ + in [RFC 2396] or [RFC 3986], and the resulting absolute \ + URI reference is returned. An error may be raised \ + [err:FORG0009] in the resolution process. + + If $relative is an absolute URI reference, it is returned \ + unchanged. + + If $relative or $base is not a valid xs:anyURI an error \ + is raised [err:FORG0002]. + + If $relative is the empty sequence, the empty sequence is returned."""; protected static final FunctionParameterSequenceType RELATIVE_ARG = new FunctionParameterSequenceType("relative", Type.STRING, Cardinality.ZERO_OR_ONE, "The relative URI"); protected static final FunctionParameterSequenceType BASE_ARG = new FunctionParameterSequenceType("base", Type.STRING, Cardinality.EXACTLY_ONE, "The base URI"); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoot.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoot.java index f6316a175ba..fcc444c6cfb 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoot.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoot.java @@ -54,12 +54,16 @@ public class FunRoot extends Function { protected static final String FUNCTION_DESCRIPTION_0_PARAM = "Returns the root of the tree to which the context item belongs. "; protected static final String FUNCTION_DESCRIPTION_1_PARAM = - "Returns the root of the tree to which $arg belongs. " + - "This will usually, but not necessarily, be a document node.\n\n" + - "If $arg is the empty sequence, the empty sequence is returned.\n\n" + - "If $arg is a document node, $arg is returned.\n\n" + - " The behavior of the zero argument version of the function is " + - "exactly the same as if the context item had been passed in $arg."; + """ + Returns the root of the tree to which $arg belongs. \ + This will usually, but not necessarily, be a document node. + + If $arg is the empty sequence, the empty sequence is returned. + + If $arg is a document node, $arg is returned. + + The behavior of the zero argument version of the function is \ + exactly the same as if the context item had been passed in $arg."""; public final static FunctionSignature[] signatures = { new FunctionSignature( diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoundBase.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoundBase.java index ba7b1050a3b..ade370d999a 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoundBase.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoundBase.java @@ -54,8 +54,8 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro final Item item = args[0].itemAt(0); final NumericValue value; - if (item instanceof NumericValue) { - value = (NumericValue) item; + if (item instanceof NumericValue numericValue) { + value = numericValue; } else { value = (NumericValue) item.convertTo(Type.NUMERIC); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoundHalfToEven.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoundHalfToEven.java index 3846d834e05..94aed1947a6 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoundHalfToEven.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunRoundHalfToEven.java @@ -54,28 +54,35 @@ public class FunRoundHalfToEven extends FunRoundBase { "value to $arg that is a multiple of ten to the power of minus " + "$precision. "; protected static final String FUNCTION_DESCRIPTION_COMMON = - "If two such values are equally near (e.g. if the " + - "fractional part in $arg is exactly .500...), the function returns " + - "the one whose least significant digit is even.\n\nIf the type of " + - "$arg is one of the four numeric types xs:float, xs:double, " + - "xs:decimal or xs:integer the type of the result is the same as " + - "the type of $arg. If the type of $arg is a type derived from one " + - "of the numeric types, the result is an instance of the " + - "base numeric type.\n\n" + - "The three argument version of the function with $precision = 0 " + - "produces the same result as the two argument version.\n\n" + - "For arguments of type xs:float and xs:double, if the argument is " + - "NaN, positive or negative zero, or positive or negative infinity, " + - "then the result is the same as the argument. In all other cases, " + - "the argument is cast to xs:decimal, the function is applied to this " + - "xs:decimal value, and the resulting xs:decimal is cast back to " + - "xs:float or xs:double as appropriate to form the function result. " + - "If the resulting xs:decimal value is zero, then positive or negative " + - "zero is returned according to the sign of the original argument.\n\n" + - "Note that the process of casting to xs:decimal " + - "may result in an error [err:FOCA0001].\n\n" + - "If $arg is of type xs:float or xs:double, rounding occurs on the " + - "value of the mantissa computed with exponent = 0."; + """ + If two such values are equally near (e.g. if the \ + fractional part in $arg is exactly .500...), the function returns \ + the one whose least significant digit is even. + + If the type of \ + $arg is one of the four numeric types xs:float, xs:double, \ + xs:decimal or xs:integer the type of the result is the same as \ + the type of $arg. If the type of $arg is a type derived from one \ + of the numeric types, the result is an instance of the \ + base numeric type. + + The three argument version of the function with $precision = 0 \ + produces the same result as the two argument version. + + For arguments of type xs:float and xs:double, if the argument is \ + NaN, positive or negative zero, or positive or negative infinity, \ + then the result is the same as the argument. In all other cases, \ + the argument is cast to xs:decimal, the function is applied to this \ + xs:decimal value, and the resulting xs:decimal is cast back to \ + xs:float or xs:double as appropriate to form the function result. \ + If the resulting xs:decimal value is zero, then positive or negative \ + zero is returned according to the sign of the original argument. + + Note that the process of casting to xs:decimal \ + may result in an error [err:FOCA0001]. + + If $arg is of type xs:float or xs:double, rounding occurs on the \ + value of the mantissa computed with exponent = 0."""; protected static final FunctionReturnSequenceType RETURN_TYPE = new FunctionReturnSequenceType(Type.NUMERIC, Cardinality.ZERO_OR_ONE, "the rounded value"); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunStartsWith.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunStartsWith.java index beddb98cdbe..22049bd431e 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunStartsWith.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunStartsWith.java @@ -42,23 +42,30 @@ public class FunStartsWith extends CollatingFunction { protected static final String FUNCTION_DESCRIPTION = - "Returns an xs:boolean indicating whether or not " + - "the value of $source starts with a sequence of collation " + - "units that provides a minimal match to the collation " + - "units of $prefix according to the collation that is used.\n\n" + - "Note:\n\n" + - "\"Minimal match\" is defined in [Unicode Collation Algorithm].\n\n" + - "If the value of $source or $prefix is the empty sequence, or " + - "contains only ignorable collation units, it is interpreted " + - "as the zero-length string.\n\nIf the value of $prefix is the " + - "zero-length string, then the function returns true. If the " + - "value of $source is the zero-length string and the value of " + - "$prefix is not the zero-length string, then the function " + - "returns false.\n\n" + - "The collation used by the invocation of this function is " + - "determined according to the rules in 7.3.1 Collations. " + - "If the specified collation does not support collation " + - "units an error may be raised [err:FOCH0004]. "; + """ + Returns an xs:boolean indicating whether or not \ + the value of $source starts with a sequence of collation \ + units that provides a minimal match to the collation \ + units of $prefix according to the collation that is used. + + Note: + + "Minimal match" is defined in [Unicode Collation Algorithm]. + + If the value of $source or $prefix is the empty sequence, or \ + contains only ignorable collation units, it is interpreted \ + as the zero-length string. + + If the value of $prefix is the \ + zero-length string, then the function returns true. If the \ + value of $source is the zero-length string and the value of \ + $prefix is not the zero-length string, then the function \ + returns false. + + The collation used by the invocation of this function is \ + determined according to the rules in 7.3.1 Collations. \ + If the specified collation does not support collation \ + units an error may be raised [err:FOCH0004]. """; protected static final FunctionParameterSequenceType ARG1_PARAM = new FunctionParameterSequenceType("source", Type.STRING, Cardinality.ZERO_OR_ONE, "The source string"); protected static final FunctionParameterSequenceType ARG2_PARAM = new FunctionParameterSequenceType("prefix", Type.STRING, Cardinality.ZERO_OR_ONE, "The string to determine if is a prefix of $source"); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunStrLength.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunStrLength.java index dbc3eac6b3e..f56586b006f 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunStrLength.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunStrLength.java @@ -44,16 +44,18 @@ public class FunStrLength extends Function { public final static FunctionSignature[] signatures = { new FunctionSignature( new QName("string-length", Function.BUILTIN_FUNCTION_NS), - "Returns an xs:integer equal to the length in characters of the value of the context item.\n" + - "If the context item is undefined an error is raised. ", + """ + Returns an xs:integer equal to the length in characters of the value of the context item. + If the context item is undefined an error is raised. """, new SequenceType[0], new FunctionReturnSequenceType(Type.INTEGER, Cardinality.EXACTLY_ONE, "the length in characters") ), new FunctionSignature( new QName("string-length", Function.BUILTIN_FUNCTION_NS), - "Returns an xs:integer equal to the length in characters of the value of $arg.\n" + - "If the value of $arg is the empty sequence, the xs:integer 0 is returned.\n" + - "If no argument is supplied, $arg defaults to the string value (calculated using fn:string()) of the context item (.). If no argument is supplied or if the argument is the context item and the context item is undefined an error is raised", + """ + Returns an xs:integer equal to the length in characters of the value of $arg. + If the value of $arg is the empty sequence, the xs:integer 0 is returned. + If no argument is supplied, $arg defaults to the string value (calculated using fn:string()) of the context item (.). If no argument is supplied or if the argument is the context item and the context item is undefined an error is raised""", new SequenceType[]{ new FunctionParameterSequenceType("arg", Type.STRING, Cardinality.ZERO_OR_ONE, "The input string") }, diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunTranslate.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunTranslate.java index c13a449b0e5..0da879b7414 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunTranslate.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunTranslate.java @@ -48,15 +48,23 @@ public class FunTranslate extends Function { public final static FunctionSignature signature = new FunctionSignature( new QName("translate", Function.BUILTIN_FUNCTION_NS), - "Returns the value of $arg modified so that every character in the value of $arg that occurs at some position N in the " + - "value of $map has been replaced by the character that occurs at position N in the value of $trans.\n\n" + - "If the value of $arg is the empty sequence, the zero-length string is returned.\n\n" + - "Every character in the value of $arg that does not appear in the value of $map is unchanged.\n\n" + - "Every character in the value of $arg that appears at some position M in the value of $map, where the value of " + - "$trans is less than M characters in length, is omitted from the returned value. If $map is the zero-length " + - "string $arg is returned.\n\nIf a character occurs more than once in $map, then the first occurrence determines " + - "the replacement character. If $trans is longer than $map, the excess characters are ignored.\n\n" + - "i.e. fn:translate(\"bar\",\"abc\",\"ABC\") returns \"BAr\"", + """ + Returns the value of $arg modified so that every character in the value of $arg that occurs at some position N in the \ + value of $map has been replaced by the character that occurs at position N in the value of $trans. + + If the value of $arg is the empty sequence, the zero-length string is returned. + + Every character in the value of $arg that does not appear in the value of $map is unchanged. + + Every character in the value of $arg that appears at some position M in the value of $map, where the value of \ + $trans is less than M characters in length, is omitted from the returned value. If $map is the zero-length \ + string $arg is returned. + + If a character occurs more than once in $map, then the first occurrence determines \ + the replacement character. If $trans is longer than $map, the excess characters are ignored. + + i.e. fn:translate("bar","abc","ABC") returns "BAr"\ + """, new SequenceType[] { new FunctionParameterSequenceType("arg", Type.STRING, Cardinality.ZERO_OR_ONE, "The string to be translated"), new FunctionParameterSequenceType("map", Type.STRING, Cardinality.EXACTLY_ONE, "The map string"), diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunUriCollection.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunUriCollection.java index 3b9426af31e..35576aac81f 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/FunUriCollection.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/FunUriCollection.java @@ -114,7 +114,7 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro final String uriWithQueryString = args[0].toString(); final int queryStringIndex = uriWithQueryString.indexOf('?'); final String uriWithoutQueryString = (queryStringIndex >= 0) ? uriWithQueryString.substring(0, queryStringIndex) : uriWithQueryString; - String uriWithoutStableQueryString = uriWithQueryString.replaceAll(String.format("%s\\s*=\\s*\\byes|no\\b\\s*&+", KEY_STABLE), ""); + String uriWithoutStableQueryString = uriWithQueryString.replaceAll("%s\\s*=\\s*\\byes|no\\b\\s*&+".formatted(KEY_STABLE), ""); if (uriWithoutStableQueryString.endsWith("?")) { uriWithoutStableQueryString = uriWithoutStableQueryString.substring(0, uriWithoutStableQueryString.length() - 1); } @@ -123,7 +123,7 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro try { uri = XmldbURI.xmldbUriFor(uriWithoutQueryString); } catch (URISyntaxException e) { - throw new XPathException(this, ErrorCodes.FODC0004, String.format("\"%s\" is not a valid URI.", args[0].toString())); + throw new XPathException(this, ErrorCodes.FODC0004, "\"%s\" is not a valid URI.".formatted(args[0].toString())); } final Map queryStringMap = parseQueryString(uriWithQueryString); @@ -162,7 +162,7 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro } } } else { - throw new XPathException(this, ErrorCodes.FODC0002, String.format("Collection \"%s\" not found.", uri)); + throw new XPathException(this, ErrorCodes.FODC0002, "Collection \"%s\" not found.".formatted(uri)); } } catch (final LockException | PermissionDeniedException e) { throw new XPathException(this, ErrorCodes.FODC0002, e); @@ -226,14 +226,14 @@ private void checkQueryStringMap(final Map queryStringMap) throw final String value = queryStringEntry.getValue(); if (key.equals(KEY_CONTENT_TYPE)) { if (Arrays.stream(VALUE_CONTENT_TYPES).noneMatch(contentTypeValue -> contentTypeValue.equals(value))) { - throw new XPathException(this, ErrorCodes.FODC0004, String.format("Invalid query-string value \"%s\".", queryStringEntry)); + throw new XPathException(this, ErrorCodes.FODC0004, "Invalid query-string value \"%s\".".formatted(queryStringEntry)); } } else if (key.equals(KEY_STABLE)) { if (Arrays.stream(VALUE_STABLES).noneMatch(stableValue -> stableValue.equals(value))) { - throw new XPathException(this, ErrorCodes.FODC0004, String.format("Invalid query-string value \"%s\".", queryStringEntry)); + throw new XPathException(this, ErrorCodes.FODC0004, "Invalid query-string value \"%s\".".formatted(queryStringEntry)); } } else if (!key.equals(KEY_MATCH)) { - throw new XPathException(this, ErrorCodes.FODC0004, String.format("Unexpected query string \"%s\".", queryStringEntry)); + throw new XPathException(this, ErrorCodes.FODC0004, "Unexpected query string \"%s\".".formatted(queryStringEntry)); } } } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Convert.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Convert.java index 21b6cc83b09..98a02f5aadb 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Convert.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Convert.java @@ -94,8 +94,8 @@ static Item ofItem(final XdmItem xdmItem) throws XPathException { throw new XPathException(ErrorCodes.XPTY0004, "net.sf.saxon.value.AtomicValue " + atomicValue + COULD_NOT_BE_CONVERTED + "atomic value"); } - } else if (xdmItem instanceof XdmNode) { - return ToExist.ofNode((XdmNode)xdmItem); + } else if (xdmItem instanceof XdmNode node) { + return ToExist.ofNode(node); } throw new XPathException(ErrorCodes.XPTY0004, diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Options.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Options.java index cb4b4a8a8ad..e59e6567a1b 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Options.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Options.java @@ -540,8 +540,8 @@ private XSLTVersion getXsltVersion(final Source xsltStylesheet) throws XPathExce private XSLTVersion domExtractXsltVersion(final Source xsltStylesheet) throws XPathException { Node node = ((DOMSource) xsltStylesheet).getNode(); - if (node instanceof Document) { - node = ((Document) node).getDocumentElement(); + if (node instanceof Document document) { + node = document.getDocumentElement(); } String version = ""; diff --git a/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Transform.java b/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Transform.java index fe9d58239f8..4b398934b5f 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Transform.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/fn/transform/Transform.java @@ -224,8 +224,9 @@ private XsltExecutable compileExecutable(final Options options) throws XPathExce if (options.resolvedStylesheetBaseURI.isEmpty() && !hrefURI.isAbsolute() && StringUtils.isEmpty(base)) { final XPathException resolutionException = new XPathException(fnTransform, ErrorCodes.XTSE0165, - "transform using a relative href, \n" + - "using option stylesheet-text, but without stylesheet-base-uri"); + """ + transform using a relative href,\s + using option stylesheet-text, but without stylesheet-base-uri"""); throw new TransformerException(resolutionException); } } catch (final IllegalArgumentException e) { @@ -257,8 +258,8 @@ private XsltExecutable compileExecutable(final Options options) throws XPathExce private XPathException originalXPathException(final String prefix, @Nonnull final Throwable e, final ErrorCodes.ErrorCode defaultErrorCode) { Throwable cause = e; while (cause != null) { - if (cause instanceof XPathException) { - return new XPathException(fnTransform, ((XPathException) cause).getErrorCode(), prefix + cause.getMessage()); + if (cause instanceof XPathException exception) { + return new XPathException(fnTransform, exception.getErrorCode(), prefix + cause.getMessage()); } cause = cause.getCause(); } @@ -364,8 +365,8 @@ private MapType invokeApplyTemplates() throws XPathException, SaxonApiException if (options.initialMatchSelection.isPresent()) { final Sequence initialMatchSelection = options.initialMatchSelection.get(); final Item item = initialMatchSelection.itemAt(0); - if (item instanceof Document) { - final Source sourceIMS = new DOMSource((Document)item, context.getBaseURI().getStringValue()); + if (item instanceof Document document) { + final Source sourceIMS = new DOMSource(document, context.getBaseURI().getStringValue()); xslt30Transformer.applyTemplates(sourceIMS, destination); } else { final XdmValue selection = toSaxon.of(initialMatchSelection); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/inspect/InspectFunctionHelper.java b/exist-core/src/main/java/org/exist/xquery/functions/inspect/InspectFunctionHelper.java index 5b390129b11..bc6b1956867 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/inspect/InspectFunctionHelper.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/inspect/InspectFunctionHelper.java @@ -133,11 +133,11 @@ private static void writeParameters(final FunctionSignature sig, final MemTreeBu attribs.clear(); attribs.addAttribute("", "type", "type", "CDATA", Type.getTypeName(type.getPrimaryType())); attribs.addAttribute("", "cardinality", "cardinality", "CDATA", type.getCardinality().getHumanDescription()); - if (type instanceof FunctionParameterSequenceType) - {attribs.addAttribute("", "var", "var", "CDATA", ((FunctionParameterSequenceType)type).getAttributeName());} + if (type instanceof FunctionParameterSequenceType sequenceType) + {attribs.addAttribute("", "var", "var", "CDATA", sequenceType.getAttributeName());} builder.startElement(ARGUMENT_QNAME, attribs); - if (type instanceof FunctionParameterSequenceType) { - builder.characters(((FunctionParameterSequenceType)type).getDescription()); + if (type instanceof FunctionParameterSequenceType sequenceType) { + builder.characters(sequenceType.getDescription()); } builder.endElement(); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/integer/DigitsIntegerPicture.java b/exist-core/src/main/java/org/exist/xquery/functions/integer/DigitsIntegerPicture.java index a8697e207a2..105e549b2c9 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/integer/DigitsIntegerPicture.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/integer/DigitsIntegerPicture.java @@ -182,7 +182,7 @@ private void regularizeGroups() { for (int i = 1; i < groups.size(); i++) { final Group group = groups.get(i); - if (!group.separator.isPresent()) group.separator = prev.separator; + if (group.separator.isEmpty()) group.separator = prev.separator; if (i > 1 && (group.total() != prev.total())) return; if (i == 1 && prev.total() > group.total()) return; if (!group.separator.equals(prev.separator)) return; diff --git a/exist-core/src/main/java/org/exist/xquery/functions/map/MapType.java b/exist-core/src/main/java/org/exist/xquery/functions/map/MapType.java index 2d635921100..de724d4792b 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/map/MapType.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/map/MapType.java @@ -162,8 +162,8 @@ public MapType(final Expression expression, final XQueryContext context, final I public void add(final AbstractMapType other) { setKeyType(other.key() != null ? other.key().getType() : UNKNOWN_KEY_TYPE); - if(other instanceof MapType) { - map = map.union(((MapType)other).map); + if(other instanceof MapType type) { + map = map.union(type.map); } else { // create a transient map diff --git a/exist-core/src/main/java/org/exist/xquery/functions/request/GetContextPath.java b/exist-core/src/main/java/org/exist/xquery/functions/request/GetContextPath.java index 0e9598890cb..62e02775a88 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/request/GetContextPath.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/request/GetContextPath.java @@ -46,9 +46,10 @@ public class GetContextPath extends StrictRequestFunction { new FunctionReturnSequenceType(Type.STRING, Cardinality.EXACTLY_ONE, "the context path of the current request")), new FunctionSignature( new QName("get-servlet-path", RequestModule.NAMESPACE_URI, RequestModule.PREFIX), - "Returns the servlet path of the current request, i.e. the portion of the request URI that " + - "points to the servlet which is handling the request.\n"+ - "For example an xquery GET or POST to /some/path/myfile.xq/extra/path will return /some/path/myfile.xq when myfile.xq is executed.", + """ + Returns the servlet path of the current request, i.e. the portion of the request URI that \ + points to the servlet which is handling the request. + For example an xquery GET or POST to /some/path/myfile.xq/extra/path will return /some/path/myfile.xq when myfile.xq is executed.""", null, new FunctionReturnSequenceType(Type.STRING, Cardinality.EXACTLY_ONE, "the servlet path of the current request")) }; diff --git a/exist-core/src/main/java/org/exist/xquery/functions/request/GetCookieValue.java b/exist-core/src/main/java/org/exist/xquery/functions/request/GetCookieValue.java index 13743d07de2..d2db0e4f0f9 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/request/GetCookieValue.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/request/GetCookieValue.java @@ -65,7 +65,7 @@ public GetCookieValue(final XQueryContext context) { @Override public Sequence eval(final Sequence[] args, final Optional request) throws XPathException { - if(!request.isPresent()) { + if(request.isEmpty()) { return Sequence.EMPTY_SEQUENCE; } else { return getCookieValue(args, request.get()); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/request/GetParameter.java b/exist-core/src/main/java/org/exist/xquery/functions/request/GetParameter.java index 45c9edbe75b..e5bb2f10e4e 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/request/GetParameter.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/request/GetParameter.java @@ -88,7 +88,7 @@ public Sequence eval(final Sequence[] args, final Optional reque failOnError = true; } - if (!request.isPresent()) { + if (request.isEmpty()) { if (failOnError) { throw new XPathException(this, ErrorCodes.XPDY0002, "Variable $request is not bound to an Java object."); } else { diff --git a/exist-core/src/main/java/org/exist/xquery/functions/request/GetPathInfo.java b/exist-core/src/main/java/org/exist/xquery/functions/request/GetPathInfo.java index dbc45a716a4..d5adbb3fa77 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/request/GetPathInfo.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/request/GetPathInfo.java @@ -43,8 +43,9 @@ public class GetPathInfo extends StrictRequestFunction { public final static FunctionSignature signature = new FunctionSignature( new QName("get-path-info", RequestModule.NAMESPACE_URI, RequestModule.PREFIX), - "Returns any extra path information associated with the URL the client sent when it made this request.\n" + - "For example an xquery GET or POST to /some/path/myfile.xq/extra/path will return /extra/path when myfile.xq is executed.", + """ + Returns any extra path information associated with the URL the client sent when it made this request. + For example an xquery GET or POST to /some/path/myfile.xq/extra/path will return /extra/path when myfile.xq is executed.""", null, new FunctionReturnSequenceType(Type.STRING, Cardinality.EXACTLY_ONE, "the request path information")); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/securitymanager/SetPrincipalMetadataFunction.java b/exist-core/src/main/java/org/exist/xquery/functions/securitymanager/SetPrincipalMetadataFunction.java index 212e18f0572..bd2cc9dc79a 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/securitymanager/SetPrincipalMetadataFunction.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/securitymanager/SetPrincipalMetadataFunction.java @@ -136,13 +136,13 @@ private void setAccountMetadata(final SecurityManager securityManager, final Pri principal.setMetadataValue(schemaType, value); try { - if(principal instanceof Account) { - securityManager.updateAccount((Account)principal); - } else if(principal instanceof Group) { - securityManager.updateGroup((Group)principal); + if(principal instanceof Account account) { + securityManager.updateAccount(account); + } else if(principal instanceof Group group) { + securityManager.updateGroup(group); } } catch(final PermissionDeniedException | EXistException pde) { throw new XPathException(this, pde); } } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/xquery/functions/session/GetAttribute.java b/exist-core/src/main/java/org/exist/xquery/functions/session/GetAttribute.java index d0b322c9bb3..cdace1df5ee 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/session/GetAttribute.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/session/GetAttribute.java @@ -58,14 +58,14 @@ public GetAttribute(final XQueryContext context) { @Override public Sequence eval(final Sequence[] args, final Optional session) throws XPathException { - if (!session.isPresent()) { + if (session.isEmpty()) { return Sequence.EMPTY_SEQUENCE; } final String attributeName = args[0].getStringValue(); final Optional maybeAttributeValue = withValidSession(session.get(), s -> Optional.ofNullable(s.getAttribute(attributeName))).orElse(Optional.empty()); - if (!maybeAttributeValue.isPresent()) { + if (maybeAttributeValue.isEmpty()) { return Sequence.EMPTY_SEQUENCE; } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/session/GetAttributeNames.java b/exist-core/src/main/java/org/exist/xquery/functions/session/GetAttributeNames.java index 78c143c95ad..f3af8f7fce3 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/session/GetAttributeNames.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/session/GetAttributeNames.java @@ -57,7 +57,7 @@ public GetAttributeNames(final XQueryContext context) { public Sequence eval(final Sequence[] args, @Nonnull final SessionWrapper session) throws XPathException { final Optional> maybeAttributeNames = withValidSession(session, SessionWrapper::getAttributeNames); - if (!maybeAttributeNames.isPresent()) { + if (maybeAttributeNames.isEmpty()) { return Sequence.EMPTY_SEQUENCE; } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/session/GetCreationTime.java b/exist-core/src/main/java/org/exist/xquery/functions/session/GetCreationTime.java index ac73583174d..16ce7d503f1 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/session/GetCreationTime.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/session/GetCreationTime.java @@ -55,7 +55,7 @@ public GetCreationTime(final XQueryContext context) { @Override public Sequence eval(final Sequence[] args, final Optional session) throws XPathException { - if (!session.isPresent()) { + if (session.isEmpty()) { return XPathUtil.javaObjectToXPath(-1, context, this); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/session/GetLastAccessedTime.java b/exist-core/src/main/java/org/exist/xquery/functions/session/GetLastAccessedTime.java index 78b0465ed2a..4d146ef0a8a 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/session/GetLastAccessedTime.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/session/GetLastAccessedTime.java @@ -59,7 +59,7 @@ public GetLastAccessedTime(final XQueryContext context) { @Override public Sequence eval(final Sequence[] args, final Optional session) throws XPathException { - if (!session.isPresent()) { + if (session.isEmpty()) { return XPathUtil.javaObjectToXPath(-1, context, this); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/session/GetMaxInactiveInterval.java b/exist-core/src/main/java/org/exist/xquery/functions/session/GetMaxInactiveInterval.java index 3c7369c0aef..6d057b35bd2 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/session/GetMaxInactiveInterval.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/session/GetMaxInactiveInterval.java @@ -56,7 +56,7 @@ public GetMaxInactiveInterval(final XQueryContext context) { @Override public Sequence eval(final Sequence[] args, final Optional session) throws XPathException { - if (!session.isPresent()) { + if (session.isEmpty()) { return XPathUtil.javaObjectToXPath(-1, context, this); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/session/Invalidate.java b/exist-core/src/main/java/org/exist/xquery/functions/session/Invalidate.java index d5010b19458..13316842f79 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/session/Invalidate.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/session/Invalidate.java @@ -50,7 +50,7 @@ public Invalidate(final XQueryContext context) { @Override public Sequence eval(final Sequence[] args, final Optional session) throws XPathException { - if (!session.isPresent()) { + if (session.isEmpty()) { return Sequence.EMPTY_SEQUENCE; } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/system/FnImport.java b/exist-core/src/main/java/org/exist/xquery/functions/system/FnImport.java index a31b9bf93ec..46e82adf776 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/system/FnImport.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/system/FnImport.java @@ -37,14 +37,14 @@ import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; -import java.nio.file.Paths; - import org.exist.backup.SystemImport; import org.exist.backup.restore.listener.AbstractRestoreListener; import org.exist.backup.restore.listener.RestoreListener; import javax.annotation.Nullable; +import java.nio.file.Path; + public class FnImport extends BasicFunction { protected final static Logger logger = LogManager.getLogger(FnImport.class); @@ -126,7 +126,7 @@ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathExce try { final SystemImport restore = new SystemImport(context.getDatabase()); final RestoreListener listener = new XMLRestoreListener(builder); - restore.restore(org.exist.security.SecurityManager.DBA_USER, adminPass, adminPassAfter, Paths.get(dirOrFile), listener); + restore.restore(org.exist.security.SecurityManager.DBA_USER, adminPass, adminPassAfter, Path.of(dirOrFile), listener); } catch (final Exception e) { throw new XPathException(this, "restore failed with exception: " + e.getMessage(), e); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/system/FunctionAvailable.java b/exist-core/src/main/java/org/exist/xquery/functions/system/FunctionAvailable.java index 32d2be1fac8..2cd50d7bf2e 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/system/FunctionAvailable.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/system/FunctionAvailable.java @@ -69,10 +69,10 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro found = context.resolveFunction(functionName, arity) != null; } else { for (final org.exist.xquery.Module module : modules) { - if (module instanceof InternalModule) { - found = ((InternalModule)module).getFunctionDef(functionName, arity) != null; - } else if (module instanceof ExternalModule) { - found = ((ExternalModule)module).getFunction(functionName, arity, context) != null; + if (module instanceof InternalModule internalModule) { + found = internalModule.getFunctionDef(functionName, arity) != null; + } else if (module instanceof ExternalModule externalModule) { + found = externalModule.getFunction(functionName, arity, context) != null; } if (found) { @@ -83,4 +83,4 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro return BooleanValue.valueOf(found); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/xquery/functions/system/Restore.java b/exist-core/src/main/java/org/exist/xquery/functions/system/Restore.java index 6b125c09811..8c46057bac4 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/system/Restore.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/system/Restore.java @@ -39,7 +39,7 @@ import org.exist.xquery.value.Sequence; import org.exist.xquery.value.Type; -import java.nio.file.Paths; +import java.nio.file.Path; import java.util.Optional; import org.exist.backup.restore.listener.AbstractRestoreListener; @@ -115,7 +115,7 @@ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathExce final RestoreListener listener = new XMLRestoreListener(builder); final org.exist.backup.Restore restore = new org.exist.backup.Restore(); - restore.restore(broker, transaction, adminPassAfter, Paths.get(dirOrFile), listener, overwriteApps); + restore.restore(broker, transaction, adminPassAfter, Path.of(dirOrFile), listener, overwriteApps); transaction.commit(); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/transform/Transform.java b/exist-core/src/main/java/org/exist/xquery/functions/transform/Transform.java index 16acdac6164..2750babbdf6 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/transform/Transform.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/transform/Transform.java @@ -53,7 +53,6 @@ import java.io.IOException; import java.io.OutputStream; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import java.util.Properties; @@ -217,9 +216,9 @@ protected void raiseError(final String error, final TransformerException ex) thr if (expandXIncludes) { String xiPath = serializationProps.getProperty(EXistOutputKeys.XINCLUDE_PATH); if (xiPath != null && !xiPath.startsWith(XmldbURI.XMLDB_URI_PREFIX)) { - final Path f = Paths.get(xiPath).normalize(); + final Path f = Path.of(xiPath).normalize(); if (!f.isAbsolute()) { - xiPath = Paths.get(context.getModuleLoadPath(), xiPath).normalize().toAbsolutePath().toString(); + xiPath = Path.of(context.getModuleLoadPath(), xiPath).normalize().toAbsolutePath().toString(); } } else { xiPath = context.getModuleLoadPath(); @@ -252,7 +251,7 @@ protected void raiseError(final String error, final TransformerException ex) thr final Optional maybeResponse = Optional.ofNullable(context.getHttpContext()) .map(XQueryContext.HttpContext::getResponse); - if (!maybeResponse.isPresent()) { + if (maybeResponse.isEmpty()) { throw new XPathException(this, ErrorCodes.XPDY0002, "No response object found in the current XQuery context."); } @@ -287,9 +286,9 @@ protected void raiseError(final String error, final TransformerException ex) thr XIncludeFilter xinclude = new XIncludeFilter(serializer, receiver); String xiPath = serializationProps.getProperty(EXistOutputKeys.XINCLUDE_PATH); if (xiPath != null) { - final Path f = Paths.get(xiPath).normalize(); + final Path f = Path.of(xiPath).normalize(); if (!f.isAbsolute()) { - xiPath = Paths.get(context.getModuleLoadPath(), xiPath).normalize().toAbsolutePath().toString(); + xiPath = Path.of(context.getModuleLoadPath(), xiPath).normalize().toAbsolutePath().toString(); } } else { @@ -368,8 +367,8 @@ private TransformerHandler createHandler( } } else { String baseUri = context.getModuleLoadPath(); - if (stylesheetItem instanceof Document) { - baseUri = ((Document) stylesheetItem).getDocumentURI(); + if (stylesheetItem instanceof Document document) { + baseUri = document.getDocumentURI(); /* * This must be checked because in the event the stylesheet is @@ -394,8 +393,8 @@ private TransformerHandler createHandler( } } catch (final Exception e) { - if (e instanceof XPathException) { - throw (XPathException) e; + if (e instanceof XPathException exception) { + throw exception; } throw new XPathException(this, "Unable to set up transformer: " + e.getMessage(), e); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/util/DocumentNameOrId.java b/exist-core/src/main/java/org/exist/xquery/functions/util/DocumentNameOrId.java index bc5067d84c2..c6a66bf4cfa 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/util/DocumentNameOrId.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/util/DocumentNameOrId.java @@ -113,8 +113,8 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro case FSN_DOCUMENT_NAME: if (arg.getType() == Type.STRING || arg.getType() == Type.ANY_URI) { return Sequence.of(getFromDocument(XmldbURI.create(arg.getStringValue()), DocumentImpl::getFileURI)); - } else if (arg instanceof NodeProxy) { - return Sequence.of(getFromDocument(((NodeProxy) arg).getOwnerDocument().getURI(), DocumentImpl::getFileURI)); + } else if (arg instanceof NodeProxy proxy) { + return Sequence.of(getFromDocument(proxy.getOwnerDocument().getURI(), DocumentImpl::getFileURI)); } else { return Sequence.EMPTY_SEQUENCE; } @@ -122,8 +122,8 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro case FSN_DOCUMENT_ID: if (arg.getType() == Type.STRING || arg.getType() == Type.ANY_URI) { return Sequence.of(getFromDocument(XmldbURI.create(arg.getStringValue()), DocumentImpl::getDocId)); - } else if (arg instanceof NodeProxy) { - return Sequence.of(getFromDocument(((NodeProxy) arg).getOwnerDocument().getURI(), DocumentImpl::getDocId)); + } else if (arg instanceof NodeProxy proxy) { + return Sequence.of(getFromDocument(proxy.getOwnerDocument().getURI(), DocumentImpl::getDocId)); } else { return Sequence.EMPTY_SEQUENCE; } @@ -131,8 +131,8 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro case FSN_ABSOLUTE_RESOURCE_ID: if (arg.getType() == Type.STRING || arg.getType() == Type.ANY_URI) { return Sequence.of(getFromDocument(XmldbURI.create(arg.getStringValue()), DocumentNameOrId::getAbsoluteResourceId)); - } else if (arg instanceof NodeProxy) { - return Sequence.of(getFromDocument(((NodeProxy) arg).getOwnerDocument().getURI(), DocumentNameOrId::getAbsoluteResourceId)); + } else if (arg instanceof NodeProxy proxy) { + return Sequence.of(getFromDocument(proxy.getOwnerDocument().getURI(), DocumentNameOrId::getAbsoluteResourceId)); } else { return Sequence.EMPTY_SEQUENCE; } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/util/Eval.java b/exist-core/src/main/java/org/exist/xquery/functions/util/Eval.java index 9c665957ac9..7e15392783e 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/util/Eval.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/util/Eval.java @@ -99,17 +99,19 @@ public class Eval extends BasicFunction { "inner expression. " + "The function returns an empty sequence if a whitespace string is passed."; - private static final String contextArgumentText = "The query inherits the context described by the XML fragment in this parameter. " + - "It should have the format:\n" + - "\n" + - "\t\n" + - "\t\n" + - "\t\n" + - "\t\n" + - "\tvariable value\n" + - "\texplicitly provide default context here\n" + - "\t\n" + - ".\n"; + private static final String contextArgumentText = """ + The query inherits the context described by the XML fragment in this parameter. \ + It should have the format: + + + + + + variable value + explicitly provide default context here + + . + """; private static final FunctionParameterSequenceType FS_PARAM_EXPRESSION = param( "expression", Type.ITEM, evalArgumentText); @@ -304,11 +306,11 @@ private Sequence doEval(final XQueryContext evalContext, final Sequence contextS if (Type.subTypeOf(expr.getType(), Type.ANY_URI)) { String uri = null; - if (querySource instanceof DBSource) { - final XmldbURI documentPath = ((DBSource)querySource).getDocumentPath(); + if (querySource instanceof DBSource source1) { + final XmldbURI documentPath = source1.getDocumentPath(); uri = XmldbURI.EMBEDDED_SERVER_URI.append(documentPath).removeLastSegment().toString(); - } else if (querySource instanceof FileSource) { - uri = ((FileSource) querySource).getPath().getParent().toString(); + } else if (querySource instanceof FileSource source) { + uri = source.getPath().getParent().toString(); } if (uri != null) { @@ -595,8 +597,8 @@ private Sequence initContext(final Node root, final XQueryContext innerContext) value = loadVarFromURI(source); } else { value = (NodeValue) elem.getFirstChild(); - if (value instanceof ReferenceNode) { - value = ((ReferenceNode) value).getReference(); + if (value instanceof ReferenceNode node) { + value = node.getReference(); } } final String type = elem.getAttribute("type"); @@ -633,8 +635,8 @@ private Sequence initContext(final Node root, final XQueryContext innerContext) final Element elem = (Element) child; //TODO : iterate over the children NodeValue value = (NodeValue) elem.getFirstChild(); - if (value instanceof ReferenceNode) { - value = ((ReferenceNode) value).getReference(); + if (value instanceof ReferenceNode node) { + value = node.getReference(); } final XmldbURI[] pathes = new XmldbURI[1]; //TODO : aggregate ! diff --git a/exist-core/src/main/java/org/exist/xquery/functions/util/GetFragmentBetween.java b/exist-core/src/main/java/org/exist/xquery/functions/util/GetFragmentBetween.java index 10ad8d4169f..e7ded6e483c 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/util/GetFragmentBetween.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/util/GetFragmentBetween.java @@ -428,8 +428,8 @@ private String getNodeXPath(Node n, final boolean setRootNamespace) { private Node getParent(final Node n) { if (n == null) { return null; - } else if (n instanceof Attr) { - return ((Attr) n).getOwnerElement(); + } else if (n instanceof Attr attr) { + return attr.getOwnerElement(); } else { return n.getParentNode(); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/util/NodeXPath.java b/exist-core/src/main/java/org/exist/xquery/functions/util/NodeXPath.java index 6d8c45fc918..8e9f80a323e 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/util/NodeXPath.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/util/NodeXPath.java @@ -86,8 +86,8 @@ public Sequence eval(Sequence contextSequence, Item contextItem) throws XPathExc private Node getParent(final Node n) { if (n == null) { return null; - } else if (n instanceof Attr) { - return ((Attr) n).getOwnerElement(); + } else if (n instanceof Attr attr) { + return attr.getOwnerElement(); } else { return n.getParentNode(); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/validation/GrammarTooling.java b/exist-core/src/main/java/org/exist/xquery/functions/validation/GrammarTooling.java index dd47bccf88b..8babcff41a5 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/validation/GrammarTooling.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/validation/GrammarTooling.java @@ -71,16 +71,18 @@ public class GrammarTooling extends BasicFunction { private final Configuration config; - public final static String cacheReport="\n"+ - "\t....\n" + - "\t\t...\n" + - "\t\t...\n" + - "\t\t....\n" + - "\t\n" + - "\t...\n" + - "\t...\n" + - "\n"; + public final static String cacheReport=""" + + .... + ... + ... + .... + + ... + ... + + """; // Setup function signature public final static FunctionSignature[] signatures = { @@ -316,4 +318,4 @@ private void writeGrammar(Grammar grammar, MemTreeBuilder builder){ builder.endElement(); attribs.clear(); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/xquery/functions/validation/Jaxp.java b/exist-core/src/main/java/org/exist/xquery/functions/validation/Jaxp.java index 490933d99d7..32071202e42 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/validation/Jaxp.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/validation/Jaxp.java @@ -293,9 +293,9 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro LOG.debug("Stopped parsing document"); // Distill namespace from document - if (contenthandler instanceof ValidationContentHandler) { + if (contenthandler instanceof ValidationContentHandler handler) { report.setNamespaceUri( - ((ValidationContentHandler) contenthandler).getNamespaceUri()); + handler.getNamespaceUri()); } diff --git a/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBLoadFromPattern.java b/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBLoadFromPattern.java index 71104f727ae..825c5f01249 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBLoadFromPattern.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBLoadFromPattern.java @@ -25,7 +25,6 @@ import org.apache.logging.log4j.Logger; import java.nio.file.Path; -import java.nio.file.Paths; import org.apache.tools.ant.DirectoryScanner; import org.exist.dom.QName; @@ -110,7 +109,7 @@ public XMLDBLoadFromPattern(XQueryContext context, FunctionSignature signature) @Override protected Sequence evalWithCollection(Collection collection, Sequence[] args, Sequence contextSequence) throws XPathException { - final Path baseDir = Paths.get(args[1].getStringValue()).normalize(); + final Path baseDir = Path.of(args[1].getStringValue()).normalize(); logger.debug("Loading files from directory: {}", baseDir.toAbsolutePath().toString()); final Sequence patternsSeq = args[2]; @@ -210,4 +209,4 @@ protected Sequence evalWithCollection(Collection collection, Sequence[] args, Se return stored; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBRegisterDatabase.java b/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBRegisterDatabase.java index 31874ec4a66..90c694ce3ae 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBRegisterDatabase.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBRegisterDatabase.java @@ -74,7 +74,7 @@ public Sequence eval(Sequence[] args, Sequence contextSequence) final boolean createDatabase = args[1].effectiveBooleanValue(); try { final Class driver = Class.forName(driverName); - final Database database = (Database) driver.newInstance(); + final Database database = (Database) driver.getDeclaredConstructor().newInstance(); database.setProperty("create-database", createDatabase ? "true" : "false"); diff --git a/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBStore.java b/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBStore.java index 02e19a2eb62..fc83cddf3aa 100644 --- a/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBStore.java +++ b/exist-core/src/main/java/org/exist/xquery/functions/xmldb/XMLDBStore.java @@ -29,7 +29,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Properties; @@ -163,13 +162,13 @@ public Sequence evalWithCollection(Collection collection, Sequence[] args, Seque try { if (Type.subTypeOf(item.getType(), Type.JAVA_OBJECT)) { final Object obj = ((JavaObjectValue) item).getObject(); - if (obj instanceof java.io.File) { - resourceId = loadFromFile(collection, ((java.io.File)obj).toPath(), docName, mimeType); - } else if(obj instanceof java.nio.file.Path) { - resourceId = loadFromFile(collection, (Path)obj, docName, mimeType); - } else { - LOGGER.error("Passed java object should be either a java.nio.file.Path or java.io.File"); - throw new XPathException(this, "Passed java object should be either a java.nio.file.Path or java.io.File"); + switch (obj) { + case java.io.File file -> resourceId = loadFromFile(collection, file.toPath(), docName, mimeType); + case Path path -> resourceId = loadFromFile(collection, path, docName, mimeType); + default -> { + LOGGER.error("Passed java object should be either a java.nio.file.Path or java.io.File"); + throw new XPathException(this, "Passed java object should be either a java.nio.file.Path or java.io.File"); + } } } else if (Type.subTypeOf(item.getType(), Type.ANY_URI)) { @@ -253,7 +252,7 @@ private String loadFromURI(final Collection collection, final URI uri, final Str if (path == null) { throw new XPathException(this, "Cannot read from URI: " + uri.toASCIIString()); } - final Path file = Paths.get(path); + final Path file = Path.of(path); if (!Files.isReadable(file)) { throw new XPathException(this, "Cannot read path: " + path); } diff --git a/exist-core/src/main/java/org/exist/xquery/modules/ModuleUtils.java b/exist-core/src/main/java/org/exist/xquery/modules/ModuleUtils.java index 711328ce768..9be8ea36e1d 100644 --- a/exist-core/src/main/java/org/exist/xquery/modules/ModuleUtils.java +++ b/exist-core/src/main/java/org/exist/xquery/modules/ModuleUtils.java @@ -172,11 +172,11 @@ public static NodeValue sourceToXML(XQueryContext context, Source src) throws SA * @throws IOException in case of error reading input source */ public static NodeValue sourceToXML(XQueryContext context, Source src, final Expression expression) throws SAXException, IOException { - if(src instanceof SAXSource && ((SAXSource)src).getXMLReader() != null) { + if(src instanceof SAXSource source && source.getXMLReader() != null) { //Handles the case where a SAXSource may already have an //XMLReader allocated, for example EXPath httpclient //where it wants to tidy html using TagSoup - return inputSourceToXML(context, (SAXSource)src, expression); + return inputSourceToXML(context, source, expression); } else { final InputSource inputSource = SAXSource.sourceToInputSource(src); if(inputSource == null){ diff --git a/exist-core/src/main/java/org/exist/xquery/parser/XQueryAST.java b/exist-core/src/main/java/org/exist/xquery/parser/XQueryAST.java index f49ae7e5c24..ab6eda1019e 100644 --- a/exist-core/src/main/java/org/exist/xquery/parser/XQueryAST.java +++ b/exist-core/src/main/java/org/exist/xquery/parser/XQueryAST.java @@ -52,8 +52,8 @@ public XQueryAST(AST ast) { */ public void initialize(AST ast) { super.initialize(ast); - if(ast instanceof XQueryAST) { - copyLexInfo((XQueryAST)ast); + if(ast instanceof XQueryAST sT) { + copyLexInfo(sT); } } diff --git a/exist-core/src/main/java/org/exist/xquery/pragmas/ForceIndexUse.java b/exist-core/src/main/java/org/exist/xquery/pragmas/ForceIndexUse.java index 956b4b7ebe5..28624bd4f37 100644 --- a/exist-core/src/main/java/org/exist/xquery/pragmas/ForceIndexUse.java +++ b/exist-core/src/main/java/org/exist/xquery/pragmas/ForceIndexUse.java @@ -49,7 +49,7 @@ public void visitGeneralComparison(final GeneralComparison expr) { @Override public void visitBuiltinFunction(final Function expr) { - if (expr instanceof IndexUseReporter && ((IndexUseReporter) expr).hasUsedIndex()) { + if (expr instanceof IndexUseReporter reporter && reporter.hasUsedIndex()) { bailout = false; } for (int i = 0; i < expr.getArgumentCount(); i++) { diff --git a/exist-core/src/main/java/org/exist/xquery/pragmas/Optimize.java b/exist-core/src/main/java/org/exist/xquery/pragmas/Optimize.java index 6484c0140fd..eccc786a8df 100644 --- a/exist-core/src/main/java/org/exist/xquery/pragmas/Optimize.java +++ b/exist-core/src/main/java/org/exist/xquery/pragmas/Optimize.java @@ -223,8 +223,8 @@ public void visitLocationStep(final LocationStep locationStep) { @Override public void visitFilteredExpr(final FilteredExpression filtered) { final Expression filteredExpr = filtered.getExpression(); - if (filteredExpr instanceof VariableReference) { - contextVar = (VariableReference) filteredExpr; + if (filteredExpr instanceof VariableReference reference) { + contextVar = reference; } final List predicates = filtered.getPredicates(); @@ -253,11 +253,11 @@ public void visitPredicate(final Predicate predicate) { @Override public void visitBuiltinFunction(final Function function) { - if (function instanceof Optimizable) { + if (function instanceof Optimizable optimizable) { if (LOG.isTraceEnabled()) { LOG.trace("exist:optimize: found optimizable function: {}", function.getClass().getName()); } - addOptimizable((Optimizable) function); + addOptimizable(optimizable); } } }); diff --git a/exist-core/src/main/java/org/exist/xquery/pragmas/TimePragma.java b/exist-core/src/main/java/org/exist/xquery/pragmas/TimePragma.java index d2906039256..20bd1d34075 100644 --- a/exist-core/src/main/java/org/exist/xquery/pragmas/TimePragma.java +++ b/exist-core/src/main/java/org/exist/xquery/pragmas/TimePragma.java @@ -139,7 +139,7 @@ private static Tuple2 nsOrMs(final long nanoseconds) { */ private static String nsOrMsStr(final long nanoseconds) { final Tuple2 time = nsOrMs(nanoseconds); - return String.format("%d %s", time._1, time._2); + return "%d %s".formatted(time._1, time._2); } /** @@ -173,7 +173,7 @@ private static Tuple2 nsOrMsDbl(final double nanoseconds) { */ private static String nsOrMsStrDbl(final double nanoseconds) { final Tuple2 time = nsOrMsDbl(nanoseconds); - return String.format("%.2f %s", time._1, time._2); + return "%.2f %s".formatted(time._1, time._2); } private void logSingleMeasurement(final Expression expression) { diff --git a/exist-core/src/main/java/org/exist/xquery/update/Modification.java b/exist-core/src/main/java/org/exist/xquery/update/Modification.java index e93bf3d2be3..c41cb36019d 100644 --- a/exist-core/src/main/java/org/exist/xquery/update/Modification.java +++ b/exist-core/src/main/java/org/exist/xquery/update/Modification.java @@ -345,8 +345,8 @@ protected Txn getTransaction() { protected @Nullable Node getParent(@Nullable final Node node) { if (node == null) { return null; - } else if (node instanceof Attr) { - return ((Attr) node).getOwnerElement(); + } else if (node instanceof Attr attr) { + return attr.getOwnerElement(); } else { return node.getParentNode(); } diff --git a/exist-core/src/main/java/org/exist/xquery/util/ExpressionDumper.java b/exist-core/src/main/java/org/exist/xquery/util/ExpressionDumper.java index 3fc26ee5989..415df173fc8 100644 --- a/exist-core/src/main/java/org/exist/xquery/util/ExpressionDumper.java +++ b/exist-core/src/main/java/org/exist/xquery/util/ExpressionDumper.java @@ -61,8 +61,8 @@ public ExpressionDumper(Writer writer, int indentAmount) { } public ExpressionDumper(Writer writer, int indentAmount, int verbosity) { - if(writer instanceof PrintWriter) - {this.out = (PrintWriter)writer;} + if(writer instanceof PrintWriter printWriter) + {this.out = printWriter;} else {this.out = new PrintWriter(writer);} this.indentAmount = indentAmount; diff --git a/exist-core/src/main/java/org/exist/xquery/util/NumberFormatter.java b/exist-core/src/main/java/org/exist/xquery/util/NumberFormatter.java index 66767b2d15e..76e84c9dda6 100644 --- a/exist-core/src/main/java/org/exist/xquery/util/NumberFormatter.java +++ b/exist-core/src/main/java/org/exist/xquery/util/NumberFormatter.java @@ -141,7 +141,7 @@ public static int getMaxDigits(String picture) { } public static NumberFormatter getInstance(final String language) { - final Locale locale = new Locale(language); + final Locale locale = Locale.of(language); return switch (language) { case "de" -> new NumberFormatter_de(locale); diff --git a/exist-core/src/main/java/org/exist/xquery/value/AbstractSequence.java b/exist-core/src/main/java/org/exist/xquery/value/AbstractSequence.java index 8e83b2ba4bc..3e8bd795df9 100644 --- a/exist-core/src/main/java/org/exist/xquery/value/AbstractSequence.java +++ b/exist-core/src/main/java/org/exist/xquery/value/AbstractSequence.java @@ -238,8 +238,8 @@ public T toJavaObject(final Class target) throws XPathException { public void clearContext(final int contextId) throws XPathException { for (final SequenceIterator i = unorderedIterator(); i.hasNext(); ) { final Item next = i.nextItem(); - if (next instanceof NodeProxy) { - ((NodeProxy) next).clearContext(contextId); + if (next instanceof NodeProxy proxy) { + proxy.clearContext(contextId); } } } diff --git a/exist-core/src/main/java/org/exist/xquery/value/AnyURIValue.java b/exist-core/src/main/java/org/exist/xquery/value/AnyURIValue.java index e25227af336..5ea8b2c1edf 100644 --- a/exist-core/src/main/java/org/exist/xquery/value/AnyURIValue.java +++ b/exist-core/src/main/java/org/exist/xquery/value/AnyURIValue.java @@ -434,8 +434,8 @@ public boolean equals(Object obj) { if (this == obj) { return true; } - if (obj instanceof AnyURIValue) { - return ((AnyURIValue) obj).uri.equals(uri); + if (obj instanceof AnyURIValue value) { + return value.uri.equals(uri); } return false; } diff --git a/exist-core/src/main/java/org/exist/xquery/value/BooleanValue.java b/exist-core/src/main/java/org/exist/xquery/value/BooleanValue.java index 07db3c5b77b..fe404a38b0a 100644 --- a/exist-core/src/main/java/org/exist/xquery/value/BooleanValue.java +++ b/exist-core/src/main/java/org/exist/xquery/value/BooleanValue.java @@ -221,8 +221,8 @@ public int compareTo(Object o) { @Override public boolean equals(Object obj) { - if (obj instanceof BooleanValue) { - return value == ((BooleanValue) obj).value; + if (obj instanceof BooleanValue booleanValue) { + return value == booleanValue.value; } return false; } diff --git a/exist-core/src/main/java/org/exist/xquery/value/DayTimeDurationValue.java b/exist-core/src/main/java/org/exist/xquery/value/DayTimeDurationValue.java index cf960f108f2..66f7f688e1c 100644 --- a/exist-core/src/main/java/org/exist/xquery/value/DayTimeDurationValue.java +++ b/exist-core/src/main/java/org/exist/xquery/value/DayTimeDurationValue.java @@ -224,13 +224,13 @@ public ComputableValue plus(ComputableValue other) throws XPathException { */ public ComputableValue mult(ComputableValue other) throws XPathException { - if (other instanceof NumericValue) { + if (other instanceof NumericValue value) { //If $arg2 is NaN an error is raised [err:FOCA0005] - if (((NumericValue) other).isNaN()) { + if (value.isNaN()) { throw new XPathException(getExpression(), ErrorCodes.FOCA0005, "Operand is not a number"); } //If $arg2 is positive or negative infinity, the result overflows - if (((NumericValue) other).isInfinite()) { + if (value.isInfinite()) { throw new XPathException(getExpression(), ErrorCodes.FODT0002, "Multiplication by infinity overflow"); } } @@ -250,16 +250,16 @@ public ComputableValue div(ComputableValue other) throws XPathException { final DecimalValue b = new DecimalValue(getExpression(), ((DayTimeDurationValue) other).secondsValueSigned()); return new DecimalValue(getExpression(), a.value.divide(b.value, 20, RoundingMode.HALF_UP)); } - if (other instanceof NumericValue) { - if (((NumericValue) other).isNaN()) { + if (other instanceof NumericValue value) { + if (value.isNaN()) { throw new XPathException(getExpression(), ErrorCodes.FOCA0005, "Operand is not a number"); } //If $arg2 is positive or negative infinity, the result is a zero-length duration - if (((NumericValue) other).isInfinite()) { + if (value.isInfinite()) { return new DayTimeDurationValue(getExpression(), "PT0S"); } //If $arg2 is positive or negative zero, the result overflows and is handled as discussed in 10.1.1 Limits and Precision - if (((NumericValue) other).isZero()) { + if (value.isZero()) { throw new XPathException(getExpression(), ErrorCodes.FODT0002, "Division by zero"); } } diff --git a/exist-core/src/main/java/org/exist/xquery/value/IntegerValue.java b/exist-core/src/main/java/org/exist/xquery/value/IntegerValue.java index 56da7dd8815..7f626ce4991 100644 --- a/exist-core/src/main/java/org/exist/xquery/value/IntegerValue.java +++ b/exist-core/src/main/java/org/exist/xquery/value/IntegerValue.java @@ -407,13 +407,13 @@ public ComputableValue mult(final ComputableValue other) throws XPathException { */ @Override public ComputableValue div(final ComputableValue other) throws XPathException { - if (other instanceof IntegerValue) { - if (((IntegerValue) other).isZero()) { + if (other instanceof IntegerValue integerValue) { + if (integerValue.isZero()) { throw new XPathException(getExpression(), ErrorCodes.FOAR0001, "division by zero"); } //http://www.w3.org/TR/xpath20/#mapping : numeric; but xs:decimal if both operands are xs:integer final BigDecimal d = new BigDecimal(value); - final BigDecimal od = new BigDecimal(((IntegerValue) other).value); + final BigDecimal od = new BigDecimal(integerValue.value); final int scale = Math.max(18, Math.max(d.scale(), od.scale())); return new DecimalValue(getExpression(), d.divide(od, scale, RoundingMode.HALF_DOWN)); } else { diff --git a/exist-core/src/main/java/org/exist/xquery/value/QNameValue.java b/exist-core/src/main/java/org/exist/xquery/value/QNameValue.java index 05e94c3720d..a5b50a20221 100644 --- a/exist-core/src/main/java/org/exist/xquery/value/QNameValue.java +++ b/exist-core/src/main/java/org/exist/xquery/value/QNameValue.java @@ -248,8 +248,8 @@ public boolean equals(Object obj) { if (this == obj) { return true; } - if (obj instanceof QNameValue) { - return ((QNameValue) obj).qname.equals(qname); + if (obj instanceof QNameValue value) { + return value.qname.equals(qname); } return false; } diff --git a/exist-core/src/main/java/org/exist/xquery/value/UntypedAtomicValue.java b/exist-core/src/main/java/org/exist/xquery/value/UntypedAtomicValue.java index 60d1ab47bbd..c4b9b0bb1c9 100644 --- a/exist-core/src/main/java/org/exist/xquery/value/UntypedAtomicValue.java +++ b/exist-core/src/main/java/org/exist/xquery/value/UntypedAtomicValue.java @@ -357,8 +357,8 @@ public T toJavaObject(final Class target) throws XPathException { @Override public boolean equals(Object obj) { - if (obj instanceof UntypedAtomicValue) { - return value.equals(((UntypedAtomicValue) obj).value); + if (obj instanceof UntypedAtomicValue atomicValue) { + return value.equals(atomicValue.value); } return false; } diff --git a/exist-core/src/main/java/org/exist/xquery/value/YearMonthDurationValue.java b/exist-core/src/main/java/org/exist/xquery/value/YearMonthDurationValue.java index 4c54b223ed0..f0a4530067c 100644 --- a/exist-core/src/main/java/org/exist/xquery/value/YearMonthDurationValue.java +++ b/exist-core/src/main/java/org/exist/xquery/value/YearMonthDurationValue.java @@ -160,13 +160,13 @@ public ComputableValue plus(ComputableValue other) throws XPathException { } public ComputableValue mult(ComputableValue other) throws XPathException { - if (other instanceof NumericValue) { + if (other instanceof NumericValue value) { //If $arg2 is NaN an error is raised [err:FOCA0005] - if (((NumericValue) other).isNaN()) { + if (value.isNaN()) { throw new XPathException(getExpression(), ErrorCodes.FOCA0005, "Operand is not a number"); } //If $arg2 is positive or negative infinity, the result overflows - if (((NumericValue) other).isInfinite()) { + if (value.isInfinite()) { throw new XPathException(getExpression(), ErrorCodes.FODT0002, "Multiplication by infinity overflow"); } } @@ -191,15 +191,15 @@ public ComputableValue div(ComputableValue other) throws XPathException { if (other.getType() == Type.YEAR_MONTH_DURATION) { return new IntegerValue(getExpression(), getValue()).div(new IntegerValue(getExpression(), ((YearMonthDurationValue) other).getValue())); } - if (other instanceof NumericValue) { - if (((NumericValue) other).isNaN()) { + if (other instanceof NumericValue value) { + if (value.isNaN()) { throw new XPathException(getExpression(), ErrorCodes.FOCA0005, "Operand is not a number"); } - if (((NumericValue) other).isInfinite()) { + if (value.isInfinite()) { return new YearMonthDurationValue(getExpression(), "P0M"); } //If $arg2 is positive or negative zero, the result overflows and is handled as discussed in 10.1.1 Limits and Precision - if (((NumericValue) other).isZero()) { + if (value.isZero()) { throw new XPathException(getExpression(), ErrorCodes.FODT0002, "Division by zero overflow"); } } diff --git a/exist-core/src/main/java/org/exist/xquery/xqdoc/XQDocHelper.java b/exist-core/src/main/java/org/exist/xquery/xqdoc/XQDocHelper.java index b2f8d2edab2..afefbc398fd 100644 --- a/exist-core/src/main/java/org/exist/xquery/xqdoc/XQDocHelper.java +++ b/exist-core/src/main/java/org/exist/xquery/xqdoc/XQDocHelper.java @@ -150,10 +150,10 @@ public String toString() { final StringBuilder out = new StringBuilder(); out.append(description.toString().trim()).append("\n\n"); for (final Map.Entry entry : meta.entrySet()) { - out.append(String.format("%20s\t%s\n", entry.getKey(), entry.getValue())); + out.append("%20s\t%s\n".formatted(entry.getKey(), entry.getValue())); } for (final Map.Entry entry : parameters.entrySet()) { - out.append(String.format("%20s\t%s\n", entry.getKey(), entry.getValue())); + out.append("%20s\t%s\n".formatted(entry.getKey(), entry.getValue())); } return out.toString(); } diff --git a/exist-core/src/main/java/org/exist/xslt/EXistURIResolver.java b/exist-core/src/main/java/org/exist/xslt/EXistURIResolver.java index 67860e08f21..ced3a17dff6 100644 --- a/exist-core/src/main/java/org/exist/xslt/EXistURIResolver.java +++ b/exist-core/src/main/java/org/exist/xslt/EXistURIResolver.java @@ -186,7 +186,7 @@ private Source databaseSource(final String path) throws TransformerException { } final Source source; - if (doc instanceof BinaryDocument) { + if (doc instanceof BinaryDocument document) { /* * NOTE: this is extremely unpleasant as we let a reference to the blob file @@ -197,7 +197,7 @@ private Source databaseSource(final String path) throws TransformerException { * the situation - AR. */ try (final Txn transaction = broker.getBrokerPool().getTransactionManager().beginTransaction()) { - source = broker.withBinaryFile(transaction, (BinaryDocument) doc, p -> { + source = broker.withBinaryFile(transaction, document, p -> { final StreamSource source1 = new StreamSource(p.toFile()); source1.setSystemId(p.toUri().toString()); return source1; diff --git a/exist-core/src/main/java/org/exist/xslt/TemplatesFactory.java b/exist-core/src/main/java/org/exist/xslt/TemplatesFactory.java index e17dc91f3b0..d82568056fa 100644 --- a/exist-core/src/main/java/org/exist/xslt/TemplatesFactory.java +++ b/exist-core/src/main/java/org/exist/xslt/TemplatesFactory.java @@ -24,7 +24,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; @@ -84,11 +83,11 @@ public static Stylesheet stylesheet(String stylesheet, String baseUri, boolean u private static String uri(String stylesheet, String baseUri) { String uri = stylesheet; if (stylesheet.indexOf(':') == Constants.STRING_NOT_FOUND) { - Path f = Paths.get(stylesheet).normalize(); + Path f = Path.of(stylesheet).normalize(); if (Files.isReadable(f)) { uri = f.toUri().toASCIIString(); } else { - f = Paths.get(baseUri, stylesheet).normalize(); + f = Path.of(baseUri, stylesheet).normalize(); if (Files.isReadable(f)) { uri = f.toUri().toASCIIString(); } diff --git a/exist-core/src/main/java/org/exist/xslt/XSLTErrorsListener.java b/exist-core/src/main/java/org/exist/xslt/XSLTErrorsListener.java index 11c982531e5..3a80515fe25 100644 --- a/exist-core/src/main/java/org/exist/xslt/XSLTErrorsListener.java +++ b/exist-core/src/main/java/org/exist/xslt/XSLTErrorsListener.java @@ -35,7 +35,7 @@ public abstract class XSLTErrorsListener implements ErrorLi private static final Logger LOG = LogManager.getLogger(XSLTErrorsListener.class); private enum ErrorType { - WARNING, ERROR, FATAL; + WARNING, ERROR, FATAL } private final boolean stopOnError; diff --git a/exist-core/src/main/java/org/exist/xupdate/Modification.java b/exist-core/src/main/java/org/exist/xupdate/Modification.java index e82778ec8be..10b60da10e6 100644 --- a/exist-core/src/main/java/org/exist/xupdate/Modification.java +++ b/exist-core/src/main/java/org/exist/xupdate/Modification.java @@ -360,8 +360,8 @@ public String toString() { protected @Nullable Node getParent(@Nullable final Node node) { if (node == null) { return null; - } else if (node instanceof Attr) { - return ((Attr) node).getOwnerElement(); + } else if (node instanceof Attr attr) { + return attr.getOwnerElement(); } else { return node.getParentNode(); } diff --git a/exist-core/src/test/java/org/exist/Indexer2Test.java b/exist-core/src/test/java/org/exist/Indexer2Test.java index 9b2d87630d2..8791af29660 100644 --- a/exist-core/src/test/java/org/exist/Indexer2Test.java +++ b/exist-core/src/test/java/org/exist/Indexer2Test.java @@ -63,10 +63,12 @@ public class Indexer2Test { private final static String XML = - "\n" + - "\n" + - "Government of new Territory of Nevada—Governor Nye and the practical jokers—Mr. Clemens begins journalistic life on Virginia City Enterprise.\n" + - "\n"; + """ + + + Government of new Territory of Nevada—Governor Nye and the practical jokers—Mr. Clemens begins journalistic life on Virginia City Enterprise. + + """; private final static String XQUERY = "declare namespace tei=\"http://www.tei-c.org/ns/1.0\"; " + diff --git a/exist-core/src/test/java/org/exist/Indexer3Test.java b/exist-core/src/test/java/org/exist/Indexer3Test.java index 6db95950a11..3cf3f5921af 100644 --- a/exist-core/src/test/java/org/exist/Indexer3Test.java +++ b/exist-core/src/test/java/org/exist/Indexer3Test.java @@ -62,103 +62,124 @@ public class Indexer3Test { public static final ExistEmbeddedServer existEmbeddedServer = new ExistEmbeddedServer(true, true); private final static String XML1 = - "\n" + - "\n" + - "a b c d f\n" + - " a b c d f \n" + - " ab c d f \n" + - " b c d \n" + - "\n"; + """ + + + a b c d f + a b c d f + ab c d f + b c d + + """; private final static String XML2 = - "\n" + - "\n" + - "a b c d f\n" + - "\n"; + """ + + + a b c d f + + """; private final static String XML3 = - "\n" + - "\n" + - " a b c d f \n" + - "\n"; + """ + + + a b c d f + + """; private final static String XML4 = - "\n" + - "\n" + - " ab c d f \n" + - "\n"; + """ + + + ab c d f + + """; private final static String XML5 = - "\n" + - "\n" + - " b c d \n" + - "\n"; + """ + + + b c d + + """; private final static String XML6 = - "\n" + - "\n" + - "\n" + - "\n"; + """ + + + + + """; private final static String XML7 = - "\n" + - "\n" + - " leading and trailing \n" + - "\n"; + """ + + + leading and trailing + + """; private final static String RESULT_SUPPRESS_WS_NONE_XML1 = - "" + - "\n" + - "a b c d f\n" + - " a b c d f \n" + - " ab c d f \n" + - " b c d \n" + - "" + - ""; + """ + \ + + a b c d f + a b c d f + ab c d f + b c d + \ + """; private final static String RESULT_SUPPRESS_WS_NONE_XML2 = - "" + - "\n" + - "a b c d f\n" + - "" + - ""; + """ + \ + + a b c d f + \ + """; private final static String RESULT_SUPPRESS_WS_NONE_XML3 = - "" + - "\n" + - " a b c d f \n" + - "" + - ""; + """ + \ + + a b c d f + \ + """; private final static String RESULT_SUPPRESS_WS_NONE_XML4 = - "" + - "\n" + - " ab c d f \n" + - "" + - ""; + """ + \ + + ab c d f + \ + """; private final static String RESULT_SUPPRESS_WS_NONE_XML5 = - "" + - "\n" + - " b c d \n" + - "" + - ""; + """ + \ + + b c d + \ + """; private final static String RESULT_SUPPRESS_WS_NONE_XML6 = - "" + - "\n" + - "\n" + - "" + - ""; + """ + \ + + + \ + """; private final static String RESULT_SUPPRESS_WS_NONE_XML7 = - "" + - "\n" + - " leading and trailing \n" + - "" + - ""; + """ + \ + + leading and trailing + \ + """; private final static String RESULT_SUPPRESS_WS_LEADING_XML1 = "" + @@ -199,19 +220,21 @@ public class Indexer3Test { ""; private final static String RESULT_SUPPRESS_WS_LEADING_XML6 = - "" + - "\n" + - "\n" + - "" + - ""; + """ + \ + + + \ + """; private final static String RESULT_SUPPRESS_WS_LEADING_XML7 = - "" + - "\n" + - " leading and trailing \n" + - "" + - ""; + """ + \ + + leading and trailing + \ + """; private final static String RESULT_SUPPRESS_WS_TRAILING_XML1 = "" + @@ -252,19 +275,21 @@ public class Indexer3Test { ""; private final static String RESULT_SUPPRESS_WS_TRAILING_XML6 = - "" + - "\n" + - "\n" + - "" + - ""; + """ + \ + + + \ + """; private final static String RESULT_SUPPRESS_WS_TRAILING_XML7 = - "" + - "\n" + - " leading and trailing\n" + - "" + - ""; + """ + \ + + leading and trailing + \ + """; private final static String RESULT_SUPPRESS_WS_BOTH_XML1 = "" + @@ -291,33 +316,37 @@ public class Indexer3Test { ""; private final static String RESULT_SUPPRESS_WS_BOTH_XML4 = - "" + - "\n" + - "ab c d f\n" + - "" + - ""; + """ + \ + + ab c d f + \ + """; private final static String RESULT_SUPPRESS_WS_BOTH_XML5 = - "" + - "\n" + - " bc d \n" + - "" + - ""; + """ + \ + + bc d + \ + """; private final static String RESULT_SUPPRESS_WS_BOTH_XML6 = - "" + - "\n" + - "\n" + - "" + - ""; + """ + \ + + + \ + """; private final static String RESULT_SUPPRESS_WS_BOTH_XML7 = - "" + - "\n" + - " leading and trailing\n" + - "" + - ""; + """ + \ + + leading and trailing + \ + """; private final static String XQUERY = "let $test := doc('" + TestConstants.TEST_COLLECTION_URI.toString() + "/" + TestConstants.TEST_XML_URI.toString() + "') " + diff --git a/exist-core/src/test/java/org/exist/IndexerTest.java b/exist-core/src/test/java/org/exist/IndexerTest.java index a4fb22d7c96..6e3b53964ab 100644 --- a/exist-core/src/test/java/org/exist/IndexerTest.java +++ b/exist-core/src/test/java/org/exist/IndexerTest.java @@ -68,88 +68,95 @@ public class IndexerTest { true); private final static String XML = - "\n" + - "\n" + - " a b c\n" + - " abc\n" + - "\n"; + """ + + + a b c + abc + + """; private final static String XML_XSLT = - "\n" + - "\n" + - " \n" + - " <?\n" + - " \n" + - " \n" + - "\n" + - "\n" + - " \n" + - " ?>\n" + - " \n" + - "\n"; + """ + + + + <? + + \s + + + + ?> + + + """; private final static String RESULT_NO_PRESERVE_MIXED_WS_XML = - "\n" + - " \n" + - " a\n" + - " b\n" + - " c\n" + - " \n" + - " a \n" + - " \n" + - " b\n" + - " \n" + - " b\n"+ - " c\n" + - " \n" + - " a\n" + - " b\n" + - " c\n" + - " \n" + - " a\n" + - " \n" + - " b\n" + - " \n" + - " b\n" + - " c\n" + - ""; + """ + + + a + b + c + + a + + b + + b + c + + a + b + c + + a + + b + + b + c + """; private final static String RESULT_PRESERVE_MIXED_WS_XML = - "\n" + - " \n" + - " a b c\n" + - " \n" + - " a \n" + - " \n" + - " b\n" + - " \n" + - " b\n"+ - " c\n" + - " \n" + - " ab c\n" + - " \n" + - " a\n" + - " \n" + - " b\n" + - " \n" + - " b\n" + - " c\n" + - ""; + """ + + + a b c + + a + + b + + b + c + + ab c + + a + + b + + b + c + """; private final static String RESULT_XML_XSLT = - "\n" + - " \n" + - " \n" + - " <?\n" + - " \n" + - " \n" + - "\n" + - "\n" + - " \n" + - " ?>\n" + - " \n" + - "\n" + - ""; + """ + + + + <? + + \s + + + + ?> + + + """; private final static String XQUERY = "let $test := doc('" + TestConstants.TEST_COLLECTION_URI.toString() + "/"+ TestConstants.TEST_XML_URI.toString() + "')/* " + diff --git a/exist-core/src/test/java/org/exist/TestDataGenerator.java b/exist-core/src/test/java/org/exist/TestDataGenerator.java index 4f9fe5fc05b..beb4f5643df 100644 --- a/exist-core/src/test/java/org/exist/TestDataGenerator.java +++ b/exist-core/src/test/java/org/exist/TestDataGenerator.java @@ -65,10 +65,12 @@ public class TestDataGenerator { } private final static String IMPORT = - "import module namespace pt='http://exist-db.org/xquery/test/performance' " + - "at 'java:org.exist.performance.xquery.PerfTestModule';\n" + - "declare variable $filename external;\n" + - "declare variable $count external;\n"; + """ + import module namespace pt='http://exist-db.org/xquery/test/performance' \ + at 'java:org.exist.performance.xquery.PerfTestModule'; + declare variable $filename external; + declare variable $count external; + """; private String prefix; private int count; @@ -158,4 +160,4 @@ public void releaseAll() { FileUtils.deleteQuietly(generatedFile); } } -} \ No newline at end of file +} diff --git a/exist-core/src/test/java/org/exist/backup/RestoreAppsTest.java b/exist-core/src/test/java/org/exist/backup/RestoreAppsTest.java index 822d45d39cb..7e01a197bc7 100644 --- a/exist-core/src/test/java/org/exist/backup/RestoreAppsTest.java +++ b/exist-core/src/test/java/org/exist/backup/RestoreAppsTest.java @@ -57,19 +57,21 @@ public class RestoreAppsTest { public static final ExistEmbeddedServer existEmbeddedServer = new ExistEmbeddedServer(true, true); private static final String REPO_XML_APP = - "\n" + - "\n" + - " Backup Test App\n" + - " application\n" + - " backup-test\n" + - ""; + """ + + + Backup Test App + application + backup-test + """; private static final String REPO_XML_LIB = - "\n" + - "\n" + - " Backup Test App\n" + - " library\n" + - ""; + """ + + + Backup Test App + library + """; /** * Create an app package and generate a backup. Install a newer version @@ -269,7 +271,7 @@ private void createAndInstallApp(String version, String repoDescriptor) throws I final BrokerPool pool = existEmbeddedServer.getBrokerPool(); Optional repo = pool.getExpathRepo(); - if (!repo.isPresent()) { + if (repo.isEmpty()) { throw new EXistException("expath repository not available for test"); } XarSource xar = new XarFileSource(xarFile); diff --git a/exist-core/src/test/java/org/exist/backup/SystemExportFiltersTest.java b/exist-core/src/test/java/org/exist/backup/SystemExportFiltersTest.java index 7885d6709f2..6dd36132f93 100644 --- a/exist-core/src/test/java/org/exist/backup/SystemExportFiltersTest.java +++ b/exist-core/src/test/java/org/exist/backup/SystemExportFiltersTest.java @@ -77,13 +77,15 @@ public class SystemExportFiltersTest { private static final String XML1 = ""; private static final String XML1_BACKUP = "test"; private static final String XML2 = - "\n" + - ""; + """ + + """; private static final String XML2_PROPER = - "\n" + - ""; + """ + + """; private static final String XML3 = ""; diff --git a/exist-core/src/test/java/org/exist/backup/SystemExportImportTest.java b/exist-core/src/test/java/org/exist/backup/SystemExportImportTest.java index 066405041b7..43678384544 100644 --- a/exist-core/src/test/java/org/exist/backup/SystemExportImportTest.java +++ b/exist-core/src/test/java/org/exist/backup/SystemExportImportTest.java @@ -114,13 +114,15 @@ public static java.util.Collection data() { private static String XML1 = ""; private static String XML2 = - "\n" + - ""; + """ + + """; private static String XML2_PROPER = - "\n" + - ""; + """ + + """; private static String XML3 = ""; diff --git a/exist-core/src/test/java/org/exist/backup/XMLDBRestoreTest.java b/exist-core/src/test/java/org/exist/backup/XMLDBRestoreTest.java index bb0f4d96c5b..b4a04039bfe 100644 --- a/exist-core/src/test/java/org/exist/backup/XMLDBRestoreTest.java +++ b/exist-core/src/test/java/org/exist/backup/XMLDBRestoreTest.java @@ -362,18 +362,19 @@ private static Path createBackupWithInvalidContent() throws IOException { final Path col1 = Files.createDirectories(backupDir.resolve("db").resolve("col1")); final String contents = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + + + + + + + + """; final String doc1 = ""; final String doc2 = "invalid"; @@ -398,15 +399,16 @@ private static Path createBackupWithDifferentAdminPassword(final String backupPa final Path accountsCol = Files.createDirectories(backupDir.resolve("db").resolve("system").resolve("security").resolve("exist").resolve("accounts")); final String contents = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " " + - ""; + """ + + + + + + + + \ + """; // password for `admin` final String backupPasswordHash = Base64.encodeBase64String(ripemd160(backupPassword)); @@ -494,33 +496,39 @@ private static void createBackupWithUserInGroups(final Path backupDir, final Str final Path accountsCol = Files.createDirectories(existRealmCol.resolve("accounts")); final String dbContents = - "\n" + - " \n" + - " \n" + - ""; + """ + + + + """; final String systemContents = - "\n" + - " \n" + - " \n" + - ""; + """ + + + + """; final String securityContents = - "\n" + - " \n" + - " \n" + - ""; + """ + + + + """; final String existRealmContents = - "\n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + """; final StringBuilder groupsContents = new StringBuilder( - "\n" + - " \n"); + """ + + + """); for (final String groupName : groupNames) { groupsContents.append( diff --git a/exist-core/src/test/java/org/exist/collections/ConcurrencyTest.java b/exist-core/src/test/java/org/exist/collections/ConcurrencyTest.java index 03b12c6173d..7fa1210610c 100644 --- a/exist-core/src/test/java/org/exist/collections/ConcurrencyTest.java +++ b/exist-core/src/test/java/org/exist/collections/ConcurrencyTest.java @@ -62,14 +62,15 @@ public class ConcurrencyTest { private static final String QUERY = "collection('/db/test')/test/c"; private static final String REMOVE = - "declare namespace xmldb=\"http://exist-db.org/xquery/xmldb\";\n" + - "declare namespace util=\"http://exist-db.org/xquery/util\";" + - "declare variable $start as xs:integer external; " + - "let $dummy := util:log('DEBUG', ('Removing $start: ', $start, ' to ', $start + 9)) " + - "for $i in $start to $start + 9 " + - "let $resource := collection('/db/test')/test[xs:integer(@id) eq $i] " + - "return" + - " xmldb:remove(util:collection-name($resource), util:document-name($resource))"; + """ + declare namespace xmldb="http://exist-db.org/xquery/xmldb"; + declare namespace util="http://exist-db.org/xquery/util";\ + declare variable $start as xs:integer external; \ + let $dummy := util:log('DEBUG', ('Removing $start: ', $start, ' to ', $start + 9)) \ + for $i in $start to $start + 9 \ + let $resource := collection('/db/test')/test[xs:integer(@id) eq $i] \ + return\ + xmldb:remove(util:collection-name($resource), util:document-name($resource))"""; @Test public void runTasks() { diff --git a/exist-core/src/test/java/org/exist/collections/triggers/HistoryTriggerTest.java b/exist-core/src/test/java/org/exist/collections/triggers/HistoryTriggerTest.java index 199f8b5c5d8..5ab4649732c 100644 --- a/exist-core/src/test/java/org/exist/collections/triggers/HistoryTriggerTest.java +++ b/exist-core/src/test/java/org/exist/collections/triggers/HistoryTriggerTest.java @@ -60,11 +60,12 @@ public class HistoryTriggerTest { private static XmldbURI TEST_CONFIG_COLLECTION_URI = XmldbURI.CONFIG_COLLECTION_URI.append(TEST_COLLECTION_URI); private static String COLLECTION_CONFIG = - "\n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + """; @Before public void setup() throws EXistException, PermissionDeniedException, IOException, SAXException, LockException { @@ -192,7 +193,7 @@ private void checkHistoryOfOriginal(final BrokerPool brokerPool, final XmldbURI try(final DBBroker broker = brokerPool.get(Optional.of(brokerPool.getSecurityManager().getSystemSubject())); final Txn transaction = brokerPool.getTransactionManager().beginTransaction()) { - try(final Collection historyCollection = broker.openCollection(HistoryTrigger.DEFAULT_ROOT_PATH.append(TEST_COLLECTION_URI).append(originalDocName), Lock.LockMode.READ_LOCK);) { + try(final Collection historyCollection = broker.openCollection(HistoryTrigger.DEFAULT_ROOT_PATH.append(TEST_COLLECTION_URI).append(originalDocName), Lock.LockMode.READ_LOCK)) { assertNotNull(historyCollection); final DocumentSet documentSet = historyCollection.getDocuments(broker, new DefaultDocumentSet()); diff --git a/exist-core/src/test/java/org/exist/collections/triggers/SAXTriggerTest.java b/exist-core/src/test/java/org/exist/collections/triggers/SAXTriggerTest.java index ab2faee3bd7..85c377c994d 100644 --- a/exist-core/src/test/java/org/exist/collections/triggers/SAXTriggerTest.java +++ b/exist-core/src/test/java/org/exist/collections/triggers/SAXTriggerTest.java @@ -59,12 +59,13 @@ public class SAXTriggerTest { + ""; private final static String DOCUMENT3_CONTENT = - "\n" + - " \n" + - " 5.6\n" + - " 22\n" + - " \n" + - ""; + """ + + + 5.6 + 22 + + """; private final static String COLLECTION_CONFIG = "" diff --git a/exist-core/src/test/java/org/exist/config/ConfigurableTest.java b/exist-core/src/test/java/org/exist/config/ConfigurableTest.java index d166fa393e6..38edeeadfb5 100644 --- a/exist-core/src/test/java/org/exist/config/ConfigurableTest.java +++ b/exist-core/src/test/java/org/exist/config/ConfigurableTest.java @@ -97,7 +97,7 @@ public void simple() throws Exception { assertEquals(2, object.spices.size()); - assertEquals("black pepper", object.spices.get(0).name); + assertEquals("black pepper", object.spices.getFirst().name); assertEquals("berbere", object.spices.get(1).name); } diff --git a/exist-core/src/test/java/org/exist/config/TwoDatabasesTest.java b/exist-core/src/test/java/org/exist/config/TwoDatabasesTest.java index 11eb68a8ce6..4a08ab06c85 100644 --- a/exist-core/src/test/java/org/exist/config/TwoDatabasesTest.java +++ b/exist-core/src/test/java/org/exist/config/TwoDatabasesTest.java @@ -25,7 +25,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import org.exist.EXistException; @@ -61,7 +60,7 @@ public class TwoDatabasesTest { public static void prepare() throws URISyntaxException { final String log4j = System.getProperty("log4j.configurationFile"); if (log4j == null) { - Path lf = Paths.get("log42j.xml"); + Path lf = Path.of("log42j.xml"); if (Files.isReadable(lf)) { System.setProperty("log4j.configurationFile", lf.toUri().toASCIIString()); } @@ -71,8 +70,8 @@ public static void prepare() throws URISyntaxException { final char separator = System.getProperty("file.separator").charAt(0); final String packagePath = TwoDatabasesTest.class.getPackage().getName().replace('.', separator); - config1File = Paths.get(loader.getResource(packagePath + separator + "conf1.xml").toURI()); - config2File = Paths.get(loader.getResource(packagePath + separator + "conf2.xml").toURI()); + config1File = Path.of(loader.getResource(packagePath + separator + "conf1.xml").toURI()); + config2File = Path.of(loader.getResource(packagePath + separator + "conf2.xml").toURI()); } @Rule @@ -119,7 +118,7 @@ private void put() throws EXistException, LockException, SAXException, Permissio final BrokerPool pool2 = existEmbeddedServer2.getBrokerPool(); try (final DBBroker broker2 = pool2.get(Optional.of(user1)); final Txn transaction2 = pool2.getTransactionManager().beginTransaction()) { - try(Collection top2 = storeBin(broker2, transaction2, "2");) { + try(Collection top2 = storeBin(broker2, transaction2, "2")) { pool2.getTransactionManager().commit(transaction2); } } diff --git a/exist-core/src/test/java/org/exist/dom/memtree/DocumentImplTest.java b/exist-core/src/test/java/org/exist/dom/memtree/DocumentImplTest.java index c485b63a05c..8be4a1dc654 100644 --- a/exist-core/src/test/java/org/exist/dom/memtree/DocumentImplTest.java +++ b/exist-core/src/test/java/org/exist/dom/memtree/DocumentImplTest.java @@ -48,9 +48,10 @@ public class DocumentImplTest { private static final String DOC_WITH_NAMESPACES = - "\n" + - " some description or other\n" + - ""; + """ + + some description or other + """; @Test public void checkNamespaces_xerces() throws IOException, ParserConfigurationException, SAXException { diff --git a/exist-core/src/test/java/org/exist/dom/memtree/MemtreeInXQueryTest.java b/exist-core/src/test/java/org/exist/dom/memtree/MemtreeInXQueryTest.java index 3d823efe1f0..468efd4dd06 100644 --- a/exist-core/src/test/java/org/exist/dom/memtree/MemtreeInXQueryTest.java +++ b/exist-core/src/test/java/org/exist/dom/memtree/MemtreeInXQueryTest.java @@ -41,11 +41,12 @@ public class MemtreeInXQueryTest { @Test public void pi_attributes() throws XMLDBException { - final String xquery = "let $doc := document{\n" + - " processing-instruction{\"ok\"}{\"ok\"},\n" + - " \n" + - "}\n" + - "return count($doc//processing-instruction()/@*)"; + final String xquery = """ + let $doc := document{ + processing-instruction{"ok"}{"ok"}, + + } + return count($doc//processing-instruction()/@*)"""; final ResourceSet result = existEmbeddedServer.executeQuery(xquery); @@ -57,11 +58,12 @@ public void pi_attributes() throws XMLDBException { @Test public void pi_children() throws XMLDBException { - final String xquery = "let $doc := document{\n" + - " processing-instruction{\"ok\"}{\"ok\"},\n" + - " \n" + - "}\n" + - "return count($doc//processing-instruction()/node())"; + final String xquery = """ + let $doc := document{ + processing-instruction{"ok"}{"ok"}, + + } + return count($doc//processing-instruction()/node())"""; final ResourceSet result = existEmbeddedServer.executeQuery(xquery); @@ -73,11 +75,12 @@ public void pi_children() throws XMLDBException { @Test public void pi_descendantAttributes() throws XMLDBException { - final String xquery = "let $doc := document{\n" + - " processing-instruction{\"ok\"}{\"ok\"},\n" + - " \n" + - "}\n" + - "return count($doc//processing-instruction()//@*)"; + final String xquery = """ + let $doc := document{ + processing-instruction{"ok"}{"ok"}, + + } + return count($doc//processing-instruction()//@*)"""; final ResourceSet result = existEmbeddedServer.executeQuery(xquery); @@ -89,12 +92,13 @@ public void pi_descendantAttributes() throws XMLDBException { @Test public void attr_attributes() throws XMLDBException { - final String xquery = "let $doc := document {\n" + - " element a {\n" + - " attribute x { \"y\" }\n" + - " }\n" + - "} return\n" + - " count($doc/a/@x/@y)"; + final String xquery = """ + let $doc := document { + element a { + attribute x { "y" } + } + } return + count($doc/a/@x/@y)"""; final ResourceSet result = existEmbeddedServer.executeQuery(xquery); @@ -106,12 +110,13 @@ public void attr_attributes() throws XMLDBException { @Test public void attr_children() throws XMLDBException { - final String xquery = "let $doc := document {\n" + - " element a {\n" + - " attribute x { \"y\" }\n" + - " }\n" + - "} return\n" + - " count($doc/a/@x/node())"; + final String xquery = """ + let $doc := document { + element a { + attribute x { "y" } + } + } return + count($doc/a/@x/node())"""; final ResourceSet result = existEmbeddedServer.executeQuery(xquery); diff --git a/exist-core/src/test/java/org/exist/dom/memtree/MemtreeTest.java b/exist-core/src/test/java/org/exist/dom/memtree/MemtreeTest.java index 332a493ccd1..90d63818540 100644 --- a/exist-core/src/test/java/org/exist/dom/memtree/MemtreeTest.java +++ b/exist-core/src/test/java/org/exist/dom/memtree/MemtreeTest.java @@ -50,25 +50,26 @@ public class MemtreeTest { private final static String XML = - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " text 1\n" + - " text 2\n" + - " \n" + - " \n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - ""; + """ + + + + + + + + + + text 1 + text 2 + + + + + + + + """; @Test public void size() throws IOException, ParserConfigurationException, SAXException { diff --git a/exist-core/src/test/java/org/exist/dom/persistent/DocTypeTest.java b/exist-core/src/test/java/org/exist/dom/persistent/DocTypeTest.java index 7ad01901a93..bf66832d539 100644 --- a/exist-core/src/test/java/org/exist/dom/persistent/DocTypeTest.java +++ b/exist-core/src/test/java/org/exist/dom/persistent/DocTypeTest.java @@ -29,7 +29,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import java.util.Properties; @@ -94,7 +93,7 @@ public void docType_usingInputSource() throws EXistException, URISyntaxException try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final URL testFileUrl = getClass().getResource("test_content.xml"); - final Path testFile = Paths.get(testFileUrl.toURI()); + final Path testFile = Path.of(testFileUrl.toURI()); assertTrue(Files.isReadable(testFile)); final InputSource is = new FileInputSource(testFile); diff --git a/exist-core/src/test/java/org/exist/dom/persistent/PersistentDomTest.java b/exist-core/src/test/java/org/exist/dom/persistent/PersistentDomTest.java index 5fd9e886aed..0b1ddb7987a 100644 --- a/exist-core/src/test/java/org/exist/dom/persistent/PersistentDomTest.java +++ b/exist-core/src/test/java/org/exist/dom/persistent/PersistentDomTest.java @@ -79,15 +79,16 @@ public class PersistentDomTest { private static final XmldbURI TEST_MIXED_XML_COLLECTION = XmldbURI.create("/db/persistent-dom-mixed-test"); private static final XmldbURI MIXED_XML_NAME = XmldbURI.create("mixed.xml"); private static final String MIXED_XML = - "\n" + - "\n" + - " \n" + - " text1\n" + - " \n" + - " text2\n" + - " \n" + - "\n" + - ""; + """ + + + + text1 + + text2 + + + """; private static final XmldbURI TEST_CDATA_XML_COLLECTION = XmldbURI.create("/db/persistent-dom-cdata-test"); private static final XmldbURI CDATA_XML_NAME = XmldbURI.create("cdata.xml"); @@ -115,7 +116,7 @@ public void mixed_childNodes() throws EXistException, PermissionDeniedException, assertComment(broker, "", documentChildNodes.item(2)); } - transaction.commit();; + transaction.commit(); } } diff --git a/exist-core/src/test/java/org/exist/dom/persistent/XMLUtilTest.java b/exist-core/src/test/java/org/exist/dom/persistent/XMLUtilTest.java index 8f4993144c4..4567660b578 100644 --- a/exist-core/src/test/java/org/exist/dom/persistent/XMLUtilTest.java +++ b/exist-core/src/test/java/org/exist/dom/persistent/XMLUtilTest.java @@ -28,7 +28,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import org.junit.Test; @@ -40,7 +39,7 @@ public class XMLUtilTest { @Test public void testGetXMLDeclWithUTF8() throws IOException, URISyntaxException { final URL testFileUrl = getClass().getResource(utf8TestFileName); - final Path testFile = Paths.get(testFileUrl.toURI()); + final Path testFile = Path.of(testFileUrl.toURI()); final String expectedDecl = ""; final String decl = XMLUtil.getXMLDecl(Files.readAllBytes(testFile)); @@ -50,7 +49,7 @@ public void testGetXMLDeclWithUTF8() throws IOException, URISyntaxException { @Test public void testGetXMLDeclWithUTF16() throws IOException, URISyntaxException { final URL testFileUrl = getClass().getResource(utf16TestFileName); - final Path testFile = Paths.get(testFileUrl.toURI()); + final Path testFile = Path.of(testFileUrl.toURI()); final String expectedDecl = ""; final String decl = XMLUtil.getXMLDecl(Files.readAllBytes(testFile)); diff --git a/exist-core/src/test/java/org/exist/http/RESTServiceTest.java b/exist-core/src/test/java/org/exist/http/RESTServiceTest.java index 581b639e22d..53e1dc96bc7 100644 --- a/exist-core/src/test/java/org/exist/http/RESTServiceTest.java +++ b/exist-core/src/test/java/org/exist/http/RESTServiceTest.java @@ -116,54 +116,67 @@ public class RESTServiceTest { + "" + ""; private static final String TEST_MODULE = - "module namespace t=\"http://test.foo\";\n" + - "declare variable $t:VAR := 'World!';"; + """ + module namespace t="http://test.foo"; + declare variable $t:VAR := 'World!';\ + """; private static final String TEST_XQUERY = - "xquery version \"1.0\";\n" + - "declare option exist:serialize \"method=text media-type=text/text\";\n" + - "import module namespace request=\"http://exist-db.org/xquery/request\";\n" + - "import module namespace t=\"http://test.foo\" at \"module.xq\";\n" + - "let $param := request:get-parameter('p', ())\n" + - "return\n" + - " ($param, ' ', $t:VAR)"; + """ + xquery version "1.0"; + declare option exist:serialize "method=text media-type=text/text"; + import module namespace request="http://exist-db.org/xquery/request"; + import module namespace t="http://test.foo" at "module.xq"; + let $param := request:get-parameter('p', ()) + return + ($param, ' ', $t:VAR)"""; private static final String TEST_XQUERY_PARAMETER = - "xquery version \"1.0\";\n" + - "declare namespace request=\"http://exist-db.org/xquery/request\";\n" + - "import module namespace requestparametermod=\"http://exist-db.org/xquery/requestparametermod\" at \"requestparametermod.xqm\";\n" + - "concat(\"xql=\", request:get-parameter(\"doc\",())),\n" + - "concat(\"xqm=\", $requestparametermod:request)"; + """ + xquery version "1.0"; + declare namespace request="http://exist-db.org/xquery/request"; + import module namespace requestparametermod="http://exist-db.org/xquery/requestparametermod" at "requestparametermod.xqm"; + concat("xql=", request:get-parameter("doc",())), + concat("xqm=", $requestparametermod:request)"""; private static final String TEST_XQUERY_PARAMETER_MODULE = - "module namespace requestparametermod = \"http://exist-db.org/xquery/requestparametermod\";\n" + - "declare namespace request=\"http://exist-db.org/xquery/request\";\n" + - "declare variable $requestparametermod:request := request:get-parameter(\"doc\",());\n"; + """ + module namespace requestparametermod = "http://exist-db.org/xquery/requestparametermod"; + declare namespace request="http://exist-db.org/xquery/request"; + declare variable $requestparametermod:request := request:get-parameter("doc",()); + """; private static final String TEST_XQUERY_WITH_PATH_PARAMETER = - "xquery version \"1.0\";\n" + - "declare namespace request=\"http://exist-db.org/xquery/request\";\n" + - "declare option exist:serialize \"method=text media-type=text/text\";\n" + - "(\"pathInfo=\", request:get-path-info(), \"\n\"," + - "\"servletPath=\", request:get-servlet-path(), \"\n\")"; + """ + xquery version "1.0"; + declare namespace request="http://exist-db.org/xquery/request"; + declare option exist:serialize "method=text media-type=text/text"; + ("pathInfo=", request:get-path-info(), " + ",\ + "servletPath=", request:get-servlet-path(), " + ")"""; private static final String TEST_XQUERY_WITH_PATH_AND_CONTENT = - "xquery version \"3.0\";\n" + - "declare namespace request=\"http://exist-db.org/xquery/request\";\n" + - "declare option exist:serialize \"method=text media-type=text/text\";\n" + - "request:get-data()//data/text() || ' ' || request:get-path-info()"; + """ + xquery version "3.0"; + declare namespace request="http://exist-db.org/xquery/request"; + declare option exist:serialize "method=text media-type=text/text"; + request:get-data()//data/text() || ' ' || request:get-path-info()"""; private static final String AUTH_QUERY = - "import module namespace request=\"http://exist-db.org/xquery/request\";\n" + - "import module namespace sm=\"http://exist-db.org/xquery/securitymanager\";\n" + - "\n" + - " {sm:id()}\n" + - "
{request:get-header('Authorization')}
\n" + - "
\n"; + """ + import module namespace request="http://exist-db.org/xquery/request"; + import module namespace sm="http://exist-db.org/xquery/securitymanager"; + + {sm:id()} +
{request:get-header('Authorization')}
+
+ """; private static final String XML_WITH_DOCTYPE = - "\n" + - ""; + """ + + """; private static final XmldbURI TEST_DOCTYPE_COLLECTION_URI = XmldbURI.ROOT_COLLECTION_URI.append("rest-test-doctype"); @@ -172,23 +185,24 @@ public class RESTServiceTest { private static final XmldbURI TEST_XSLPI_COLLECTION_URI = XmldbURI.ROOT_COLLECTION_URI.append("rest-test-xslpi"); private static final String XSLT_WITH_XSLPI = - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + + + + + + + + + + + + + """; private static final XmldbURI TEST_XSLT_DOC_WITH_XSLPI_URI = XmldbURI.create("test-with-xslpi.xslt"); @@ -199,8 +213,9 @@ public class RESTServiceTest { private static final XmldbURI TEST_XML_DOC_WITH_XSLPI_URI = XmldbURI.create("test-with-xslpi.xml"); private static final String XML_WITH_XMLDECL = - "\n" + - ""; + """ + + """; private static final XmldbURI TEST_XMLDECL_COLLECTION_URI = XmldbURI.ROOT_COLLECTION_URI.append("rest-test-xmldecl"); private static final XmldbURI TEST_XML_DOC_WITH_XMLDECL_URI = XmldbURI.create("test-with-xmldecl.xml"); @@ -849,17 +864,18 @@ public void execGuestQueryWithNoAuth() throws IOException { final String response = readResponse(connect.getInputStream()); final Source expectedSource = Input.from( - "\n" + - " \n" + - " \n" + - " guest\n" + - " \n" + - " guest\n" + - " \n" + - " \n" + - " \n" + - "
\n" + - "").build(); + """ + + + + guest + + guest + + + +
+ """).build(); final Source actualSource = Input.from(response).build(); final Diff diff = DiffBuilder.compare(expectedSource) @@ -895,17 +911,18 @@ public void execQueryWithBasicAuth() throws IOException { final String response = readResponse(connect.getInputStream()); final Source expectedSource = Input.from( - "\n" + - " \n" + - " \n" + - " admin\n" + - " \n" + - " dba\n" + - " \n" + - " \n" + - " \n" + - "
Basic YWRtaW46
\n" + - "
").build(); + """ + + + + admin + + dba + + + +
Basic YWRtaW46
+
""").build(); final Source actualSource = Input.from(response).build(); final Diff diff = DiffBuilder.compare(expectedSource) @@ -941,17 +958,18 @@ public void execQueryWithBasicAuthCaseInsensitive() throws IOException { final String response = readResponse(connect.getInputStream()); final Source expectedSource = Input.from( - "\n" + - " \n" + - " \n" + - " admin\n" + - " \n" + - " dba\n" + - " \n" + - " \n" + - " \n" + - "
bAsiC YWRtaW46
\n" + - "
").build(); + """ + + + + admin + + dba + + + +
bAsiC YWRtaW46
+
""").build(); final Source actualSource = Input.from(response).build(); final Diff diff = DiffBuilder.compare(expectedSource) @@ -986,23 +1004,24 @@ public void execSetUidQueryWithNoAuth() throws IOException { final String response = readResponse(connect.getInputStream()); final Source expectedSource = Input.from( - "\n" + - " \n" + - " \n" + - " guest\n" + - " \n" + - " guest\n" + - " \n" + - " \n" + - " \n" + - " admin\n" + - " \n" + - " dba\n" + - " \n" + - " \n" + - " \n" + - "
\n" + - "").build(); + """ + + + + guest + + guest + + + + admin + + dba + + + +
+ """).build(); final Source actualSource = Input.from(response).build(); final Diff diff = DiffBuilder.compare(expectedSource) @@ -1038,17 +1057,18 @@ public void execSetUidQueryWithBasicAuth() throws IOException { final String response = readResponse(connect.getInputStream()); final Source expectedSource = Input.from( - "\n" + - " \n" + - " \n" + - " admin\n" + - " \n" + - " dba\n" + - " \n" + - " \n" + - " \n" + - "
Basic YWRtaW46
\n" + - "
").build(); + """ + + + + admin + + dba + + + +
Basic YWRtaW46
+
""").build(); final Source actualSource = Input.from(response).build(); final Diff diff = DiffBuilder.compare(expectedSource) @@ -1107,23 +1127,24 @@ public void execSetUidQueryWithBearerAuth() throws IOException { final String response = readResponse(connect.getInputStream()); final Source expectedSource = Input.from( - "\n" + - " \n" + - " \n" + - " guest\n" + - " \n" + - " guest\n" + - " \n" + - " \n" + - " \n" + - " admin\n" + - " \n" + - " dba\n" + - " \n" + - " \n" + - " \n" + - "
Bearer some-token
\n" + - "
").build(); + """ + + + + guest + + guest + + + + admin + + dba + + + +
Bearer some-token
+
""").build(); final Source actualSource = Input.from(response).build(); final Diff diff = DiffBuilder.compare(expectedSource) @@ -1223,11 +1244,12 @@ public void doPostEncodedPath() throws IOException { final String docUri = getServerUri() + GET_METHOD_ENCODED_COLLECTION_URI.getCollectionPath(); final HttpURLConnection connect = getConnection(docUri); - final String data = "\n" + - " \n" + - " //foo\n" + - " \n" + - ""; + final String data = """ + + + //foo + + """; try { connect.setRequestProperty("Authorization", "Basic " + credentials); connect.setRequestMethod("POST"); @@ -1382,10 +1404,12 @@ public void getDocWithXslPi() throws IOException { final String response = readResponse(connect.getInputStream()); - final Source expectedSource = Input.from("\n" + - "\n" + - " \n" + - "\n").build(); + final Source expectedSource = Input.from(""" + + + + + """).build(); final Source actualSource = Input.from(response).build(); final Diff diff = DiffBuilder.compare(expectedSource) diff --git a/exist-core/src/test/java/org/exist/numbering/DLNTest.java b/exist-core/src/test/java/org/exist/numbering/DLNTest.java index f09a3534471..fc660db68f3 100644 --- a/exist-core/src/test/java/org/exist/numbering/DLNTest.java +++ b/exist-core/src/test/java/org/exist/numbering/DLNTest.java @@ -103,7 +103,7 @@ public void create() { @Test public void levelIds() { - DLN dln = new DLN("1.33.56.2.98.1.27");; + DLN dln = new DLN("1.33.56.2.98.1.27"); assertEquals("1.33.56.2.98.1.27", dln.toString()); dln = new DLN("1.56.4.33.30.11.9.40.3.2"); @@ -273,4 +273,4 @@ public void insertion() { dln = (DLN) left.insertNode(right); assertEquals("1.1/0/34", dln.toString()); } -} \ No newline at end of file +} diff --git a/exist-core/src/test/java/org/exist/security/internal/BackupRestoreSecurityPrincipalsTest.java b/exist-core/src/test/java/org/exist/security/internal/BackupRestoreSecurityPrincipalsTest.java index a5e6c797204..9103b832ca5 100644 --- a/exist-core/src/test/java/org/exist/security/internal/BackupRestoreSecurityPrincipalsTest.java +++ b/exist-core/src/test/java/org/exist/security/internal/BackupRestoreSecurityPrincipalsTest.java @@ -105,10 +105,11 @@ public void restoreConflictingUsername() throws PermissionDeniedException, EXist //create new users: 'frank(id=11)' and 'jack(id=12)' createInitialUsers(FRANK_USER, JACK_USER); - final String accountQuery = "declare namespace c = 'http://exist-db.org/Configuration';\n" + - "for $account in //c:account\n" + - "return\n" + - ""; + final String accountQuery = """ + declare namespace c = 'http://exist-db.org/Configuration'; + for $account in //c:account + return + """; final XPathQueryService xqs = server.getRoot().getService(XPathQueryService.class); diff --git a/exist-core/src/test/java/org/exist/security/internal/aider/UnixStylePermissionAiderTest.java b/exist-core/src/test/java/org/exist/security/internal/aider/UnixStylePermissionAiderTest.java index 455c880a33d..edc26b3aea4 100644 --- a/exist-core/src/test/java/org/exist/security/internal/aider/UnixStylePermissionAiderTest.java +++ b/exist-core/src/test/java/org/exist/security/internal/aider/UnixStylePermissionAiderTest.java @@ -123,10 +123,10 @@ public void fromString_toString() throws SyntaxException { @Test(expected=SyntaxException.class) public void fromStringInvalidSyntax_tooShort() throws SyntaxException{ UnixStylePermissionAider.fromString("rwx"); - }; + } @Test(expected=SyntaxException.class) public void fromStringInvalidSyntax_invalidChars() throws SyntaxException{ UnixStylePermissionAider.fromString("rwurwurwu"); - }; + } } diff --git a/exist-core/src/test/java/org/exist/source/SourceFactoryTest.java b/exist-core/src/test/java/org/exist/source/SourceFactoryTest.java index 2c1761aaaaa..67a9e68a533 100644 --- a/exist-core/src/test/java/org/exist/source/SourceFactoryTest.java +++ b/exist-core/src/test/java/org/exist/source/SourceFactoryTest.java @@ -35,7 +35,7 @@ import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; -import java.nio.file.Paths; +import java.nio.file.Path; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; @@ -59,9 +59,9 @@ public void getSourceFromFile_contextAbsoluteFileUrl_locationAbsoluteUrl() throw @Test public void getSourceFromFile_contextAbsoluteFile_locationAbsoluteFile() throws IOException, PermissionDeniedException, URISyntaxException { final URL mainUrl = getClass().getResource("main.xq"); - final String contextPath = Paths.get(mainUrl.toURI()).toAbsolutePath().toString(); + final String contextPath = Path.of(mainUrl.toURI()).toAbsolutePath().toString(); final URL libraryUrl = getClass().getResource("library.xqm"); - final String location = Paths.get(libraryUrl.toURI()).toAbsolutePath().toString(); + final String location = Path.of(libraryUrl.toURI()).toAbsolutePath().toString(); final Source source = SourceFactory.getSource(null, contextPath, location, false); @@ -84,7 +84,7 @@ public void getSourceFromFile_contextAbsoluteFileUrl_locationRelative() throws I @Test public void getSourceFromFile_contextAbsoluteFile_locationRelative() throws IOException, PermissionDeniedException, URISyntaxException { final URL mainUrl = getClass().getResource("main.xq"); - final String contextPath = Paths.get(mainUrl.toURI()).toAbsolutePath().toString(); + final String contextPath = Path.of(mainUrl.toURI()).toAbsolutePath().toString(); final String location = "library.xqm"; final Source source = SourceFactory.getSource(null, contextPath, location, false); @@ -96,14 +96,14 @@ public void getSourceFromFile_contextAbsoluteFile_locationRelative() throws IOEx @Test public void getSourceFromFile_contextAbsoluteDir_locationRelative() throws IOException, PermissionDeniedException, URISyntaxException { final URL mainUrl = getClass().getResource("main.xq"); - final String contextPath = Paths.get(mainUrl.toURI()).getParent().toString(); + final String contextPath = Path.of(mainUrl.toURI()).getParent().toString(); //final String contextPath = mainParent.substring(0, mainParent.lastIndexOf('/')); final String location = "library.xqm"; final Source source = SourceFactory.getSource(null, contextPath, location, false); assertTrue(source instanceof FileSource); - assertEquals(Paths.get(getClass().getResource("library.xqm").toURI()).toString(), source.path()); + assertEquals(Path.of(getClass().getResource("library.xqm").toURI()).toString(), source.path()); } @Test diff --git a/exist-core/src/test/java/org/exist/stax/EmbeddedXMLStreamReaderTest.java b/exist-core/src/test/java/org/exist/stax/EmbeddedXMLStreamReaderTest.java index 196f76e5a82..3d88a6a3880 100644 --- a/exist-core/src/test/java/org/exist/stax/EmbeddedXMLStreamReaderTest.java +++ b/exist-core/src/test/java/org/exist/stax/EmbeddedXMLStreamReaderTest.java @@ -70,15 +70,16 @@ public class EmbeddedXMLStreamReaderTest { private static final XmldbURI TEST_MIXED_XML_COLLECTION = XmldbURI.create("/db/persistent-dom-mixed-test"); private static final XmldbURI MIXED_XML_NAME = XmldbURI.create("mixed.xml"); private static final String MIXED_XML = - "\n" + - "\n" + - " \n" + - " text1\n" + - " \n" + - " text2\n" + - " \n" + - "\n" + - ""; + """ + + + + text1 + + text2 + + + """; /** * Attempts to read all nodes in the document starting from the first node of the document. diff --git a/exist-core/src/test/java/org/exist/storage/AbstractRecoverTest.java b/exist-core/src/test/java/org/exist/storage/AbstractRecoverTest.java index 60101058237..f8c04d182eb 100644 --- a/exist-core/src/test/java/org/exist/storage/AbstractRecoverTest.java +++ b/exist-core/src/test/java/org/exist/storage/AbstractRecoverTest.java @@ -60,7 +60,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import static org.junit.Assert.*; @@ -789,7 +788,7 @@ protected void flushJournal() { } protected Path resolveTestFile(final String fileName) throws IOException { - final Path path = TestUtils.getEXistHome().orElseGet(() -> Paths.get(".")).resolve(fileName); + final Path path = TestUtils.getEXistHome().orElseGet(() -> Path.of(".")).resolve(fileName); if(!Files.exists(path)) { throw new IOException("No such test file: " + path.toAbsolutePath()); } diff --git a/exist-core/src/test/java/org/exist/storage/AbstractUpdateTest.java b/exist-core/src/test/java/org/exist/storage/AbstractUpdateTest.java index 44201bdc4e3..675ccc82d24 100644 --- a/exist-core/src/test/java/org/exist/storage/AbstractUpdateTest.java +++ b/exist-core/src/test/java/org/exist/storage/AbstractUpdateTest.java @@ -94,7 +94,7 @@ public final void update() throws EXistException, DatabaseConfigurationException private void read(final BrokerPool pool) throws EXistException, PermissionDeniedException, SAXException, XPathException { - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final Serializer serializer = broker.borrowSerializer(); try(final LockedDocument lockedDoc = broker.getXMLResource(TEST_COLLECTION_URI.append("test2/test.xml"), LockMode.READ_LOCK)) { diff --git a/exist-core/src/test/java/org/exist/storage/ConcurrentBrokerPoolTest.java b/exist-core/src/test/java/org/exist/storage/ConcurrentBrokerPoolTest.java index e3911e080e0..7b383639980 100644 --- a/exist-core/src/test/java/org/exist/storage/ConcurrentBrokerPoolTest.java +++ b/exist-core/src/test/java/org/exist/storage/ConcurrentBrokerPoolTest.java @@ -44,7 +44,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import java.util.Optional; import java.util.Properties; @@ -150,7 +149,7 @@ private static String docContent(final UUID uuid) { } private static Path getConfigFile(final Class instance) throws URISyntaxException { - return Paths.get(instance.getResource("ConcurrentBrokerPoolTest.conf.xml").toURI()); + return Path.of(instance.getResource("ConcurrentBrokerPoolTest.conf.xml").toURI()); } private static class StoreInstance implements Callable> { diff --git a/exist-core/src/test/java/org/exist/storage/ConcurrentStoreTest.java b/exist-core/src/test/java/org/exist/storage/ConcurrentStoreTest.java index 4f18d55e121..efd5360b246 100644 --- a/exist-core/src/test/java/org/exist/storage/ConcurrentStoreTest.java +++ b/exist-core/src/test/java/org/exist/storage/ConcurrentStoreTest.java @@ -102,7 +102,7 @@ private void read(final BrokerPool pool) throws EXistException, PermissionDenied protected void setupCollections(final BrokerPool pool) throws EXistException, PermissionDeniedException, IOException, TriggerException { final TransactionManager transact = pool.getTransactionManager(); try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject())); - final Txn transaction = transact.beginTransaction();) { + final Txn transaction = transact.beginTransaction()) { Collection root = broker.getOrCreateCollection(transaction, TEST_COLLECTION_URI); broker.saveCollection(transaction, root); diff --git a/exist-core/src/test/java/org/exist/storage/CopyCollectionTest.java b/exist-core/src/test/java/org/exist/storage/CopyCollectionTest.java index c405061e91e..d229882eb3e 100644 --- a/exist-core/src/test/java/org/exist/storage/CopyCollectionTest.java +++ b/exist-core/src/test/java/org/exist/storage/CopyCollectionTest.java @@ -144,7 +144,7 @@ public void copyToExistentAsOther() throws AuthenticationException, LockExceptio */ @Test public void copyPreserveToNonExistentAsSelf() throws AuthenticationException, LockException, PermissionDeniedException, EXistException, IOException, TriggerException { - final Subject user1 = existWebServer.getBrokerPool().getSecurityManager().authenticate(USER1_NAME, USER1_PWD);; + final Subject user1 = existWebServer.getBrokerPool().getSecurityManager().authenticate(USER1_NAME, USER1_PWD); copyCol(user1, PRESERVE, USER1_COL1, USER1_NEW_COL); checkAttributes(USER1_NEW_COL, USER1_NAME, USER1_NAME, USER1_COL1_MODE, equalTo(getCreated(USER1_COL1))); } diff --git a/exist-core/src/test/java/org/exist/storage/DOMFileRecoverTest.java b/exist-core/src/test/java/org/exist/storage/DOMFileRecoverTest.java index be657e327d6..aebe7b51677 100644 --- a/exist-core/src/test/java/org/exist/storage/DOMFileRecoverTest.java +++ b/exist-core/src/test/java/org/exist/storage/DOMFileRecoverTest.java @@ -147,7 +147,7 @@ public void add() throws EXistException, ReadOnlyException, TerminatedException, @Test public void get() throws EXistException, IOException, BTreeException { final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { //Recover and read the data assertNotNull(broker); diff --git a/exist-core/src/test/java/org/exist/storage/RangeIndexUpdateTest.java b/exist-core/src/test/java/org/exist/storage/RangeIndexUpdateTest.java index 09f55d88c48..e818e740dd0 100644 --- a/exist-core/src/test/java/org/exist/storage/RangeIndexUpdateTest.java +++ b/exist-core/src/test/java/org/exist/storage/RangeIndexUpdateTest.java @@ -93,7 +93,7 @@ public void updates() throws EXistException, PermissionDeniedException, XPathExc final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final TransactionManager transact = pool.getTransactionManager(); try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject())); - final Txn transaction = transact.beginTransaction();) { + final Txn transaction = transact.beginTransaction()) { checkIndex(broker, docs, ITEM_QNAME, new StringValue("Chair"), 1); checkIndex(broker, docs, ITEM_QNAME, new StringValue("Table892.25"), 1); diff --git a/exist-core/src/test/java/org/exist/storage/RecoverBinary2Test.java b/exist-core/src/test/java/org/exist/storage/RecoverBinary2Test.java index 2b7a2b86c63..d845a3ed945 100644 --- a/exist-core/src/test/java/org/exist/storage/RecoverBinary2Test.java +++ b/exist-core/src/test/java/org/exist/storage/RecoverBinary2Test.java @@ -26,7 +26,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Iterator; import java.util.List; import java.util.Optional; @@ -57,7 +56,7 @@ public class RecoverBinary2Test { private static Path getBinaryResourcesDir() { try { final URI uri = RecoverBinary2Test.class.getResource("/binary-resources/sample.bin").toURI(); - return Paths.get(uri).getParent(); + return Path.of(uri).getParent(); } catch (final URISyntaxException e) { throw new RuntimeException("Cannot resolve binary-resources path", e); } diff --git a/exist-core/src/test/java/org/exist/storage/RecoverXmlTest.java b/exist-core/src/test/java/org/exist/storage/RecoverXmlTest.java index dc27fa31881..c8d1cca05f3 100644 --- a/exist-core/src/test/java/org/exist/storage/RecoverXmlTest.java +++ b/exist-core/src/test/java/org/exist/storage/RecoverXmlTest.java @@ -135,8 +135,8 @@ protected void storeAndVerify(final DBBroker broker, final Txn transaction, fina assertNotNull(doc); final Source expected; - if (data instanceof FileInputSource) { - expected = Input.fromFile(((FileInputSource)data).getFile().toFile()).build(); + if (data instanceof FileInputSource source) { + expected = Input.fromFile(source.getFile().toFile()).build(); } else if(data instanceof StringInputSource) { try (final Reader reader = data.getCharacterStream()) { expected = Input.fromString("" + readAll(reader)).build(); @@ -168,8 +168,8 @@ protected void readAndVerify(final DBBroker broker, final DocumentImpl doc, fina final String dbFilename) throws IOException { final Source expected; - if (data instanceof FileInputSource) { - expected = Input.fromFile(((FileInputSource)data).getFile().toFile()).build(); + if (data instanceof FileInputSource source) { + expected = Input.fromFile(source.getFile().toFile()).build(); } else if(data instanceof StringInputSource) { try (final Reader reader = data.getCharacterStream()) { expected = Input.fromString("" + readAll(reader)).build(); diff --git a/exist-core/src/test/java/org/exist/storage/Recovery2Test.java b/exist-core/src/test/java/org/exist/storage/Recovery2Test.java index 56d16d0adfb..e5aa498a02d 100644 --- a/exist-core/src/test/java/org/exist/storage/Recovery2Test.java +++ b/exist-core/src/test/java/org/exist/storage/Recovery2Test.java @@ -27,7 +27,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import java.util.Optional; @@ -73,7 +72,7 @@ public class Recovery2Test { private static Path getXmlDir() { try { final URI uri = Recovery2Test.class.getResource("/recovery/saami/terms-eng.xml").toURI(); - return Paths.get(uri).getParent(); + return Path.of(uri).getParent(); } catch (final URISyntaxException e) { throw new RuntimeException("Cannot resolve recovery/saami path", e); } diff --git a/exist-core/src/test/java/org/exist/storage/ReindexRecoveryTest.java b/exist-core/src/test/java/org/exist/storage/ReindexRecoveryTest.java index 1403f02ef94..81c44c423f1 100644 --- a/exist-core/src/test/java/org/exist/storage/ReindexRecoveryTest.java +++ b/exist-core/src/test/java/org/exist/storage/ReindexRecoveryTest.java @@ -82,7 +82,7 @@ public void reindexRecoveryTest() throws EXistException, PermissionDeniedExcepti private void storeDocuments(final BrokerPool pool) throws EXistException, PermissionDeniedException, IOException, TriggerException, LockException { final TransactionManager transact = pool.getTransactionManager(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { try(final Txn transaction = transact.beginTransaction()) { diff --git a/exist-core/src/test/java/org/exist/storage/ReindexTest.java b/exist-core/src/test/java/org/exist/storage/ReindexTest.java index 43d2ac8b359..b180dc3deef 100644 --- a/exist-core/src/test/java/org/exist/storage/ReindexTest.java +++ b/exist-core/src/test/java/org/exist/storage/ReindexTest.java @@ -58,10 +58,11 @@ public class ReindexTest { private static final XmldbURI DOCUMENT_WITH_CHILD_NODES_NAME = XmldbURI.create("doc-child-nodes.xml"); private static final String DOCUMENT_WITH_CHILD_NODES_XML = - "\n" + - "\n" + - "\n" + - ""; + """ + + + + """; private static final XmldbURI ELEMENT_WITH_CHILD_NODES_COLLECTION = XmldbURI.create("/db/reindex-element-child-nodes-test"); private static final XmldbURI ELEMENT_WITH_CHILD_NODES_NAME = XmldbURI.create("elem-child-nodes.xml"); diff --git a/exist-core/src/test/java/org/exist/storage/RemoveCollectionIT.java b/exist-core/src/test/java/org/exist/storage/RemoveCollectionIT.java index 24eaced1295..716f8d0732e 100644 --- a/exist-core/src/test/java/org/exist/storage/RemoveCollectionIT.java +++ b/exist-core/src/test/java/org/exist/storage/RemoveCollectionIT.java @@ -62,27 +62,28 @@ public class RemoveCollectionIT { private ExistEmbeddedServer existEmbeddedServer = new ExistEmbeddedServer(true, true); private final static String generateXQ = - "declare function local:random-sequence($length as xs:integer, $G as map(xs:string, item())) {\n" - + " if ($length eq 0)\n" - + " then ()\n" - + " else ($G?number, local:random-sequence($length - 1, $G?next()))\n" - + "};\n" - + "let $rnd := fn:random-number-generator() return" - + "" - + " " - + " {local:random-sequence(7, $rnd)}" - + " {" - + " for $section in 1 to 8 return" - + "
" - + " {local:random-sequence(7, $rnd)}" - + " {" - + " for $para in 1 to 10 return" - + " {local:random-sequence(120, $rnd)}" - + " }" - + "
" - + " }" - + "
" - + "
"; + """ + declare function local:random-sequence($length as xs:integer, $G as map(xs:string, item())) { + if ($length eq 0) + then () + else ($G?number, local:random-sequence($length - 1, $G?next())) + }; + let $rnd := fn:random-number-generator() return\ + \ + \ + {local:random-sequence(7, $rnd)}\ + {\ + for $section in 1 to 8 return\ +
\ + {local:random-sequence(7, $rnd)}\ + {\ + for $para in 1 to 10 return\ + {local:random-sequence(120, $rnd)}\ + }\ +
\ + }\ +
\ +
"""; private final static int COUNT = 300; @@ -201,7 +202,7 @@ private Collection storeDocs(final DBBroker broker, final TransactionManager tra public void recover(final BrokerPool pool, final boolean checkResource) throws EXistException, PermissionDeniedException, DatabaseConfigurationException, IOException { LockedDocument lockedDoc = null; - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { if (checkResource) { lockedDoc = broker.getXMLResource(TestConstants.TEST_COLLECTION_URI.append("hamlet.xml"), LockMode.READ_LOCK); assertNull("Resource should have been removed", lockedDoc); diff --git a/exist-core/src/test/java/org/exist/storage/RemoveTest.java b/exist-core/src/test/java/org/exist/storage/RemoveTest.java index 19a52290618..defad6ddf9d 100644 --- a/exist-core/src/test/java/org/exist/storage/RemoveTest.java +++ b/exist-core/src/test/java/org/exist/storage/RemoveTest.java @@ -83,7 +83,7 @@ protected void doUpdate(final DBBroker broker, final TransactionManager transact final Serializer serializer = broker.borrowSerializer(); - try(final LockedDocument lockedDoc = broker.getXMLResource(TestConstants.TEST_COLLECTION_URI2.append(TestConstants.TEST_XML_URI), LockMode.READ_LOCK);) { + try(final LockedDocument lockedDoc = broker.getXMLResource(TestConstants.TEST_COLLECTION_URI2.append(TestConstants.TEST_XML_URI), LockMode.READ_LOCK)) { assertNotNull("Document '" + XmldbURI.ROOT_COLLECTION + "/test/test2/test.xml' should not be null", lockedDoc); final String data = serializer.serialize(lockedDoc.getDocument()); } finally { diff --git a/exist-core/src/test/java/org/exist/storage/ResourceTest.java b/exist-core/src/test/java/org/exist/storage/ResourceTest.java index fe3444fa1a4..966be93dd2c 100644 --- a/exist-core/src/test/java/org/exist/storage/ResourceTest.java +++ b/exist-core/src/test/java/org/exist/storage/ResourceTest.java @@ -102,7 +102,7 @@ private void read(final BrokerPool pool) throws EXistException, PermissionDenie byte[] data = null; try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject())); - final Txn transaction = transact.beginTransaction();) { + final Txn transaction = transact.beginTransaction()) { final XmldbURI docPath = TestConstants.TEST_COLLECTION_URI.append(DOCUMENT_NAME_URI); diff --git a/exist-core/src/test/java/org/exist/storage/StoreBinaryTest.java b/exist-core/src/test/java/org/exist/storage/StoreBinaryTest.java index f0161707b56..571578946d5 100644 --- a/exist-core/src/test/java/org/exist/storage/StoreBinaryTest.java +++ b/exist-core/src/test/java/org/exist/storage/StoreBinaryTest.java @@ -92,7 +92,7 @@ private BinaryDocument getBinary(final XmldbURI uri) throws EXistException, Perm BinaryDocument binaryDoc = null; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { assertNotNull(broker); final Collection root = broker.getCollection(TestConstants.TEST_COLLECTION_URI); diff --git a/exist-core/src/test/java/org/exist/storage/UpdateRecoverTest.java b/exist-core/src/test/java/org/exist/storage/UpdateRecoverTest.java index d7465283e99..d3fdda46fd9 100644 --- a/exist-core/src/test/java/org/exist/storage/UpdateRecoverTest.java +++ b/exist-core/src/test/java/org/exist/storage/UpdateRecoverTest.java @@ -285,10 +285,10 @@ private void store(final BrokerPool pool) throws EXistException, PermissionDenie } private void read(final BrokerPool pool) throws IllegalAccessException, DatabaseConfigurationException, InstantiationException, ClassNotFoundException, XMLDBException, EXistException, PermissionDeniedException, SAXException { - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final Serializer serializer = broker.borrowSerializer(); - try(final LockedDocument lockedDoc = broker.getXMLResource(TestConstants.TEST_COLLECTION_URI2.append(TestConstants.TEST_XML_URI), LockMode.READ_LOCK);) { + try(final LockedDocument lockedDoc = broker.getXMLResource(TestConstants.TEST_COLLECTION_URI2.append(TestConstants.TEST_XML_URI), LockMode.READ_LOCK)) { assertNotNull("Document '" + XmldbURI.ROOT_COLLECTION + "/test/test2/test.xml' should not be null", lockedDoc); final String data = serializer.serialize(lockedDoc.getDocument()); assertNotNull(data); diff --git a/exist-core/src/test/java/org/exist/storage/blob/BlobStoreRecoveryTest.java b/exist-core/src/test/java/org/exist/storage/blob/BlobStoreRecoveryTest.java index 0d41ef42d8f..19c0e15be90 100644 --- a/exist-core/src/test/java/org/exist/storage/blob/BlobStoreRecoveryTest.java +++ b/exist-core/src/test/java/org/exist/storage/blob/BlobStoreRecoveryTest.java @@ -154,8 +154,8 @@ public void addCommit() throws IOException, BrokerPoolServiceException, EXistExc assertNotNull(actual); assertEquals(tempBin1._2, tempBin1._2); assertArrayEquals(tempBin1._1, tempBin1._1); - if (blobDb.blobStore instanceof BlobStoreImpl) { - assertEquals(1, ((BlobStoreImpl)blobDb.blobStore).getReferenceCount(blobId).intValue()); + if (blobDb.blobStore instanceof BlobStoreImpl impl) { + assertEquals(1, impl.getReferenceCount(blobId).intValue()); } } } @@ -188,8 +188,8 @@ public void addNoCommit() throws IOException, BrokerPoolServiceException, EXistE final BlobId blobId = new BlobId(tempBin1._2.getValue()); final Tuple2 actual = getCommit(blobDb.transactionManager, blobDb.blobStore, blobId); assertNull(actual); - if (blobDb.blobStore instanceof BlobStoreImpl) { - assertNull(((BlobStoreImpl)blobDb.blobStore).getReferenceCount(blobId)); + if (blobDb.blobStore instanceof BlobStoreImpl impl) { + assertNull(impl.getReferenceCount(blobId)); } } } @@ -223,8 +223,8 @@ public void addCommit_removeCommit() throws IOException, BrokerPoolServiceExcept final BlobId blobId = new BlobId(tempBin1._2.getValue()); final Tuple2 actual = getCommit(blobDb.transactionManager, blobDb.blobStore, blobId); assertNull(actual); - if (blobDb.blobStore instanceof BlobStoreImpl) { - assertNull(((BlobStoreImpl)blobDb.blobStore).getReferenceCount(blobId)); + if (blobDb.blobStore instanceof BlobStoreImpl impl) { + assertNull(impl.getReferenceCount(blobId)); } } } @@ -260,8 +260,8 @@ public void addCommit_removeNoCommit() throws IOException, BrokerPoolServiceExce assertNotNull(actual); assertEquals(tempBin1._2, tempBin1._2); assertArrayEquals(tempBin1._1, tempBin1._1); - if (blobDb.blobStore instanceof BlobStoreImpl) { - assertEquals(1, ((BlobStoreImpl)blobDb.blobStore).getReferenceCount(blobId).intValue()); + if (blobDb.blobStore instanceof BlobStoreImpl impl) { + assertEquals(1, impl.getReferenceCount(blobId).intValue()); } } } @@ -297,8 +297,8 @@ public void addCommit_addCommit() throws IOException, BrokerPoolServiceException assertNotNull(actual); assertEquals(tempBin1._2, tempBin1._2); assertArrayEquals(tempBin1._1, tempBin1._1); - if (blobDb.blobStore instanceof BlobStoreImpl) { - assertEquals(2, ((BlobStoreImpl)blobDb.blobStore).getReferenceCount(blobId).intValue()); + if (blobDb.blobStore instanceof BlobStoreImpl impl) { + assertEquals(2, impl.getReferenceCount(blobId).intValue()); } } } @@ -334,8 +334,8 @@ public void addCommit_addNoCommit() throws IOException, BrokerPoolServiceExcepti assertNotNull(actual); assertEquals(tempBin1._2, tempBin1._2); assertArrayEquals(tempBin1._1, tempBin1._1); - if (blobDb.blobStore instanceof BlobStoreImpl) { - assertEquals(1, ((BlobStoreImpl)blobDb.blobStore).getReferenceCount(blobId).intValue()); + if (blobDb.blobStore instanceof BlobStoreImpl impl) { + assertEquals(1, impl.getReferenceCount(blobId).intValue()); } } } @@ -372,8 +372,8 @@ public void addCommit_addCommit_removeCommit() throws IOException, BrokerPoolSer assertNotNull(actual); assertEquals(tempBin1._2, tempBin1._2); assertArrayEquals(tempBin1._1, tempBin1._1); - if (blobDb.blobStore instanceof BlobStoreImpl) { - assertEquals(1, ((BlobStoreImpl)blobDb.blobStore).getReferenceCount(blobId).intValue()); + if (blobDb.blobStore instanceof BlobStoreImpl impl) { + assertEquals(1, impl.getReferenceCount(blobId).intValue()); } } } @@ -410,8 +410,8 @@ public void addCommit_addCommit_removeNoCommit() throws IOException, BrokerPoolS assertNotNull(actual); assertEquals(tempBin1._2, tempBin1._2); assertArrayEquals(tempBin1._1, tempBin1._1); - if (blobDb.blobStore instanceof BlobStoreImpl) { - assertEquals(2, ((BlobStoreImpl)blobDb.blobStore).getReferenceCount(blobId).intValue()); + if (blobDb.blobStore instanceof BlobStoreImpl impl) { + assertEquals(2, impl.getReferenceCount(blobId).intValue()); } } } diff --git a/exist-core/src/test/java/org/exist/storage/journal/JournalTest.java b/exist-core/src/test/java/org/exist/storage/journal/JournalTest.java index 0094a8e45be..767b9de352a 100644 --- a/exist-core/src/test/java/org/exist/storage/journal/JournalTest.java +++ b/exist-core/src/test/java/org/exist/storage/journal/JournalTest.java @@ -38,7 +38,6 @@ import java.nio.channels.SeekableByteChannel; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -84,80 +83,80 @@ public void getFileNameWithFileNumMinusOneRaisesException() { @Test public void journalFileNum() { - assertEquals(0, Journal.journalFileNum(Paths.get("0000000000.log"))); - assertEquals(1, Journal.journalFileNum(Paths.get("0000000001.log"))); - assertEquals(2, Journal.journalFileNum(Paths.get("0000000002.log"))); - assertEquals(10, Journal.journalFileNum(Paths.get("000000000a.log"))); - assertEquals(11, Journal.journalFileNum(Paths.get("000000000b.log"))); - assertEquals(20, Journal.journalFileNum(Paths.get("0000000014.log"))); - assertEquals(21, Journal.journalFileNum(Paths.get("0000000015.log"))); - assertEquals(30, Journal.journalFileNum(Paths.get("000000001e.log"))); - assertEquals(31, Journal.journalFileNum(Paths.get("000000001f.log"))); - - assertEquals(Short.MAX_VALUE - 1, Journal.journalFileNum(Paths.get("0000007ffe.log"))); - assertEquals(Short.MAX_VALUE, Journal.journalFileNum(Paths.get("0000007fff.log"))); + assertEquals(0, Journal.journalFileNum(Path.of("0000000000.log"))); + assertEquals(1, Journal.journalFileNum(Path.of("0000000001.log"))); + assertEquals(2, Journal.journalFileNum(Path.of("0000000002.log"))); + assertEquals(10, Journal.journalFileNum(Path.of("000000000a.log"))); + assertEquals(11, Journal.journalFileNum(Path.of("000000000b.log"))); + assertEquals(20, Journal.journalFileNum(Path.of("0000000014.log"))); + assertEquals(21, Journal.journalFileNum(Path.of("0000000015.log"))); + assertEquals(30, Journal.journalFileNum(Path.of("000000001e.log"))); + assertEquals(31, Journal.journalFileNum(Path.of("000000001f.log"))); + + assertEquals(Short.MAX_VALUE - 1, Journal.journalFileNum(Path.of("0000007ffe.log"))); + assertEquals(Short.MAX_VALUE, Journal.journalFileNum(Path.of("0000007fff.log"))); } @Test(expected = IllegalArgumentException.class) public void journalFileNumWithPathShortMinValueRaisesException() { - final String fileName = String.format("%010x", Short.MIN_VALUE) + '.' + Journal.LOG_FILE_SUFFIX; - Journal.journalFileNum(Paths.get(fileName)); + final String fileName = "%010x".formatted(Short.MIN_VALUE) + '.' + Journal.LOG_FILE_SUFFIX; + Journal.journalFileNum(Path.of(fileName)); } @Test(expected = IllegalArgumentException.class) public void journalFileNumWithPathMinusOneRaisesException() { - final String fileName = String.format("%010x", -1) + '.' + Journal.LOG_FILE_SUFFIX; - Journal.journalFileNum(Paths.get(fileName)); + final String fileName = "%010x".formatted(-1) + '.' + Journal.LOG_FILE_SUFFIX; + Journal.journalFileNum(Path.of(fileName)); } @Test public void findLastFile() { try (final Stream paths = Stream.of( - Paths.get(Journal.getFileName((short)1)), - Paths.get(Journal.getFileName((short)31)), - Paths.get(Journal.getFileName((short)11)), - Paths.get(Journal.getFileName((short)10)), - Paths.get(Journal.getFileName((short)2)), - Paths.get(Journal.getFileName(Short.MAX_VALUE)), - Paths.get(Journal.getFileName((short)20)), - Paths.get(Journal.getFileName((short)(Short.MAX_VALUE - 1))), - Paths.get(Journal.getFileName((short)21)), - Paths.get(Journal.getFileName((short)30)) + Path.of(Journal.getFileName((short)1)), + Path.of(Journal.getFileName((short)31)), + Path.of(Journal.getFileName((short)11)), + Path.of(Journal.getFileName((short)10)), + Path.of(Journal.getFileName((short)2)), + Path.of(Journal.getFileName(Short.MAX_VALUE)), + Path.of(Journal.getFileName((short)20)), + Path.of(Journal.getFileName((short)(Short.MAX_VALUE - 1))), + Path.of(Journal.getFileName((short)21)), + Path.of(Journal.getFileName((short)30)) )) { assertEquals(Short.MAX_VALUE, Journal.findLastFile(paths)); } try (final Stream paths = Stream.of( - Paths.get(Journal.getFileName((short)1)), - Paths.get(Journal.getFileName((short)31)), - Paths.get(Journal.getFileName((short)11)), - Paths.get(Journal.getFileName((short)10)), - Paths.get(Journal.getFileName((short)2)), - Paths.get(Journal.getFileName((short)20)), - Paths.get(Journal.getFileName((short)(Short.MAX_VALUE - 1))), - Paths.get(Journal.getFileName((short)21)), - Paths.get(Journal.getFileName((short)30)) + Path.of(Journal.getFileName((short)1)), + Path.of(Journal.getFileName((short)31)), + Path.of(Journal.getFileName((short)11)), + Path.of(Journal.getFileName((short)10)), + Path.of(Journal.getFileName((short)2)), + Path.of(Journal.getFileName((short)20)), + Path.of(Journal.getFileName((short)(Short.MAX_VALUE - 1))), + Path.of(Journal.getFileName((short)21)), + Path.of(Journal.getFileName((short)30)) )) { assertEquals(Short.MAX_VALUE - 1, Journal.findLastFile(paths)); } try (final Stream paths = Stream.of( - Paths.get(Journal.getFileName((short)1)), - Paths.get(Journal.getFileName((short)11)), - Paths.get(Journal.getFileName((short)2)) + Path.of(Journal.getFileName((short)1)), + Path.of(Journal.getFileName((short)11)), + Path.of(Journal.getFileName((short)2)) )) { assertEquals(11, Journal.findLastFile(paths)); } try (final Stream paths = Stream.of( - Paths.get(Journal.getFileName((short)1)) + Path.of(Journal.getFileName((short)1)) )) { assertEquals(1, Journal.findLastFile(paths)); } try (final Stream paths = Stream.of( - Paths.get(Journal.getFileName((short)111)), - Paths.get(Journal.getFileName((short)1)) + Path.of(Journal.getFileName((short)111)), + Path.of(Journal.getFileName((short)1)) )) { assertEquals(111, Journal.findLastFile(paths)); } diff --git a/exist-core/src/test/java/org/exist/storage/lock/DeadlockIT.java b/exist-core/src/test/java/org/exist/storage/lock/DeadlockIT.java index fb078a3578a..5e137135cf5 100644 --- a/exist-core/src/test/java/org/exist/storage/lock/DeadlockIT.java +++ b/exist-core/src/test/java/org/exist/storage/lock/DeadlockIT.java @@ -115,27 +115,28 @@ public static java.util.Collection data() { private static final int N_THREADS = 40; private final static String generateXQ = - "declare function local:random-sequence($length as xs:integer, $G as map(xs:string, item())) {\n" - + " if ($length eq 0)\n" - + " then ()\n" - + " else ($G?number, local:random-sequence($length - 1, $G?next()))\n" - + "};\n" - + "let $rnd := fn:random-number-generator() return" - + "" - + " " - + " {local:random-sequence(7, $rnd)}" - + " {" - + " for $section in 1 to 8 return" - + "
" - + " {local:random-sequence(7, $rnd)}" - + " {" - + " for $para in 1 to 10 return" - + " {local:random-sequence(120, $rnd)}" - + " }" - + "
" - + " }" - + "
" - + "
"; + """ + declare function local:random-sequence($length as xs:integer, $G as map(xs:string, item())) { + if ($length eq 0) + then () + else ($G?number, local:random-sequence($length - 1, $G?next())) + }; + let $rnd := fn:random-number-generator() return\ + \ + \ + {local:random-sequence(7, $rnd)}\ + {\ + for $section in 1 to 8 return\ +
\ + {local:random-sequence(7, $rnd)}\ + {\ + for $para in 1 to 10 return\ + {local:random-sequence(120, $rnd)}\ + }\ +
\ + }\ +
\ +
"""; private final Random random = new Random(); diff --git a/exist-core/src/test/java/org/exist/storage/lock/ProtectedModeTest.java b/exist-core/src/test/java/org/exist/storage/lock/ProtectedModeTest.java index 83f2fc33f74..afc597ebcad 100644 --- a/exist-core/src/test/java/org/exist/storage/lock/ProtectedModeTest.java +++ b/exist-core/src/test/java/org/exist/storage/lock/ProtectedModeTest.java @@ -49,27 +49,28 @@ public class ProtectedModeTest { private final static int DOCUMENT_COUNT = 20; private final static String generateXQ = - "declare function local:random-sequence($length as xs:integer, $G as map(xs:string, item())) {\n" - + " if ($length eq 0)\n" - + " then ()\n" - + " else ($G?number, local:random-sequence($length - 1, $G?next()))\n" - + "};\n" - + "let $rnd := fn:random-number-generator() return" - + "" - + " " - + " {local:random-sequence(7, $rnd)}" - + " {" - + " for $section in 1 to 8 return" - + "
" - + " {local:random-sequence(7, $rnd)}" - + " {" - + " for $para in 1 to 10 return" - + " {local:random-sequence(120, $rnd)}" - + " }" - + "
" - + " }" - + "
" - + "
"; + """ + declare function local:random-sequence($length as xs:integer, $G as map(xs:string, item())) { + if ($length eq 0) + then () + else ($G?number, local:random-sequence($length - 1, $G?next())) + }; + let $rnd := fn:random-number-generator() return\ + \ + \ + {local:random-sequence(7, $rnd)}\ + {\ + for $section in 1 to 8 return\ +
\ + {local:random-sequence(7, $rnd)}\ + {\ + for $para in 1 to 10 return\ + {local:random-sequence(120, $rnd)}\ + }\ +
\ + }\ +
\ +
"""; @Test public void queryCollection() throws XMLDBException { diff --git a/exist-core/src/test/java/org/exist/storage/statistics/StatisticsIndexTest.java b/exist-core/src/test/java/org/exist/storage/statistics/StatisticsIndexTest.java index 9cd694ce162..a2f26a0becd 100644 --- a/exist-core/src/test/java/org/exist/storage/statistics/StatisticsIndexTest.java +++ b/exist-core/src/test/java/org/exist/storage/statistics/StatisticsIndexTest.java @@ -24,7 +24,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import org.exist.storage.BrokerPool; import org.exist.test.ExistEmbeddedServer; @@ -43,7 +42,7 @@ public static void prepare() throws URISyntaxException { final char separator = System.getProperty("file.separator").charAt(0); final String packagePath = StatisticsIndexTest.class.getPackage().getName().replace('.', separator); - configFile = Paths.get(loader.getResource(packagePath + separator + "conf.xml").toURI()); + configFile = Path.of(loader.getResource(packagePath + separator + "conf.xml").toURI()); } @Rule @@ -51,7 +50,7 @@ public static void prepare() throws URISyntaxException { @Test public void statsFileExists() { - final Path dataDir = existEmbeddedServer.getBrokerPool().getConfiguration().getProperty(BrokerPool.PROPERTY_DATA_DIR, Paths.get(DEFAULT_DATA_DIR)); + final Path dataDir = existEmbeddedServer.getBrokerPool().getConfiguration().getProperty(BrokerPool.PROPERTY_DATA_DIR, Path.of(DEFAULT_DATA_DIR)); assertTrue(Files.exists(dataDir.resolve("stats.dbx"))); } } diff --git a/exist-core/src/test/java/org/exist/storage/structural/NativeStructuralIndexWorkerTest.java b/exist-core/src/test/java/org/exist/storage/structural/NativeStructuralIndexWorkerTest.java index b55bf73da0a..87e1cde9262 100644 --- a/exist-core/src/test/java/org/exist/storage/structural/NativeStructuralIndexWorkerTest.java +++ b/exist-core/src/test/java/org/exist/storage/structural/NativeStructuralIndexWorkerTest.java @@ -65,8 +65,8 @@ public void getDocIdRanges_multipleContiguous() { assertEquals(5, ranges.size()); - assertEquals(1, ranges.get(0).start); - assertEquals(6, ranges.get(0).end); + assertEquals(1, ranges.getFirst().start); + assertEquals(6, ranges.getFirst().end); assertEquals(88, ranges.get(1).start); assertEquals(89, ranges.get(1).end); @@ -105,8 +105,8 @@ public void getDocIdRanges_singleId_followed_by_continguousIds() { assertEquals(2, ranges.size()); - assertEquals(6574, ranges.get(0).start); - assertEquals(6574, ranges.get(0).end); + assertEquals(6574, ranges.getFirst().start); + assertEquals(6574, ranges.getFirst().end); assertEquals(11, ranges.get(1).start); assertEquals(15, ranges.get(1).end); @@ -122,8 +122,8 @@ public void getDocIdRanges_contiguousIds_followed_by_single() { assertEquals(2, ranges.size()); - assertEquals(11, ranges.get(0).start); - assertEquals(15, ranges.get(0).end); + assertEquals(11, ranges.getFirst().start); + assertEquals(15, ranges.getFirst().end); assertEquals(6574, ranges.get(1).start); assertEquals(6574, ranges.get(1).end); @@ -139,8 +139,8 @@ public void getDocIdRanges_multiple_singleIds() { assertEquals(4, ranges.size()); - assertEquals(6574, ranges.get(0).start); - assertEquals(6574, ranges.get(0).end); + assertEquals(6574, ranges.getFirst().start); + assertEquals(6574, ranges.getFirst().end); assertEquals(200, ranges.get(1).start); assertEquals(200, ranges.get(1).end); diff --git a/exist-core/src/test/java/org/exist/test/runner/InspectLineSourceTest.java b/exist-core/src/test/java/org/exist/test/runner/InspectLineSourceTest.java index 46323871f43..b2d0b8494a7 100644 --- a/exist-core/src/test/java/org/exist/test/runner/InspectLineSourceTest.java +++ b/exist-core/src/test/java/org/exist/test/runner/InspectLineSourceTest.java @@ -39,7 +39,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Collections; import static java.nio.charset.StandardCharsets.UTF_8; @@ -59,7 +58,7 @@ public class InspectLineSourceTest { @Test public void inspectFunctionReturnsLineAndSourceForUDF() throws EXistException, PermissionDeniedException, XPathException, IOException, DatabaseConfigurationException { final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - final Path path = Paths.get("src/test/resources/org/exist/test/runner/inspect-line-source-test.xqm").toAbsolutePath(); + final Path path = Path.of("src/test/resources/org/exist/test/runner/inspect-line-source-test.xqm").toAbsolutePath(); if (!Files.exists(path)) { throw new AssertionError("Test resource missing: " + path); } diff --git a/exist-core/src/test/java/org/exist/test/runner/XMLTestRunnerTest.java b/exist-core/src/test/java/org/exist/test/runner/XMLTestRunnerTest.java index 0983cf51e7d..70970ebcb79 100644 --- a/exist-core/src/test/java/org/exist/test/runner/XMLTestRunnerTest.java +++ b/exist-core/src/test/java/org/exist/test/runner/XMLTestRunnerTest.java @@ -72,7 +72,7 @@ void testGetDescription() { assertEquals("xmlts.demoTest", description.getDisplayName()); assertEquals(2, description.testCount()); final ArrayList children = description.getChildren(); - assertChild(children.get(0), "testId(xmlts.demoTest)"); + assertChild(children.getFirst(), "testId(xmlts.demoTest)"); assertChild(children.get(1), "taskName(xmlts.demoTest)"); } diff --git a/exist-core/src/test/java/org/exist/test/runner/XQueryTestRunnerTest.java b/exist-core/src/test/java/org/exist/test/runner/XQueryTestRunnerTest.java index 40686354e50..4ab90071ab3 100644 --- a/exist-core/src/test/java/org/exist/test/runner/XQueryTestRunnerTest.java +++ b/exist-core/src/test/java/org/exist/test/runner/XQueryTestRunnerTest.java @@ -28,7 +28,7 @@ import java.net.URISyntaxException; import java.net.URL; -import java.nio.file.Paths; +import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -42,7 +42,7 @@ class XQueryTestRunnerTest { @Test void testGetDescription() throws URISyntaxException, InitializationError { final URL queryUrl = getClass().getResource("single-test.xqm"); - final XQueryTestRunner runner = new XQueryTestRunner(Paths.get(queryUrl.toURI()), false); + final XQueryTestRunner runner = new XQueryTestRunner(Path.of(queryUrl.toURI()), false); final Description description = runner.getDescription(); assertNotNull(description); assertTrue(description.isSuite()); @@ -54,7 +54,7 @@ void testGetDescription() throws URISyntaxException, InitializationError { @Test void testGetDescriptionWhenNoTests() throws URISyntaxException, InitializationError { final URL queryUrl = getClass().getResource("no-tests.xqm"); - final XQueryTestRunner runner = new XQueryTestRunner(Paths.get(queryUrl.toURI()), false); + final XQueryTestRunner runner = new XQueryTestRunner(Path.of(queryUrl.toURI()), false); final Description description = runner.getDescription(); assertNotNull(description); assertFalse(description.isSuite()); diff --git a/exist-core/src/test/java/org/exist/test/runner/XSuiteDiscoveryTest.java b/exist-core/src/test/java/org/exist/test/runner/XSuiteDiscoveryTest.java index cfa8e66bb03..abb3e32f157 100644 --- a/exist-core/src/test/java/org/exist/test/runner/XSuiteDiscoveryTest.java +++ b/exist-core/src/test/java/org/exist/test/runner/XSuiteDiscoveryTest.java @@ -30,7 +30,6 @@ import org.junit.runners.model.InitializationError; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; @@ -50,7 +49,7 @@ public class XSuiteDiscoveryTest { @Test public void discoveryReturnsTestListForSingleTestFile() { final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - final Path path = Paths.get("src/test/resources/org/exist/test/runner/single-test.xqm").toAbsolutePath(); + final Path path = Path.of("src/test/resources/org/exist/test/runner/single-test.xqm").toAbsolutePath(); final XQueryTestRunner.XQueryTestInfo info = XQueryTestRunner.runDiscovery(pool, path); assertNotNull("discovery XQuery should return test info", info); assertEquals("namespace", "http://exist-db.org/xquery/single-test-module", info.namespace()); @@ -65,7 +64,7 @@ public void discoveryReturnsTestListForSingleTestFile() { */ @Test public void runnerUsesDiscoveryWhenDbIsUp() throws InitializationError { - final Path path = Paths.get("src/test/resources/org/exist/test/runner/single-test.xqm").toAbsolutePath(); + final Path path = Path.of("src/test/resources/org/exist/test/runner/single-test.xqm").toAbsolutePath(); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final XQueryTestRunner.XQueryTestInfo discoveryInfo = XQueryTestRunner.runDiscovery(pool, path); assertNotNull("discovery must succeed in this test", discoveryInfo); diff --git a/exist-core/src/test/java/org/exist/util/MimeTableTest.java b/exist-core/src/test/java/org/exist/util/MimeTableTest.java index c3176844684..a85ab2b4716 100644 --- a/exist-core/src/test/java/org/exist/util/MimeTableTest.java +++ b/exist-core/src/test/java/org/exist/util/MimeTableTest.java @@ -23,7 +23,6 @@ import java.net.URISyntaxException; import java.nio.file.Path; -import java.nio.file.Paths; import static org.junit.Assert.*; @@ -49,7 +48,7 @@ public class MimeTableTest { */ @Test public void testDistributionVersionOfMimeTypesXml() throws URISyntaxException { - final Path mimeTypes = Paths.get(getClass().getResource("mime-types.xml").toURI()); + final Path mimeTypes = Path.of(getClass().getResource("mime-types.xml").toURI()); MimeTable mimeTable = new MimeTable(mimeTypes); assertNotNull("Mime table not found", mimeTable); @@ -84,7 +83,7 @@ public void testDistributionVersionOfMimeTypesXml() throws URISyntaxException { */ @Test public void testWithDefaultResourceTypeFeature() throws URISyntaxException { - final Path mimeTypes = Paths.get(getClass().getResource("mime-types-xml-default.xml").toURI()); + final Path mimeTypes = Path.of(getClass().getResource("mime-types-xml-default.xml").toURI()); MimeTable mimeTable = new MimeTable(mimeTypes); assertNotNull("Mime table not found", mimeTable); @@ -123,7 +122,7 @@ public void testWithDefaultResourceTypeFeature() throws URISyntaxException { */ @Test public void testWithDefaultMimeTypeFeature() throws URISyntaxException { - final Path mimeTypes = Paths.get(getClass().getResource("mime-types-foo-default.xml").toURI()); + final Path mimeTypes = Path.of(getClass().getResource("mime-types-foo-default.xml").toURI()); MimeTable mimeTable = new MimeTable(mimeTypes); assertNotNull("Mime table not found", mimeTable); diff --git a/exist-core/src/test/java/org/exist/util/io/FilterInputStreamCacheMonitorTest.java b/exist-core/src/test/java/org/exist/util/io/FilterInputStreamCacheMonitorTest.java index c067d9bbf21..14a158b64e8 100644 --- a/exist-core/src/test/java/org/exist/util/io/FilterInputStreamCacheMonitorTest.java +++ b/exist-core/src/test/java/org/exist/util/io/FilterInputStreamCacheMonitorTest.java @@ -41,7 +41,6 @@ import java.net.URISyntaxException; import java.nio.file.Path; -import java.nio.file.Paths; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.*; @@ -64,7 +63,7 @@ public static void setup() throws XMLDBException, URISyntaxException { } monitor.clear(); - final Path icon = Paths.get(FilterInputStreamCacheMonitorTest.class.getResource("icon.png").toURI()); + final Path icon = Path.of(FilterInputStreamCacheMonitorTest.class.getResource("icon.png").toURI()); final Collection testCollection = existXmldbEmbeddedServer.createCollection(existXmldbEmbeddedServer.getRoot(), TEST_COLLECTION_NAME); try(final EXistResource resource = (EXistResource)testCollection.createResource("icon.png", BinaryResource.class)) { diff --git a/exist-core/src/test/java/org/exist/util/sorters/ComparatorChecker.java b/exist-core/src/test/java/org/exist/util/sorters/ComparatorChecker.java index 6f45928d7de..1db0b7ebd83 100644 --- a/exist-core/src/test/java/org/exist/util/sorters/ComparatorChecker.java +++ b/exist-core/src/test/java/org/exist/util/sorters/ComparatorChecker.java @@ -40,7 +40,7 @@ public abstract class ComparatorChecker extends SortMethodChecker { enum SortOrder { ASCENDING, DESCENDING, UNSTABLE, RANDOM - }; + } ComparatorChecker(SortingAlgorithmTester sorter) { super(sorter); diff --git a/exist-core/src/test/java/org/exist/validation/CollectionConfigSchema6000Test.java b/exist-core/src/test/java/org/exist/validation/CollectionConfigSchema6000Test.java index bc8fe91f1f1..7a8698d1f21 100644 --- a/exist-core/src/test/java/org/exist/validation/CollectionConfigSchema6000Test.java +++ b/exist-core/src/test/java/org/exist/validation/CollectionConfigSchema6000Test.java @@ -30,7 +30,6 @@ import javax.xml.validation.Validator; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import static org.junit.Assert.fail; import static org.junit.Assert.assertTrue; @@ -91,7 +90,7 @@ public void xsdAcceptsFieldWithoutType() throws Exception { } private Path resolveSchemaPath() { - final Path base = Paths.get(System.getProperty("user.dir")); + final Path base = Path.of(System.getProperty("user.dir")); Path p = base.resolve("schema").resolve("collection.xconf.xsd"); if (!Files.exists(p)) { p = base.getParent().resolve("schema").resolve("collection.xconf.xsd"); diff --git a/exist-core/src/test/java/org/exist/validation/DatabaseInsertResourcesWithValidationTest.java b/exist-core/src/test/java/org/exist/validation/DatabaseInsertResourcesWithValidationTest.java index c2d60fe7a4f..e4ff56da32c 100644 --- a/exist-core/src/test/java/org/exist/validation/DatabaseInsertResourcesWithValidationTest.java +++ b/exist-core/src/test/java/org/exist/validation/DatabaseInsertResourcesWithValidationTest.java @@ -109,13 +109,11 @@ private static void removeTestCollections() throws Exception { } /** - * Test for inserting hamlet.xml, while validating using default registered - * DTD set in system catalog. + * Verifies insertion of {@code hamlet.xml} with validation against the + * default DTD registered in the system catalog. *

- * First the string - * - * needs to be modified into - * + * Prior to validation, the inlined DOCTYPE declaration in the source must be expanded. + * This ensures the document is properly recognized and validated. */ @Test public void validDocumentSystemCatalog() throws IOException { @@ -143,12 +141,19 @@ private URL getPlayDtdUrl() { * Test for inserting hamlet.xml, while validating using default registered * DTD set in system catalog. *

- * First the string - * - * needs to be modified into - * + * First the inline DOCTYPE declaration must be expanded. + *

+ * Additionally all "TITLE" elements are renamed to "INVALIDTITLE". + * This ensures that validation fails against the DTD, since "INVALIDTITLE" + * is not a declared element. *

- * Additionally all "TITLE" elements are renamed to "INVALIDTITLE" + * The test verifies that: + *

    + *
  • The DOCTYPE declaration is correctly restored before parsing.
  • + *
  • DTD validation is triggered using the system catalog.
  • + *
  • The invalid element names cause a validation error.
  • + *
  • The insert operation is rejected due to the validation failure.
  • + *
*/ @Test public void invalidDocumentSystemCatalog() throws IOException { diff --git a/exist-core/src/test/java/org/exist/w3c/tests/TestCase.java b/exist-core/src/test/java/org/exist/w3c/tests/TestCase.java index 4c459a84a33..49116c8eab0 100644 --- a/exist-core/src/test/java/org/exist/w3c/tests/TestCase.java +++ b/exist-core/src/test/java/org/exist/w3c/tests/TestCase.java @@ -30,7 +30,6 @@ import java.lang.reflect.Field; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import java.util.Properties; @@ -138,7 +137,7 @@ public boolean compareResult(String testCase, String folder, Element outputFile, if (outputFile == null) Assert.fail("no expected result information"); - Path expectedResult = Paths.get(testLocation+folder, outputFile.getTextContent()); + Path expectedResult = Path.of(testLocation+folder, outputFile.getTextContent()); if (!Files.isReadable(expectedResult)) { Assert.fail("can't read expected result"); } @@ -308,14 +307,14 @@ public Resource getResource(Object r) throws XMLDBException { final BrokerPool pool = existEmbeddedServer.getBrokerPool(); if (r instanceof NodeProxy p) { res = new LocalXMLResource(user, pool, collection, p); - } else if (r instanceof Node) { + } else if (r instanceof Node node) { res = new LocalXMLResource(user, pool, collection, XmldbURI.EMPTY_URI); - res.setContentAsDOM((Node)r); + res.setContentAsDOM(node); } else if (r instanceof AtomicValue) { res = new LocalXMLResource(user, pool, collection, XmldbURI.EMPTY_URI); res.setContent(r); - } else if (r instanceof LocalXMLResource) - res = (LocalXMLResource) r; + } else if (r instanceof LocalXMLResource resource) + res = resource; else throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "unknown object "+r.getClass()); @@ -360,7 +359,7 @@ public NodeImpl loadVarFromURI(XQueryContext context, String uri) throws IOExcep //workaround BOM if ("Content is not allowed in prolog.".equals(e.getMessage())) { try { - String xml = readFileAsString(Paths.get(uri)); + String xml = readFileAsString(Path.of(uri)); xml = xml.trim().replaceFirst("^([\\W]+)<","<"); InputSource src = new InputSource(new StringReader(xml)); xr.parse(src); diff --git a/exist-core/src/test/java/org/exist/xmldb/BinaryResourceUpdateIT.java b/exist-core/src/test/java/org/exist/xmldb/BinaryResourceUpdateIT.java index f6fbb3e1178..7a5194f44db 100644 --- a/exist-core/src/test/java/org/exist/xmldb/BinaryResourceUpdateIT.java +++ b/exist-core/src/test/java/org/exist/xmldb/BinaryResourceUpdateIT.java @@ -35,7 +35,7 @@ import java.net.URISyntaxException; import java.net.URL; -import java.nio.file.Paths; +import java.nio.file.Path; import static org.junit.Assert.assertNotNull; @@ -80,14 +80,14 @@ public void tearDown() throws XMLDBException { public void updateBinarySameName() throws XMLDBException, URISyntaxException { for (int i = 0; i < REPEAT; i++) { BinaryResource binaryResource = testCollection.createResource("test.xml", BinaryResource.class); - binaryResource.setContent(Paths.get(binFile.toURI())); + binaryResource.setContent(Path.of(binFile.toURI())); testCollection.storeResource(binaryResource); Resource resource = testCollection.getResource("test.xml"); assertNotNull(resource); XMLResource xmlResource = testCollection.createResource("test.xml", XMLResource.class); - xmlResource.setContent(Paths.get(xmlFile.toURI())); + xmlResource.setContent(Path.of(xmlFile.toURI())); testCollection.storeResource(xmlResource); resource = testCollection.getResource("test.xml"); diff --git a/exist-core/src/test/java/org/exist/xmldb/BinaryResourceUpdateTest.java b/exist-core/src/test/java/org/exist/xmldb/BinaryResourceUpdateTest.java index 2501a53ae2a..9263bc47254 100644 --- a/exist-core/src/test/java/org/exist/xmldb/BinaryResourceUpdateTest.java +++ b/exist-core/src/test/java/org/exist/xmldb/BinaryResourceUpdateTest.java @@ -34,7 +34,7 @@ import java.net.URISyntaxException; import java.net.URL; -import java.nio.file.Paths; +import java.nio.file.Path; import org.junit.Test; import static org.junit.Assert.assertNotNull; @@ -57,14 +57,14 @@ public class BinaryResourceUpdateTest { public void updateBinary() throws XMLDBException, URISyntaxException { for (int i = 0; i < REPEAT; i++) { BinaryResource binaryResource = testCollection.createResource("test1.xml", BinaryResource.class); - binaryResource.setContent(Paths.get(binFile.toURI())); + binaryResource.setContent(Path.of(binFile.toURI())); testCollection.storeResource(binaryResource); Resource resource = testCollection.getResource("test1.xml"); assertNotNull(resource); XMLResource xmlResource = testCollection.createResource("test2.xml", XMLResource.class); - xmlResource.setContent(Paths.get(xmlFile.toURI())); + xmlResource.setContent(Path.of(xmlFile.toURI())); testCollection.storeResource(xmlResource); resource = testCollection.getResource("test2.xml"); @@ -92,4 +92,4 @@ public void tearDown() throws XMLDBException { binFile = null; xmlFile = null; } -} \ No newline at end of file +} diff --git a/exist-core/src/test/java/org/exist/xmldb/CollectionConfigurationTest.java b/exist-core/src/test/java/org/exist/xmldb/CollectionConfigurationTest.java index 516f184ff93..3b41de209bc 100644 --- a/exist-core/src/test/java/org/exist/xmldb/CollectionConfigurationTest.java +++ b/exist-core/src/test/java/org/exist/xmldb/CollectionConfigurationTest.java @@ -146,15 +146,16 @@ public class CollectionConfigurationTest { + " " + ""; - private final static String INVALID_CONFIG1 = "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + ""; + private final static String INVALID_CONFIG1 = """ + + + + + + + + + """; @Before public void setUp() throws Exception { diff --git a/exist-core/src/test/java/org/exist/xmldb/CreateCollectionsTest.java b/exist-core/src/test/java/org/exist/xmldb/CreateCollectionsTest.java index a4224d73a64..a7f2d9c1f26 100644 --- a/exist-core/src/test/java/org/exist/xmldb/CreateCollectionsTest.java +++ b/exist-core/src/test/java/org/exist/xmldb/CreateCollectionsTest.java @@ -26,7 +26,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -178,7 +177,7 @@ public void storeBinaryResource() throws XMLDBException, IOException, URISyntaxE UserManagementService ums = testCollection.getService(UserManagementService.class); ums.chmod("rwxr-xr-x"); - final Path fLogo = Paths.get(getClass().getClassLoader().getResource("org/exist/xquery/value/logo.jpg").toURI()); + final Path fLogo = Path.of(getClass().getClassLoader().getResource("org/exist/xquery/value/logo.jpg").toURI()); byte[] data = storeBinaryResourceFromFile(fLogo, testCollection); Object content = testCollection.getResource("logo.jpg").getContent(); byte[] dataStored = (byte[])content; @@ -229,4 +228,4 @@ public void testMultipleCreates() throws XMLDBException { c1 = testCol.getChildCollection("dummy1"); assertNull(c1); } -} \ No newline at end of file +} diff --git a/exist-core/src/test/java/org/exist/xmldb/DOMJUnitTest.java b/exist-core/src/test/java/org/exist/xmldb/DOMJUnitTest.java index 00c754c0070..710cf3ecfde 100644 --- a/exist-core/src/test/java/org/exist/xmldb/DOMJUnitTest.java +++ b/exist-core/src/test/java/org/exist/xmldb/DOMJUnitTest.java @@ -73,17 +73,17 @@ public void domUpdate() throws XMLDBException { Element root=null; NodeList nl=null; Node n = index.getContentAsDOM(); - if (n instanceof Document) { - doc=(Document)n; - root=doc.getDocumentElement(); - } - else if (n instanceof Element) { - doc = n.getOwnerDocument(); - root=(Element)n; - } - else { - fail("RemoteXMLResource unable to return a Document either an Element"); - } + switch (n) { + case Document document -> { + doc = document; + root = doc.getDocumentElement(); + } + case Element element -> { + doc = n.getOwnerDocument(); + root = element; + } + default -> fail("RemoteXMLResource unable to return a Document either an Element"); + } nl = doc.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { @@ -102,13 +102,13 @@ else if (n instanceof Element) { index = (XMLResource) rootColl.getResource(name); content = (String) index.getContent(); n = index.getContentAsDOM(); - if (n instanceof Document) { - doc=(Document)n; + if (n instanceof Document document) { + doc=document; root=doc.getDocumentElement(); } - else if (n instanceof Element) { + else if (n instanceof Element element) { doc = n.getOwnerDocument(); - root=(Element)n; + root=element; } nl = root.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { diff --git a/exist-core/src/test/java/org/exist/xmldb/DeclareVariableTest.java b/exist-core/src/test/java/org/exist/xmldb/DeclareVariableTest.java index b0e25b0eb7e..d700b98aa67 100644 --- a/exist-core/src/test/java/org/exist/xmldb/DeclareVariableTest.java +++ b/exist-core/src/test/java/org/exist/xmldb/DeclareVariableTest.java @@ -103,9 +103,10 @@ private Resource executeQueryWithExternalVariable(final Object value) throws XML xqueryService.declareVariable("x", value); final String query = - "xquery version \"3.1\";\n" + - "declare variable $x external;\n" + - "$x"; + """ + xquery version "3.1"; + declare variable $x external; + $x"""; final CompiledExpression compiled = xqueryService.compile(query); diff --git a/exist-core/src/test/java/org/exist/xmldb/IndexingTest.java b/exist-core/src/test/java/org/exist/xmldb/IndexingTest.java index baee51ee86c..bf6e258aa5f 100644 --- a/exist-core/src/test/java/org/exist/xmldb/IndexingTest.java +++ b/exist-core/src/test/java/org/exist/xmldb/IndexingTest.java @@ -143,10 +143,10 @@ private void irregularilyStructured(boolean getContentAsDOM) } Element documentElement = null; - if (n instanceof Element) { - documentElement = (Element) n; - } else if (n instanceof Document) { - documentElement = ((Document) n).getDocumentElement(); + if (n instanceof Element element) { + documentElement = element; + } else if (n instanceof Document document) { + documentElement = document.getDocumentElement(); } assertions(documentElement); diff --git a/exist-core/src/test/java/org/exist/xmldb/ResourceTest.java b/exist-core/src/test/java/org/exist/xmldb/ResourceTest.java index fdd72441ef4..6c27312aecf 100644 --- a/exist-core/src/test/java/org/exist/xmldb/ResourceTest.java +++ b/exist-core/src/test/java/org/exist/xmldb/ResourceTest.java @@ -162,10 +162,10 @@ public void readDOM() throws XMLDBException { assertNotNull(doc); Node n = doc.getContentAsDOM(); Element elem=null; - if (n instanceof Element) { - elem = (Element)n; - } else if (n instanceof Document) { - elem = ((Document)n).getDocumentElement(); + if (n instanceof Element element) { + elem = element; + } else if (n instanceof Document document) { + elem = document.getDocumentElement(); } assertNotNull(elem); assertEquals(elem.getNodeName(), "PLAY"); diff --git a/exist-core/src/test/java/org/exist/xmldb/SerializationTest.java b/exist-core/src/test/java/org/exist/xmldb/SerializationTest.java index b4de05229db..72d60528a6b 100644 --- a/exist-core/src/test/java/org/exist/xmldb/SerializationTest.java +++ b/exist-core/src/test/java/org/exist/xmldb/SerializationTest.java @@ -93,14 +93,16 @@ public class SerializationTest { private static final XmldbURI TEST_XML_DOC_WITH_DOCTYPE_URI = XmldbURI.create("test-with-doctype.xml"); private static final String XML_WITH_DOCTYPE = - "\n" + - ""; + """ + + """; private static final XmldbURI TEST_XML_DOC_WITH_XMLDECL_URI = XmldbURI.create("test-with-xmldecl.xml"); private static final String XML_WITH_XMLDECL = - "\n" + - ""; + """ + + """; @Parameterized.Parameters(name = "{0}") public static java.util.Collection data() { diff --git a/exist-core/src/test/java/org/exist/xmldb/TestEXistXMLSerialize.java b/exist-core/src/test/java/org/exist/xmldb/TestEXistXMLSerialize.java index 632bd03e650..34929e61c5f 100644 --- a/exist-core/src/test/java/org/exist/xmldb/TestEXistXMLSerialize.java +++ b/exist-core/src/test/java/org/exist/xmldb/TestEXistXMLSerialize.java @@ -30,7 +30,7 @@ import java.io.StringWriter; import java.net.URISyntaxException; import java.net.URL; -import java.nio.file.Paths; +import java.nio.file.Path; import java.util.Properties; import javax.xml.parsers.ParserConfigurationException; @@ -113,7 +113,7 @@ public void serialize1() throws TransformerException, XMLDBException, ParserConf XMLResource resource = testCollection.createResource(null, XMLResource.class); Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance( ). - newDocumentBuilder().parse(Paths.get(testFile.toURI()).toFile()); + newDocumentBuilder().parse(Path.of(testFile.toURI()).toFile()); resource.setContentAsDOM(doc); testCollection.storeResource(resource); @@ -136,7 +136,7 @@ public void serialize1() throws TransformerException, XMLDBException, ParserConf @Test public void serialize2() throws ParserConfigurationException, SAXException, IOException, XMLDBException, URISyntaxException { Collection testCollection = DatabaseManager.getCollection(XmldbURI.LOCAL_DB + "/" + TEST_COLLECTION); - Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance( ).newDocumentBuilder().parse(Paths.get(testFile.toURI()).toFile()); + Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance( ).newDocumentBuilder().parse(Path.of(testFile.toURI()).toFile()); XMLResource resource = testCollection.createResource(null, XMLResource.class); resource.setContentAsDOM(doc); testCollection.storeResource(resource); @@ -152,12 +152,10 @@ public void serialize2() throws ParserConfigurationException, SAXException, IOEx try (final UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) { XMLSerializer serializer = new XMLSerializer(out, format); - if (node instanceof Document) { - serializer.serialize((Document) node); - } else if (node instanceof Element) { - serializer.serialize((Element) node); - } else { - fail("Can't serialize node type: " + node); + switch (node) { + case Document document -> serializer.serialize(document); + case Element element -> serializer.serialize(element); + default -> fail("Can't serialize node type: " + node); } } } @@ -165,7 +163,7 @@ public void serialize2() throws ParserConfigurationException, SAXException, IOEx @Test public void serialize3() throws ParserConfigurationException, SAXException, IOException, XMLDBException, TransformerException, URISyntaxException { Collection testCollection = DatabaseManager.getCollection(XmldbURI.LOCAL_DB + "/" + TEST_COLLECTION); - Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance( ).newDocumentBuilder().parse(Paths.get(testFile.toURI()).toFile()); + Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance( ).newDocumentBuilder().parse(Path.of(testFile.toURI()).toFile()); XMLResource resource = testCollection.createResource(null, XMLResource.class); resource.setContentAsDOM(doc); testCollection.storeResource(resource); @@ -185,7 +183,7 @@ public void serialize3() throws ParserConfigurationException, SAXException, IOEx public void serialize4() throws ParserConfigurationException, SAXException, IOException, XMLDBException, URISyntaxException { Collection testCollection = DatabaseManager.getCollection(XmldbURI.LOCAL_DB + "/" + TEST_COLLECTION); - Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance( ).newDocumentBuilder().parse(Paths.get(testFile.toURI()).toFile()); + Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance( ).newDocumentBuilder().parse(Path.of(testFile.toURI()).toFile()); XMLResource resource = testCollection.createResource(null, XMLResource.class); resource.setContentAsDOM(doc); @@ -222,4 +220,4 @@ public void serialize5() throws XMLDBException { SAXSerializer serializer = new SAXSerializer(writer, outputProperties); resource.getContentAsSAX(serializer); } -} \ No newline at end of file +} diff --git a/exist-core/src/test/java/org/exist/xmldb/concurrent/ConcurrentResourceTest2.java b/exist-core/src/test/java/org/exist/xmldb/concurrent/ConcurrentResourceTest2.java index 3b893556ded..b003d498e5e 100644 --- a/exist-core/src/test/java/org/exist/xmldb/concurrent/ConcurrentResourceTest2.java +++ b/exist-core/src/test/java/org/exist/xmldb/concurrent/ConcurrentResourceTest2.java @@ -30,7 +30,6 @@ import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Arrays; import java.util.List; @@ -63,7 +62,7 @@ public String getTestCollectionName() { private String getModsPath() { try { final URI uri = ConcurrentResourceTest2.class.getResource("/samples/mods/mod1.xml").toURI(); - final Path dir = Paths.get(uri).getParent(); + final Path dir = Path.of(uri).getParent(); return dir.toAbsolutePath().toString(); } catch (final URISyntaxException e) { throw new RuntimeException("Cannot resolve samples/mods path", e); diff --git a/exist-core/src/test/java/org/exist/xmldb/concurrent/DeadlockTest.java b/exist-core/src/test/java/org/exist/xmldb/concurrent/DeadlockTest.java index 70978bede4e..38fa47f4de9 100644 --- a/exist-core/src/test/java/org/exist/xmldb/concurrent/DeadlockTest.java +++ b/exist-core/src/test/java/org/exist/xmldb/concurrent/DeadlockTest.java @@ -41,11 +41,14 @@ public class DeadlockTest { private static final Logger LOG = LogManager.getLogger(DeadlockTest.class); - public static final String DOCUMENT_CONTENT = "\n" - + " value1\n" - + " value2\n" - + " value3\n" - + " value4\n" + "\n"; + public static final String DOCUMENT_CONTENT = """ + + value1 + value2 + value3 + value4 + + """; @Test public void deadlock() throws Exception { @@ -86,4 +89,4 @@ public void run() { } } } -} \ No newline at end of file +} diff --git a/exist-core/src/test/java/org/exist/xmldb/concurrent/action/MultiResourcesAction.java b/exist-core/src/test/java/org/exist/xmldb/concurrent/action/MultiResourcesAction.java index 1cbff274a3a..7af7c01a648 100644 --- a/exist-core/src/test/java/org/exist/xmldb/concurrent/action/MultiResourcesAction.java +++ b/exist-core/src/test/java/org/exist/xmldb/concurrent/action/MultiResourcesAction.java @@ -24,7 +24,6 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.List; import org.exist.util.FileUtils; @@ -53,7 +52,7 @@ public boolean execute() throws XMLDBException, IOException { } private void addFiles(final Collection col) throws XMLDBException, IOException { - final Path d = Paths.get(dirPath); + final Path d = Path.of(dirPath); if(!(Files.isReadable(d) && Files.isDirectory(d))) { throw new RuntimeException("Cannot read directory: " + dirPath); } diff --git a/exist-core/src/test/java/org/exist/xmldb/concurrent/action/XQueryUpdateAction.java b/exist-core/src/test/java/org/exist/xmldb/concurrent/action/XQueryUpdateAction.java index 7c42aefd5a3..766ceb5962d 100644 --- a/exist-core/src/test/java/org/exist/xmldb/concurrent/action/XQueryUpdateAction.java +++ b/exist-core/src/test/java/org/exist/xmldb/concurrent/action/XQueryUpdateAction.java @@ -30,17 +30,18 @@ public class XQueryUpdateAction extends Action { private static final String query = - "util:exclusive-lock(collection('/db/C1'),\n" + - " let $maxId := max(for $i in //node/@id return xs:integer($i)) + 1\n" + - " let $update :=\n" + - " \n" + - " \n" + - " appended node\n" + - " \n" + - " \n" + - " return\n" + - " xmldb:update('/db/C1', $update)" + - ")"; + """ + util:exclusive-lock(collection('/db/C1'), + let $maxId := max(for $i in //node/@id return xs:integer($i)) + 1 + let $update := + + + appended node + + + return + xmldb:update('/db/C1', $update)\ + )"""; public XQueryUpdateAction(final String collectionPath, final String resourceName) { super(collectionPath, resourceName); diff --git a/exist-core/src/test/java/org/exist/xmlrpc/QuerySessionTest.java b/exist-core/src/test/java/org/exist/xmlrpc/QuerySessionTest.java index 2eb68a96c2a..afbdd42d6ea 100755 --- a/exist-core/src/test/java/org/exist/xmlrpc/QuerySessionTest.java +++ b/exist-core/src/test/java/org/exist/xmlrpc/QuerySessionTest.java @@ -51,27 +51,28 @@ public class QuerySessionTest { public final static ExistWebServer existWebServer = new ExistWebServer(true, false, true, true); private final static String generateXQ = - "declare function local:random-sequence($length as xs:integer, $G as map(xs:string, item())) {\n" - + " if ($length eq 0)\n" - + " then ()\n" - + " else ($G?number, local:random-sequence($length - 1, $G?next()))\n" - + "};\n" - + "let $rnd := fn:random-number-generator() return" - + "" - + " " - + " {local:random-sequence(7, $rnd)}" - + " {" - + " for $section in 1 to 8 return" - + "
" - + " {local:random-sequence(7, $rnd)}" - + " {" - + " for $para in 1 to 10 return" - + " {local:random-sequence(120, $rnd)}" - + " }" - + "
" - + " }" - + "
" - + "
"; + """ + declare function local:random-sequence($length as xs:integer, $G as map(xs:string, item())) { + if ($length eq 0) + then () + else ($G?number, local:random-sequence($length - 1, $G?next())) + }; + let $rnd := fn:random-number-generator() return\ + \ + \ + {local:random-sequence(7, $rnd)}\ + {\ + for $section in 1 to 8 return\ +
\ + {local:random-sequence(7, $rnd)}\ + {\ + for $para in 1 to 10 return\ + {local:random-sequence(120, $rnd)}\ + }\ +
\ + }\ +
\ +
"""; private final static String QUERY = "declare variable $n external;" + diff --git a/exist-core/src/test/java/org/exist/xquery/AbsolutePathTests.java b/exist-core/src/test/java/org/exist/xquery/AbsolutePathTests.java index 74c1b24ed0f..2232020d297 100644 --- a/exist-core/src/test/java/org/exist/xquery/AbsolutePathTests.java +++ b/exist-core/src/test/java/org/exist/xquery/AbsolutePathTests.java @@ -89,10 +89,11 @@ public void immediateLambdaContainsDoubleSlash() throws EXistException, Permissi public void immediateLambdaWithDocumentAndDoubleSlash() throws EXistException, PermissionDeniedException { final Source expected = elemSource(""); - final String query = "let $f := function($d) { $d ! //x }\n" + - "let $d := document { }\n" + - "return\n" + - " { $f($d) }"; + final String query = """ + let $f := function($d) { $d ! //x } + let $d := document { } + return + { $f($d) }"""; final Either actual = executeQuery(query); assertXQResultIdentical(expected, actual); @@ -102,10 +103,11 @@ public void immediateLambdaWithDocumentAndDoubleSlash() throws EXistException, P public void immediateLambdaWithDocumentAndSlash() throws EXistException, PermissionDeniedException { final Source expected = elemSource(""); - final String query = "let $f := function($d) { $d ! /root }\n" + - "let $d := document { }\n" + - "return\n" + - " $f($d)"; + final String query = """ + let $f := function($d) { $d ! /root } + let $d := document { } + return + $f($d)"""; final Either actual = executeQuery(query); assertXQResultIdentical(expected, actual); @@ -115,10 +117,11 @@ public void immediateLambdaWithDocumentAndSlash() throws EXistException, Permiss public void immediateLambdaWithDocumentAndLoneSlash() throws EXistException, PermissionDeniedException { final Source expected = docSource(""); - final String query = "let $f := function($d) { $d ! / }\n" + - "let $d := document { }\n" + - "return\n" + - " $f($d)"; + final String query = """ + let $f := function($d) { $d ! / } + let $d := document { } + return + $f($d)"""; final Either actual = executeQuery(query); assertXQResultSimilar(expected, actual); diff --git a/exist-core/src/test/java/org/exist/xquery/AbstractDescendantOrSelfNodeKindTest.java b/exist-core/src/test/java/org/exist/xquery/AbstractDescendantOrSelfNodeKindTest.java index bb0ba727458..57cb2e3c111 100644 --- a/exist-core/src/test/java/org/exist/xquery/AbstractDescendantOrSelfNodeKindTest.java +++ b/exist-core/src/test/java/org/exist/xquery/AbstractDescendantOrSelfNodeKindTest.java @@ -37,18 +37,19 @@ public abstract class AbstractDescendantOrSelfNodeKindTest { @ClassRule public final static ExistXmldbEmbeddedServer existEmbeddedServer = new ExistXmldbEmbeddedServer(false, true, true); - protected final static String TEST_DOCUMENT = "\n"+ - "\n"+ - " \n"+ - " texttexttext\n"+ - " \n"+ - " \n"+ - " \n"+ - " text\n"+ - " \n"+ - " \n"+ - " \n"+ - ""; + protected final static String TEST_DOCUMENT = """ + + + + texttexttext + + + + text + + + + """; protected abstract ResourceSet executeQueryOnDoc(final String docQuery) throws XMLDBException; diff --git a/exist-core/src/test/java/org/exist/xquery/CleanupTest.java b/exist-core/src/test/java/org/exist/xquery/CleanupTest.java index 1b183e0d703..4affdaae71d 100644 --- a/exist-core/src/test/java/org/exist/xquery/CleanupTest.java +++ b/exist-core/src/test/java/org/exist/xquery/CleanupTest.java @@ -65,10 +65,11 @@ public class CleanupTest { "\"xmldb:exist:///db/test/test-module.xql\";" + "t:test('Hello world')"; - private final static String TEST_INLINE = "let $a := \"a\"\n" + - "let $func := function() { $a }\n" + - "return\n" + - " $func"; + private final static String TEST_INLINE = """ + let $a := "a" + let $func := function() { $a } + return + $func"""; private final static String INTERNAL_MODULE_TEST = "import module namespace tt=\"" + MODULE_NS + "\" at " + "\"java:org.exist.xquery.TestModule\";" + diff --git a/exist-core/src/test/java/org/exist/xquery/ConstructedNodesRecoveryTest.java b/exist-core/src/test/java/org/exist/xquery/ConstructedNodesRecoveryTest.java index 190ac850f42..3217b10392e 100644 --- a/exist-core/src/test/java/org/exist/xquery/ConstructedNodesRecoveryTest.java +++ b/exist-core/src/test/java/org/exist/xquery/ConstructedNodesRecoveryTest.java @@ -67,22 +67,24 @@ public class ConstructedNodesRecoveryTest { private final static String xquery = - "declare variable $categories := \n" + - " \n" + - " Fruit\n" + - " Vegetable\n" + - " Meat\n" + - " Dairy\n" + - " \n" + - ";\n\n" + - - "for $category in $categories/category return\n" + - " element option {\n" + - " attribute value {\n" + - " $category/@uid\n" + - " },\n" + - " text { $category }\n" + - " }"; + """ + declare variable $categories :=\s + + Fruit + Vegetable + Meat + Dairy + + ; + + for $category in $categories/category return + element option { + attribute value { + $category/@uid + }, + text { $category } + }\ + """; private final static String expectedResults [] = { "Fruit", diff --git a/exist-core/src/test/java/org/exist/xquery/ConstructedNodesTest.java b/exist-core/src/test/java/org/exist/xquery/ConstructedNodesTest.java index c00da0b2cb1..a5e40a70f82 100644 --- a/exist-core/src/test/java/org/exist/xquery/ConstructedNodesTest.java +++ b/exist-core/src/test/java/org/exist/xquery/ConstructedNodesTest.java @@ -51,22 +51,24 @@ public class ConstructedNodesTest { @Test public void iterateConstructNodes() throws XPathException, XMLDBException { String xquery = - "declare variable $categories := \n" + - " \n" + - " Fruit\n" + - " Vegetable\n" + - " Meat\n" + - " Dairy\n" + - " \n" + - ";\n\n" + - - "for $category in $categories/category return\n" + - " element option {\n" + - " attribute value {\n" + - " $category/@uid\n" + - " },\n" + - " text { $category }\n" + - " }"; + """ + declare variable $categories :=\s + + Fruit + Vegetable + Meat + Dairy + + ; + + for $category in $categories/category return + element option { + attribute value { + $category/@uid + }, + text { $category } + }\ + """; String expectedResults [] = { "", @@ -91,16 +93,17 @@ public void iterateConstructNodes() throws XPathException, XMLDBException { @Test public void constructedNodesSort() throws XMLDBException { String xquery = - "declare variable $categories := \n" + - " \n" + - " Fruit\n" + - " Vegetable\n" + - " Meat\n" + - " Dairy\n" + - " \n" + - ";\n\n" + - - "for $category in $categories/category order by $category/@uid descending return $category"; + """ + declare variable $categories :=\s + + Fruit + Vegetable + Meat + Dairy + + ; + + for $category in $categories/category order by $category/@uid descending return $category"""; String expectedResults [] = { "Dairy", @@ -125,17 +128,18 @@ public void constructedNodesSort() throws XMLDBException { @Test public void constructedNodesPosition() throws XMLDBException { String xquery = - "declare variable $categories := \n" + - " \n" + - " Fruit\n" + - " Vegetable\n" + - " Meat\n" + - " Dairy\n" + - " \n" + - ";\n\n" + - - "$categories/category[1],\n" + - "$categories/category[position() eq 1]"; + """ + declare variable $categories :=\s + + Fruit + Vegetable + Meat + Dairy + + ; + + $categories/category[1], + $categories/category[position() eq 1]"""; String expectedResults [] = { "Fruit", @@ -160,9 +164,10 @@ public void constructedNodesPosition() throws XMLDBException { @Test public void constructedTextNodes() throws XMLDBException { String xquery = - "declare variable $hello-text-first := { \"hello\" }world;\n" + - "declare variable $hello-text-last := world{ \"hello\" };\n" + - "($hello-text-first, $hello-text-last)"; + """ + declare variable $hello-text-first := { "hello" }world; + declare variable $hello-text-last := world{ "hello" }; + ($hello-text-first, $hello-text-last)"""; String expectedResults [] = { "helloworld", diff --git a/exist-core/src/test/java/org/exist/xquery/ConversionsTest.java b/exist-core/src/test/java/org/exist/xquery/ConversionsTest.java index 9ce19bd4c24..67d4ee861e2 100644 --- a/exist-core/src/test/java/org/exist/xquery/ConversionsTest.java +++ b/exist-core/src/test/java/org/exist/xquery/ConversionsTest.java @@ -40,11 +40,12 @@ public class ConversionsTest { /** test conversion from QName to string */ @Test public void qname2string() throws XMLDBException { - final String query = "declare namespace foo = 'http://foo'; \n" + - "let $a := ( xs:QName('foo:bar'), xs:QName('foo:john'), xs:QName('foo:doe') )\n" + - "for $b in $a \n" + - "return \n" + - "{string($b)}" ; + final String query = """ + declare namespace foo = 'http://foo';\s + let $a := ( xs:QName('foo:bar'), xs:QName('foo:john'), xs:QName('foo:doe') ) + for $b in $a\s + return\s + {string($b)}""" ; final ResourceSet result = existEmbeddedServer.executeQuery( query ); /* which returns : foo:bar diff --git a/exist-core/src/test/java/org/exist/xquery/CountExpressionTest.java b/exist-core/src/test/java/org/exist/xquery/CountExpressionTest.java index 6798961fc92..a2fa1a9d290 100644 --- a/exist-core/src/test/java/org/exist/xquery/CountExpressionTest.java +++ b/exist-core/src/test/java/org/exist/xquery/CountExpressionTest.java @@ -44,15 +44,16 @@ public class CountExpressionTest { @Test public void countTest() throws RecognitionException, XPathException, TokenStreamException, QName.IllegalQNameException { - final String query = "xquery version \"3.1\";\n" + - "for $p in $products\n" + - "order by $p/sales descending\n" + - "count $rank\n" + - "where $rank <= 3\n" + - "return\n" + - " \n" + - " {$p/name, $p/sales}\n" + - " "; + final String query = """ + xquery version "3.1"; + for $p in $products + order by $p/sales descending + count $rank + where $rank <= 3 + return + + {$p/name, $p/sales} + """; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); diff --git a/exist-core/src/test/java/org/exist/xquery/DocumentUpdateTest.java b/exist-core/src/test/java/org/exist/xquery/DocumentUpdateTest.java index 17534a21b3e..e2ed1156572 100644 --- a/exist-core/src/test/java/org/exist/xquery/DocumentUpdateTest.java +++ b/exist-core/src/test/java/org/exist/xquery/DocumentUpdateTest.java @@ -51,8 +51,10 @@ public class DocumentUpdateTest { @Test public void update() throws XMLDBException { String imports = - "import module namespace xdb='http://exist-db.org/xquery/xmldb';\n" + - "import module namespace util='http://exist-db.org/xquery/util';\n"; + """ + import module namespace xdb='http://exist-db.org/xquery/xmldb'; + import module namespace util='http://exist-db.org/xquery/util'; + """; //TEST 1: doc() function String query = imports + diff --git a/exist-core/src/test/java/org/exist/xquery/DuplicateAttributesTest.java b/exist-core/src/test/java/org/exist/xquery/DuplicateAttributesTest.java index ead782d2fbc..08171ef1995 100644 --- a/exist-core/src/test/java/org/exist/xquery/DuplicateAttributesTest.java +++ b/exist-core/src/test/java/org/exist/xquery/DuplicateAttributesTest.java @@ -56,24 +56,25 @@ public class DuplicateAttributesTest { private static String STORED_DOC2 = ""; private static String DOC_WITH_DTD = - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - "\n" + - " \n" + - "\n" + - "]>\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " "; + """ + + + + + + + + \s + + ]> + + + + + \s + """; /** * Add attribute to element which already has an attribute of that name. @@ -82,9 +83,10 @@ public class DuplicateAttributesTest { public void appendStoredAttrFail() throws XMLDBException { XQueryService xqs = testCollection.getService(XQueryService.class); String query = - "let $a := \n" + - "{doc(\"/db/test/stored1.xml\")//@attr}" + - "return $a"; + """ + let $a :=\s + {doc("/db/test/stored1.xml")//@attr}\ + return $a"""; xqs.query(query); } @@ -96,9 +98,10 @@ public void appendStoredAttrOK() { try { XQueryService xqs = testCollection.getService(XQueryService.class); String query = - "let $a := \n" + - "{doc(\"/db/test/stored2.xml\")//@attr2}" + - "return $a"; + """ + let $a :=\s + {doc("/db/test/stored2.xml")//@attr2}\ + return $a"""; ResourceSet result = xqs.query(query); assertEquals(1, result.getSize()); assertEquals("", result.getResource(0).getContent()); @@ -116,10 +119,11 @@ public void appendStoredAttrOK() { public void appendConstrAttr() throws XMLDBException { XQueryService xqs = testCollection.getService(XQueryService.class); String query = - "let $a := " + - "let $b := \n" + - " {$a//@attr}" + - "return $a"; + """ + let $a := \ + let $b :=\s + {$a//@attr}\ + return $a"""; xqs.query(query); } @@ -160,4 +164,4 @@ public static void cleanup() throws XMLDBException { final CollectionManagementService service = existEmbeddedServer.getRoot().getService(CollectionManagementService.class); service.removeCollection("test"); } -} \ No newline at end of file +} diff --git a/exist-core/src/test/java/org/exist/xquery/ForwardReferenceTest.java b/exist-core/src/test/java/org/exist/xquery/ForwardReferenceTest.java index ffd47489159..8acd3912732 100644 --- a/exist-core/src/test/java/org/exist/xquery/ForwardReferenceTest.java +++ b/exist-core/src/test/java/org/exist/xquery/ForwardReferenceTest.java @@ -60,55 +60,61 @@ public class ForwardReferenceTest { private static final XmldbURI CONFIG_MODULE_NAME = XmldbURI.create("config.xqm"); private static final InputSource CONFIG_MODULE = new StringInputSource( - ("xquery version \"3.1\";\n" + - "module namespace config = \"http://example.com/config\";\n" + - "\n" + - "import module namespace pages = \"http://example.com/pages\" at \"pages.xqm\";\n" + - "\n" + - "declare variable $config:PUBLICATIONS := map {\n" + - " \"short-title\" : \"My Non-default Short Title\"\n" + - "};\n" + - "\n" + - "declare variable $config:OPEN_GRAPH as map(xs:string, function(*)) := map {\n" + - " \"og:type\" : function($node, $model) {\n" + - " \n" + - " },\n" + - " \"og:title\": function($node, $model) {\n" + - " \n" + - " }\n" + - "};").getBytes(UTF_8)); + (""" + xquery version "3.1"; + module namespace config = "http://example.com/config"; + + import module namespace pages = "http://example.com/pages" at "pages.xqm"; + + declare variable $config:PUBLICATIONS := map { + "short-title" : "My Non-default Short Title" + }; + + declare variable $config:OPEN_GRAPH as map(xs:string, function(*)) := map { + "og:type" : function($node, $model) { + + }, + "og:title": function($node, $model) { + + } + };\ + """).getBytes(UTF_8)); private static XmldbURI CONFIG_MODULE_URI = null; private static final XmldbURI PAGES_MODULE_NAME = XmldbURI.create("pages.xqm"); private static final InputSource PAGES_MODULE = new StringInputSource( - ("xquery version \"3.1\";\n" + - "module namespace pages = \"http://example.com/pages\";\n" + - "\n" + - "import module namespace config = \"http://example.com/config\" at \"config.xqm\";\n" + - "\n" + - "declare function pages:generate-short-title($node, $model) as xs:string? {\n" + - " ( \n" + - " $config:PUBLICATIONS?short-title,\n" + - " 'My Default Short Title'\n" + - " )[. ne ''][1]\n" + - "};").getBytes(UTF_8)); + (""" + xquery version "3.1"; + module namespace pages = "http://example.com/pages"; + + import module namespace config = "http://example.com/config" at "config.xqm"; + + declare function pages:generate-short-title($node, $model) as xs:string? { + ( \s + $config:PUBLICATIONS?short-title, + 'My Default Short Title' + )[. ne ''][1] + };\ + """).getBytes(UTF_8)); private static XmldbURI PAGES_MODULE_URI = null; private static final XmldbURI TEST_PAGES_MODULE_NAME = XmldbURI.create("test-pages.xqm"); private static final InputSource TEST_PAGES_MODULE = new StringInputSource( - ("xquery version \"3.1\";\n" + - "module namespace test-pages = \"http://example.com/test-pages\";\n" + - "\n" + - "import module namespace pages = \"http://example.com/pages\" at \"pages.xqm\";\n" + - "import module namespace config = \"http://example.com/config\" at \"config.xqm\";\n" + - "\n" + - "declare namespace test = \"http://exist-db.org/xquery/xqsuite\";\n" + - "\n" + - "declare\n" + - " %test:assertEquals(\"My Non-default Short Title\")\n" + - "function test-pages:generate-short-title-default() {\n" + - " pages:generate-short-title((),())\n" + - "};\n").getBytes(UTF_8)); + (""" + xquery version "3.1"; + module namespace test-pages = "http://example.com/test-pages"; + + import module namespace pages = "http://example.com/pages" at "pages.xqm"; + import module namespace config = "http://example.com/config" at "config.xqm"; + + declare namespace test = "http://exist-db.org/xquery/xqsuite"; + + declare + %test:assertEquals("My Non-default Short Title") + function test-pages:generate-short-title-default() { + pages:generate-short-title((),()) + }; + """).getBytes(UTF_8)); private static XmldbURI TEST_PAGES_MODULE_URI = null; @BeforeClass diff --git a/exist-core/src/test/java/org/exist/xquery/FunctionTypeInElementContentTest.java b/exist-core/src/test/java/org/exist/xquery/FunctionTypeInElementContentTest.java index 4dd4da8599d..694a93b7c67 100644 --- a/exist-core/src/test/java/org/exist/xquery/FunctionTypeInElementContentTest.java +++ b/exist-core/src/test/java/org/exist/xquery/FunctionTypeInElementContentTest.java @@ -130,9 +130,7 @@ public void arrayOfMaps() throws EXistException, PermissionDeniedException { final String query = "element test { [map {}] }"; final String error = "Enclosed expression contains function item"; assertXQDynamicError(ErrorCodes.XQTY0105, 1, 16, error, executeQuery(query)); - }; - - // TODO(JL): add (sub-expression) location + }// TODO(JL): add (sub-expression) location // TODO(JL): This should throw at compile time, but does not @Test public void mapConstructorInSubExpression() throws EXistException, PermissionDeniedException { diff --git a/exist-core/src/test/java/org/exist/xquery/ImportModuleTest.java b/exist-core/src/test/java/org/exist/xquery/ImportModuleTest.java index f224803f45f..368d3a2d12b 100644 --- a/exist-core/src/test/java/org/exist/xquery/ImportModuleTest.java +++ b/exist-core/src/test/java/org/exist/xquery/ImportModuleTest.java @@ -103,11 +103,13 @@ public void prefixXmlNs() throws SAXException, PermissionDeniedException, IOExce */ private @Nullable ErrorCodes.ErrorCode prefixNot(final String prefix) throws EXistException, IOException, PermissionDeniedException, LockException, SAXException { final String module = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + """; final String query = "import module namespace " + prefix + " = \"http://example.com/impl\" at \"xmldb:exist:///db/impl1.xqm\";\n" + @@ -149,26 +151,32 @@ public void prefixXmlNs() throws SAXException, PermissionDeniedException, IOExce @Test public void prefixSameAsOtherImport() throws EXistException, IOException, SAXException, PermissionDeniedException, LockException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string, $b as xs:string) as xs:string {\n" + - " fn:concat($a, ' ', $b)\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string, $b as xs:string) as xs:string { + fn:concat($a, ' ', $b) + }; + """; final String query = - "import module namespace impl = \"http://example.com/impl\" at \"xmldb:exist:///db/impl1.xqm\";\n" + - "import module namespace impl = \"http://example.com/impl\" at \"xmldb:exist:///db/impl2.xqm\";\n" + - "\n" + - " {impl:f1(\"to impl1\")}" + - " {impl:f1(\"to\", \"impl1\")}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl" at "xmldb:exist:///db/impl1.xqm"; + import module namespace impl = "http://example.com/impl" at "xmldb:exist:///db/impl2.xqm"; + + {impl:f1("to impl1")}\ + {impl:f1("to", "impl1")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -207,18 +215,22 @@ public void prefixSameAsOtherImport() throws EXistException, IOException, SAXExc @Test public void prefixSameAsOtherNamespaceDeclaration() throws EXistException, IOException, SAXException, PermissionDeniedException, LockException { final String module = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + """; final String query = - "declare namespace impl = \"http://example.com/impl\";\n" + - "import module namespace impl = \"http://example.com/impl\" at \"xmldb:exist:///db/impl1.xqm\";\n" + - "\n" + - " {impl:f1(\"to impl1\")}" + - "\n"; + """ + declare namespace impl = "http://example.com/impl"; + import module namespace impl = "http://example.com/impl" at "xmldb:exist:///db/impl1.xqm"; + + {impl:f1("to impl1")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -254,26 +266,32 @@ public void prefixSameAsOtherNamespaceDeclaration() throws EXistException, IOExc @Test public void prefixSameAsModuleDeclaration() throws EXistException, IOException, SAXException, PermissionDeniedException, LockException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "import module namespace impl = \"http://example.com/impl\" at \"xmldb:exist:///db/impl2.xqm\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + import module namespace impl = "http://example.com/impl" at "xmldb:exist:///db/impl2.xqm"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string, $b as xs:string) as xs:string {\n" + - " fn:concat($a, ' ', $b)\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string, $b as xs:string) as xs:string { + fn:concat($a, ' ', $b) + }; + """; final String query = - "declare namespace impl = \"http://example.com/impl\";\n" + - "import module namespace impl = \"http://example.com/impl\" at \"xmldb:exist:///db/impl1.xqm\";\n" + - "\n" + - " {impl:f1(\"to impl1\")}" + - "\n"; + """ + declare namespace impl = "http://example.com/impl"; + import module namespace impl = "http://example.com/impl" at "xmldb:exist:///db/impl1.xqm"; + + {impl:f1("to impl1")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -311,17 +329,21 @@ public void prefixSameAsModuleDeclaration() throws EXistException, IOException, @Test public void emptyNamespace() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException { final String module = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + """; final String query = - "import module namespace impl = \"\" at \"xmldb:exist:///db/impl1.xqm\";\n" + - "\n" + - " {impl:f1(\"to impl1\")}" + - "\n"; + """ + import module namespace impl = "" at "xmldb:exist:///db/impl1.xqm"; + + {impl:f1("to impl1")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -357,28 +379,34 @@ public void emptyNamespace() throws EXistException, IOException, PermissionDenie @Test public void namespaceSameAsOtherImport() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string, $b as xs:string) as xs:string {\n" + - " fn:concat($a, ' ', $b)\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string, $b as xs:string) as xs:string { + fn:concat($a, ' ', $b) + }; + """; final String query = - "import module namespace impl1 = \"http://example.com/impl\"" + - " at \"xmldb:exist:///db/impl1.xqm\";\n" + - "import module namespace impl2 = \"http://example.com/impl\"" + - " at \"xmldb:exist:///db/impl2.xqm\";\n" + - "\n" + - " {impl1:f1(\"to impl1\")}" + - " {impl2:f1(\"to\", \"impl2\")}" + - "\n"; + """ + import module namespace impl1 = "http://example.com/impl"\ + at "xmldb:exist:///db/impl1.xqm"; + import module namespace impl2 = "http://example.com/impl"\ + at "xmldb:exist:///db/impl2.xqm"; + + {impl1:f1("to impl1")}\ + {impl2:f1("to", "impl2")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -416,10 +444,12 @@ public void namespaceSameAsOtherImport() throws EXistException, IOException, Per @Test public void noSuchModuleWithLocationHint() throws EXistException, IOException, PermissionDeniedException { final String query = - "import module namespace impl = \"http://example.com/impl\" at \"xmldb:exist:///db/impl1.xqm\";\n" + - "\n" + - " {impl:f1(\"to impl1\")}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl" at "xmldb:exist:///db/impl1.xqm"; + + {impl:f1("to impl1")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -451,10 +481,12 @@ public void noSuchModuleWithLocationHint() throws EXistException, IOException, P @Test public void noSuchModuleWithoutLocationHint() throws EXistException, IOException, PermissionDeniedException { final String query = - "import module namespace impl = \"http://example.com/impl\";\n" + - "\n" + - " {impl:f1(\"to impl1\")}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl"; + + {impl:f1("to impl1")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -486,26 +518,32 @@ public void noSuchModuleWithoutLocationHint() throws EXistException, IOException @Test public void functionSameAsOtherModule() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + """; final String query = - "import module namespace impl = \"http://example.com/impl\"" + - " at \"xmldb:exist:///db/impl1.xqm\", \"xmldb:exist:///db/impl2.xqm\";\n" + - "\n" + - " {impl:f1(\"to impl1\")}" + - " {impl:f1(\"to impl1\")}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl"\ + at "xmldb:exist:///db/impl1.xqm", "xmldb:exist:///db/impl2.xqm"; + + {impl:f1("to impl1")}\ + {impl:f1("to impl1")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -544,18 +582,20 @@ public void functionSameAsOtherModule() throws EXistException, IOException, Perm @Test public void functionDuplicateInMainModule() throws EXistException, IOException, PermissionDeniedException, LockException, TriggerException, XPathException { final String query = - "declare function local:f1($a as xs:string) as xs:string {\n" + - " {$a}\n" + - "};\n" + - "\n" + - "declare function local:f1($a as xs:string) as xs:string {\n" + - " {$a}\n" + - "};\n" + - "\n" + - "\n" + - " {local:f1(\"to impl1\")}" + - " {local:f1(\"to impl1\")}" + - "\n"; + """ + declare function local:f1($a as xs:string) as xs:string { + {$a} + }; + + declare function local:f1($a as xs:string) as xs:string { + {$a} + }; + + + {local:f1("to impl1")}\ + {local:f1("to impl1")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -588,21 +628,23 @@ public void functionDuplicateInMainModule() throws EXistException, IOException, @Test public void functionDuplicateNsInMainModule() throws EXistException, IOException, PermissionDeniedException, LockException, TriggerException, XPathException { final String query = - "declare namespace ns1 = 'http://ns1';\n" + - "declare namespace ns12 = 'http://ns1';\n" + - "\n" + - "declare function ns1:f1($a as xs:string) as xs:string {\n" + - " {$a}\n" + - "};\n" + - "\n" + - "declare function ns12:f1($a as xs:string) as xs:string {\n" + - " {$a}\n" + - "};\n" + - "\n" + - "\n" + - " {ns1:f1(\"to impl1\")}" + - " {ns12:f1(\"to impl1\")}" + - "\n"; + """ + declare namespace ns1 = 'http://ns1'; + declare namespace ns12 = 'http://ns1'; + + declare function ns1:f1($a as xs:string) as xs:string { + {$a} + }; + + declare function ns12:f1($a as xs:string) as xs:string { + {$a} + }; + + + {ns1:f1("to impl1")}\ + {ns12:f1("to impl1")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -635,21 +677,25 @@ public void functionDuplicateNsInMainModule() throws EXistException, IOException @Test public void functionSameAsImportingModule() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException { final String module = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + """; final String query = - "import module namespace impl = \"http://example.com/impl\"" + - " at \"xmldb:exist:///db/impl1.xqm\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n" + - "\n" + - " {impl:f1(\"to impl1\")}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl"\ + at "xmldb:exist:///db/impl1.xqm"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + + {impl:f1("to impl1")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -687,21 +733,27 @@ public void functionSameAsImportingModule() throws EXistException, IOException, @Test public void variableSameAsOtherModule() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare variable $impl:f1 := \"impl1\";\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare variable $impl:f1 := "impl1"; + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare variable $impl:f1 := \"impl2\";\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare variable $impl:f1 := "impl2"; + """; final String query = - "import module namespace impl = \"http://example.com/impl\"" + - " at \"xmldb:exist:///db/impl1.xqm\", \"xmldb:exist:///db/impl2.xqm\";\n" + - "\n" + - " {$impl:f1}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl"\ + at "xmldb:exist:///db/impl1.xqm", "xmldb:exist:///db/impl2.xqm"; + + {$impl:f1}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -739,17 +791,21 @@ public void variableSameAsOtherModule() throws EXistException, IOException, Perm @Test public void variableSameAsImportingModule() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException { final String module = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare variable $impl:f1 := \"impl1\";\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare variable $impl:f1 := "impl1"; + """; final String query = - "import module namespace impl = \"http://example.com/impl\"" + - " at \"xmldb:exist:///db/impl1.xqm\";\n" + - "declare variable $impl:f1 := \"this\";\n" + - "\n" + - " {$impl:f1}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl"\ + at "xmldb:exist:///db/impl1.xqm"; + declare variable $impl:f1 := "this"; + + {$impl:f1}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -786,17 +842,21 @@ public void variableSameAsImportingModule() throws EXistException, IOException, @Test public void functionsSingleLocationHint() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException, XPathException { final String module = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + """; final String query = - "import module namespace impl = \"http://example.com/impl\" at \"xmldb:exist:///db/impl1.xqm\";\n" + - "\n" + - " {impl:f1(\"to impl1\")}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl" at "xmldb:exist:///db/impl1.xqm"; + + {impl:f1("to impl1")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -841,34 +901,42 @@ public void functionsSingleLocationHint() throws EXistException, IOException, Pe @Test public void functionsCompositeFromMultipleLocationHints() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException, XPathException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string) as xs:string { + $a + }; + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f1($a as xs:string, $b as xs:string) as xs:string {\n" + - " fn:concat($a, ' ', $b)\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f1($a as xs:string, $b as xs:string) as xs:string { + fn:concat($a, ' ', $b) + }; + """; final String module3 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare function impl:f2($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare function impl:f2($a as xs:string) as xs:string { + $a + }; + """; final String query = - "import module namespace impl = \"http://example.com/impl\"" + - " at \"xmldb:exist:///db/impl1.xqm\", \"xmldb:exist:///db/impl2.xqm\", \"xmldb:exist:///db/impl3.xqm\";\n" + - "\n" + - " {impl:f1(\"to impl1\")}" + - " {impl:f1(\"to\", \"impl2\")}" + - " {impl:f2(\"to impl3\")}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl"\ + at "xmldb:exist:///db/impl1.xqm", "xmldb:exist:///db/impl2.xqm", "xmldb:exist:///db/impl3.xqm"; + + {impl:f1("to impl1")}\ + {impl:f1("to", "impl2")}\ + {impl:f2("to impl3")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -921,34 +989,42 @@ public void functionsCompositeFromMultipleLocationHints() throws EXistException, @Test public void functionsCompositeFromMultipleLocationHintsWithDifferingPrefixes() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException, XPathException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace impl1 = \"http://example.com/impl\";\n" + - "declare function impl1:f1($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl1 = "http://example.com/impl"; + declare function impl1:f1($a as xs:string) as xs:string { + $a + }; + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace impl2 = \"http://example.com/impl\";\n" + - "declare function impl2:f1($a as xs:string, $b as xs:string) as xs:string {\n" + - " fn:concat($a, ' ', $b)\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl2 = "http://example.com/impl"; + declare function impl2:f1($a as xs:string, $b as xs:string) as xs:string { + fn:concat($a, ' ', $b) + }; + """; final String module3 = - "xquery version \"1.0\";\n" + - "module namespace impl3 = \"http://example.com/impl\";\n" + - "declare function impl3:f2($a as xs:string) as xs:string {\n" + - " $a\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl3 = "http://example.com/impl"; + declare function impl3:f2($a as xs:string) as xs:string { + $a + }; + """; final String query = - "import module namespace impl = \"http://example.com/impl\"" + - " at \"xmldb:exist:///db/impl1.xqm\", \"xmldb:exist:///db/impl2.xqm\", \"xmldb:exist:///db/impl3.xqm\";\n" + - "\n" + - " {impl:f1(\"to impl1\")}" + - " {impl:f1(\"to\", \"impl2\")}" + - " {impl:f2(\"to impl3\")}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl"\ + at "xmldb:exist:///db/impl1.xqm", "xmldb:exist:///db/impl2.xqm", "xmldb:exist:///db/impl3.xqm"; + + {impl:f1("to impl1")}\ + {impl:f1("to", "impl2")}\ + {impl:f2("to impl3")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -1001,15 +1077,19 @@ public void functionsCompositeFromMultipleLocationHintsWithDifferingPrefixes() t @Test public void variablesSingleLocationHint() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException, XPathException { final String module = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare variable $impl:v1 := \"impl1\";\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare variable $impl:v1 := "impl1"; + """; final String query = - "import module namespace impl = \"http://example.com/impl\" at \"xmldb:exist:///db/impl1.xqm\";\n" + - "\n" + - " {$impl:v1}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl" at "xmldb:exist:///db/impl1.xqm"; + + {$impl:v1}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -1054,28 +1134,36 @@ public void variablesSingleLocationHint() throws EXistException, IOException, Pe @Test public void variablesCompositeFromMultipleLocationHints() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException, XPathException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare variable $impl:v1 := \"impl1\";\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare variable $impl:v1 := "impl1"; + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare variable $impl:v2 := \"impl2\";\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare variable $impl:v2 := "impl2"; + """; final String module3 = - "xquery version \"1.0\";\n" + - "module namespace impl = \"http://example.com/impl\";\n" + - "declare variable $impl:v3 := \"impl3\";\n"; + """ + xquery version "1.0"; + module namespace impl = "http://example.com/impl"; + declare variable $impl:v3 := "impl3"; + """; final String query = - "import module namespace impl = \"http://example.com/impl\"" + - " at \"xmldb:exist:///db/impl1.xqm\", \"xmldb:exist:///db/impl2.xqm\", \"xmldb:exist:///db/impl3.xqm\";\n" + - "\n" + - " {$impl:v1}" + - " {$impl:v2}" + - " {$impl:v3}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl"\ + at "xmldb:exist:///db/impl1.xqm", "xmldb:exist:///db/impl2.xqm", "xmldb:exist:///db/impl3.xqm"; + + {$impl:v1}\ + {$impl:v2}\ + {$impl:v3}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -1128,28 +1216,36 @@ public void variablesCompositeFromMultipleLocationHints() throws EXistException, @Test public void variablesCompositeFromMultipleLocationHintsWithDifferingPrefixes() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException, XPathException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace impl1 = \"http://example.com/impl\";\n" + - "declare variable $impl1:v1 := \"impl1\";\n"; + """ + xquery version "1.0"; + module namespace impl1 = "http://example.com/impl"; + declare variable $impl1:v1 := "impl1"; + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace impl2 = \"http://example.com/impl\";\n" + - "declare variable $impl2:v2 := \"impl2\";\n"; + """ + xquery version "1.0"; + module namespace impl2 = "http://example.com/impl"; + declare variable $impl2:v2 := "impl2"; + """; final String module3 = - "xquery version \"1.0\";\n" + - "module namespace impl3 = \"http://example.com/impl\";\n" + - "declare variable $impl3:v3 := \"impl3\";\n"; + """ + xquery version "1.0"; + module namespace impl3 = "http://example.com/impl"; + declare variable $impl3:v3 := "impl3"; + """; final String query = - "import module namespace impl = \"http://example.com/impl\"" + - " at \"xmldb:exist:///db/impl1.xqm\", \"xmldb:exist:///db/impl2.xqm\", \"xmldb:exist:///db/impl3.xqm\";\n" + - "\n" + - " {$impl:v1}" + - " {$impl:v2}" + - " {$impl:v3}" + - "\n"; + """ + import module namespace impl = "http://example.com/impl"\ + at "xmldb:exist:///db/impl1.xqm", "xmldb:exist:///db/impl2.xqm", "xmldb:exist:///db/impl3.xqm"; + + {$impl:v1}\ + {$impl:v2}\ + {$impl:v3}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -1199,34 +1295,40 @@ public void variablesCompositeFromMultipleLocationHintsWithDifferingPrefixes() t @Test public void variablesBetweenModules() throws EXistException, PermissionDeniedException, IOException, LockException, SAXException, XPathException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace mod1 = \"http://example.com/mod1\";\n" + - "declare variable $mod1:var1 := \"mod1 var1\";\n" + - "declare function mod1:test() {\n" + - " \n" + - " {$mod1:var1}\n" + - " \n" + - "};"; + """ + xquery version "1.0"; + module namespace mod1 = "http://example.com/mod1"; + declare variable $mod1:var1 := "mod1 var1"; + declare function mod1:test() { + + {$mod1:var1} + + };\ + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace mod2 = \"http://example.com/mod2\";\n" + - "declare variable $mod2:var1 := \"mod2 var1\";\n" + - "import module namespace mod1 = \"http://example.com/mod1\" at \"xmldb:exist:///db/mod1.xqm\";\n" + - "declare function mod2:test() {\n" + - " \n" + - " {$mod2:var1}\n" + - " { mod1:test() }\n" + - " {$mod1:var1}\n" + - " \n" + - "};"; + """ + xquery version "1.0"; + module namespace mod2 = "http://example.com/mod2"; + declare variable $mod2:var1 := "mod2 var1"; + import module namespace mod1 = "http://example.com/mod1" at "xmldb:exist:///db/mod1.xqm"; + declare function mod2:test() { + + {$mod2:var1} + { mod1:test() } + {$mod1:var1} + + };\ + """; final String query = - "xquery version \"1.0\";\n" + - " import module namespace mod2 = 'http://example.com/mod2' at 'xmldb:exist:///db/mod2.xqm';\n" + - "\n" + - " {mod2:test()}\n" + - "\n"; + """ + xquery version "1.0"; + import module namespace mod2 = 'http://example.com/mod2' at 'xmldb:exist:///db/mod2.xqm'; + + {mod2:test()} + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -1285,30 +1387,36 @@ public void variablesBetweenModules() throws EXistException, PermissionDeniedExc @Test public void xq10CyclicTwoLibraryModules() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace impl1 = \"http://example.com/impl1\";\n" + - "import module namespace impl2 = \"http://example.com/impl2\"" + - " at \"xmldb:exist:///db/impl2.xqm\";\n" + - "declare function impl1:f1($a as xs:string) {\n" + - " {$a}\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl1 = "http://example.com/impl1"; + import module namespace impl2 = "http://example.com/impl2"\ + at "xmldb:exist:///db/impl2.xqm"; + declare function impl1:f1($a as xs:string) { + {$a} + }; + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace impl2 = \"http://example.com/impl2\";\n" + - "import module namespace impl1 = \"http://example.com/impl1\"" + - " at \"xmldb:exist:///db/impl1.xqm\";\n" + - "declare function impl2:f1($a as xs:string) as xs:string {\n" + - " {$a}\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl2 = "http://example.com/impl2"; + import module namespace impl1 = "http://example.com/impl1"\ + at "xmldb:exist:///db/impl1.xqm"; + declare function impl2:f1($a as xs:string) as xs:string { + {$a} + }; + """; final String query = - "xquery version \"1.0\";\n" + - "import module namespace impl1 = \"http://example.com/impl1\"" + - " at \"xmldb:exist:///db/impl1.xqm\";\n" + - "\n" + - " {impl1:f1(\"from main\")}" + - "\n"; + """ + xquery version "1.0"; + import module namespace impl1 = "http://example.com/impl1"\ + at "xmldb:exist:///db/impl1.xqm"; + + {impl1:f1("from main")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -1349,30 +1457,36 @@ public void xq10CyclicTwoLibraryModules() throws EXistException, IOException, Pe @Test public void xq31CyclicTwoLibraryModules() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException, XPathException { final String module1 = - "xquery version \"3.1\";\n" + - "module namespace impl1 = \"http://example.com/impl1\";\n" + - "import module namespace impl2 = \"http://example.com/impl2\"" + - " at \"xmldb:exist:///db/impl2.xqm\";\n" + - "declare function impl1:f1($a as xs:string) {\n" + - " {$a}\n" + - "};\n"; + """ + xquery version "3.1"; + module namespace impl1 = "http://example.com/impl1"; + import module namespace impl2 = "http://example.com/impl2"\ + at "xmldb:exist:///db/impl2.xqm"; + declare function impl1:f1($a as xs:string) { + {$a} + }; + """; final String module2 = - "xquery version \"3.1\";\n" + - "module namespace impl2 = \"http://example.com/impl2\";\n" + - "import module namespace impl1 = \"http://example.com/impl1\"" + - " at \"xmldb:exist:///db/impl1.xqm\";\n" + - "declare function impl2:f1($a as xs:string) as xs:string {\n" + - " {$a}\n" + - "};\n"; + """ + xquery version "3.1"; + module namespace impl2 = "http://example.com/impl2"; + import module namespace impl1 = "http://example.com/impl1"\ + at "xmldb:exist:///db/impl1.xqm"; + declare function impl2:f1($a as xs:string) as xs:string { + {$a} + }; + """; final String query = - "xquery version \"3.1\";\n" + - "import module namespace impl1 = \"http://example.com/impl1\"" + - " at \"xmldb:exist:///db/impl1.xqm\";\n" + - "\n" + - " {impl1:f1(\"from main\")}" + - "\n"; + """ + xquery version "3.1"; + import module namespace impl1 = "http://example.com/impl1"\ + at "xmldb:exist:///db/impl1.xqm"; + + {impl1:f1("from main")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -1425,39 +1539,47 @@ public void xq31CyclicTwoLibraryModules() throws EXistException, IOException, Pe @Test public void xq10CyclicThreeLibraryModules() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException { final String module1 = - "xquery version \"1.0\";\n" + - "module namespace impl1 = \"http://example.com/impl1\";\n" + - "import module namespace impl2 = \"http://example.com/impl2\"" + - " at \"xmldb:exist:///db/impl2.xqm\";\n" + - "declare function impl1:f1($a as xs:string) {\n" + - " {$a}\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl1 = "http://example.com/impl1"; + import module namespace impl2 = "http://example.com/impl2"\ + at "xmldb:exist:///db/impl2.xqm"; + declare function impl1:f1($a as xs:string) { + {$a} + }; + """; final String module2 = - "xquery version \"1.0\";\n" + - "module namespace impl2 = \"http://example.com/impl2\";\n" + - "import module namespace impl3 = \"http://example.com/impl3\"" + - " at \"xmldb:exist:///db/impl3.xqm\";\n" + - "declare function impl2:f1($a as xs:string) {\n" + - " {$a}\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl2 = "http://example.com/impl2"; + import module namespace impl3 = "http://example.com/impl3"\ + at "xmldb:exist:///db/impl3.xqm"; + declare function impl2:f1($a as xs:string) { + {$a} + }; + """; final String module3 = - "xquery version \"1.0\";\n" + - "module namespace impl3 = \"http://example.com/impl3\";\n" + - "import module namespace impl1 = \"http://example.com/impl1\"" + - " at \"xmldb:exist:///db/impl1.xqm\";\n" + - "declare function impl3:f1($a as xs:string) {\n" + - " {$a}\n" + - "};\n"; + """ + xquery version "1.0"; + module namespace impl3 = "http://example.com/impl3"; + import module namespace impl1 = "http://example.com/impl1"\ + at "xmldb:exist:///db/impl1.xqm"; + declare function impl3:f1($a as xs:string) { + {$a} + }; + """; final String query = - "xquery version \"1.0\";\n" + - "import module namespace impl1 = \"http://example.com/impl1\"" + - " at \"xmldb:exist:///db/impl1.xqm\";\n" + - "\n" + - " {impl1:f1(\"from main\")}" + - "\n"; + """ + xquery version "1.0"; + import module namespace impl1 = "http://example.com/impl1"\ + at "xmldb:exist:///db/impl1.xqm"; + + {impl1:f1("from main")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); @@ -1499,39 +1621,47 @@ public void xq10CyclicThreeLibraryModules() throws EXistException, IOException, @Test public void xq31CyclicThreeLibraryModules() throws EXistException, IOException, PermissionDeniedException, LockException, SAXException, XPathException { final String module1 = - "xquery version \"3.1\";\n" + - "module namespace impl1 = \"http://example.com/impl1\";\n" + - "import module namespace impl2 = \"http://example.com/impl2\"" + - " at \"xmldb:exist:///db/impl2.xqm\";\n" + - "declare function impl1:f1($a as xs:string) {\n" + - " {$a}\n" + - "};\n"; + """ + xquery version "3.1"; + module namespace impl1 = "http://example.com/impl1"; + import module namespace impl2 = "http://example.com/impl2"\ + at "xmldb:exist:///db/impl2.xqm"; + declare function impl1:f1($a as xs:string) { + {$a} + }; + """; final String module2 = - "xquery version \"3.1\";\n" + - "module namespace impl2 = \"http://example.com/impl2\";\n" + - "import module namespace impl3 = \"http://example.com/impl3\"" + - " at \"xmldb:exist:///db/impl3.xqm\";\n" + - "declare function impl2:f1($a as xs:string) {\n" + - " {$a}\n" + - "};\n"; + """ + xquery version "3.1"; + module namespace impl2 = "http://example.com/impl2"; + import module namespace impl3 = "http://example.com/impl3"\ + at "xmldb:exist:///db/impl3.xqm"; + declare function impl2:f1($a as xs:string) { + {$a} + }; + """; final String module3 = - "xquery version \"3.1\";\n" + - "module namespace impl3 = \"http://example.com/impl3\";\n" + - "import module namespace impl1 = \"http://example.com/impl1\"" + - " at \"xmldb:exist:///db/impl1.xqm\";\n" + - "declare function impl3:f1($a as xs:string) {\n" + - " {$a}\n" + - "};\n"; + """ + xquery version "3.1"; + module namespace impl3 = "http://example.com/impl3"; + import module namespace impl1 = "http://example.com/impl1"\ + at "xmldb:exist:///db/impl1.xqm"; + declare function impl3:f1($a as xs:string) { + {$a} + }; + """; final String query = - "xquery version \"3.1\";\n" + - "import module namespace impl1 = \"http://example.com/impl1\"" + - " at \"xmldb:exist:///db/impl1.xqm\";\n" + - "\n" + - " {impl1:f1(\"from main\")}" + - "\n"; + """ + xquery version "3.1"; + import module namespace impl1 = "http://example.com/impl1"\ + at "xmldb:exist:///db/impl1.xqm"; + + {impl1:f1("from main")}\ + + """; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source source = new StringSource(query); diff --git a/exist-core/src/test/java/org/exist/xquery/ModuleImportTest.java b/exist-core/src/test/java/org/exist/xquery/ModuleImportTest.java index 07dea7ddc8b..29ba709394f 100644 --- a/exist-core/src/test/java/org/exist/xquery/ModuleImportTest.java +++ b/exist-core/src/test/java/org/exist/xquery/ModuleImportTest.java @@ -36,7 +36,6 @@ import java.net.URISyntaxException; import java.nio.file.Path; -import java.nio.file.Paths; import static com.evolvedbinary.j8fu.Either.Left; import static com.evolvedbinary.j8fu.Either.Right; @@ -85,7 +84,7 @@ private static Path getConfigFile() { final String packagePath = ModuleImportTest.class.getPackage().getName().replace('.', separator); try { - return Paths.get(loader.getResource(packagePath + separator + "conf.xml").toURI()); + return Path.of(loader.getResource(packagePath + separator + "conf.xml").toURI()); } catch (final URISyntaxException e) { fail(e); return null; diff --git a/exist-core/src/test/java/org/exist/xquery/NamespaceUpdateTest.java b/exist-core/src/test/java/org/exist/xquery/NamespaceUpdateTest.java index 55cd7fc1ca3..469b91aca71 100644 --- a/exist-core/src/test/java/org/exist/xquery/NamespaceUpdateTest.java +++ b/exist-core/src/test/java/org/exist/xquery/NamespaceUpdateTest.java @@ -55,17 +55,19 @@ public class NamespaceUpdateTest { public void updateAttribute() throws XMLDBException { XQueryService service = testCollection.getService(XQueryService.class); String query = - "declare namespace t='http://www.foo.com';\n" + - "\n" + - "{\n" + - " update insert attribute { 'ID' } { 'myid' } into /t:test\n" + - "}\n" + - ""; + """ + declare namespace t='http://www.foo.com'; + + { + update insert attribute { 'ID' } { 'myid' } into /t:test + } + """; service.query(query); query = - "declare namespace t='http://www.foo.com';\n" + - "/t:test/@ID/string(.)"; + """ + declare namespace t='http://www.foo.com'; + /t:test/@ID/string(.)"""; ResourceSet result = service.query(query); assertEquals(1, result.getSize()); assertEquals("myid", result.getResource(0).getContent().toString()); diff --git a/exist-core/src/test/java/org/exist/xquery/ReservedNamesConflictTest.java b/exist-core/src/test/java/org/exist/xquery/ReservedNamesConflictTest.java index d16283c211c..11d4ce3ed12 100644 --- a/exist-core/src/test/java/org/exist/xquery/ReservedNamesConflictTest.java +++ b/exist-core/src/test/java/org/exist/xquery/ReservedNamesConflictTest.java @@ -42,10 +42,11 @@ public class ReservedNamesConflictTest { @Test public void reservedNamesIssueTest() throws RecognitionException, XPathException, TokenStreamException { - final String query = "xquery version \"3.1\";\n" + - ",\n" + - ",\n" + - ""; + final String query = """ + xquery version "3.1"; + , + , + """; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); diff --git a/exist-core/src/test/java/org/exist/xquery/StoredModuleTest.java b/exist-core/src/test/java/org/exist/xquery/StoredModuleTest.java index 394171d3f31..9f40b5a2ae1 100644 --- a/exist-core/src/test/java/org/exist/xquery/StoredModuleTest.java +++ b/exist-core/src/test/java/org/exist/xquery/StoredModuleTest.java @@ -57,14 +57,16 @@ public class StoredModuleTest { public static final TemporaryFolder temporaryFolder = new TemporaryFolder(); private final static String MODULE = - "module namespace itg-modules = \"http://localhost:80/itg/xquery\";\n" + - "declare variable $itg-modules:colls as xs:string+ external;\n" + - "declare variable $itg-modules:coll as xs:string external;\n" + - "declare variable $itg-modules:ordinal as xs:integer external;\n" + - "declare function itg-modules:check-coll() as xs:boolean {\n" + - " if (fn:empty($itg-modules:coll)) then fn:false()\n" + - " else fn:true()\n" + - "};"; + """ + module namespace itg-modules = "http://localhost:80/itg/xquery"; + declare variable $itg-modules:colls as xs:string+ external; + declare variable $itg-modules:coll as xs:string external; + declare variable $itg-modules:ordinal as xs:integer external; + declare function itg-modules:check-coll() as xs:boolean { + if (fn:empty($itg-modules:coll)) then fn:false() + else fn:true() + };\ + """; private Collection createCollection(String collectionName) throws XMLDBException { Collection collection = existEmbeddedServer.getRoot().getChildCollection(collectionName); diff --git a/exist-core/src/test/java/org/exist/xquery/TransformTest.java b/exist-core/src/test/java/org/exist/xquery/TransformTest.java index a8df3730e42..ab1e56fac8e 100644 --- a/exist-core/src/test/java/org/exist/xquery/TransformTest.java +++ b/exist-core/src/test/java/org/exist/xquery/TransformTest.java @@ -113,35 +113,38 @@ public void setUp() throws ClassNotFoundException, IllegalAccessException, Insta assertNotNull(xsl2); - String doc1 = "\n" + - "\n"+ - "\n" + - "\n" + - "" + - "

Start Template 1

" + - "" + - "" + - "

End Template 1

" + - "
" + - "
" + - "
"; - - String doc2 = "\n" + - "\n"+ - "\n" + - "\n" + - "

Start Template 2

" + - "" + - "

End Template 2

" + - "
" + - "
"; - - String doc3 = "\n" + - "\n"+ - "\n" + - "

Template 3

" + - "
" + - "
"; + String doc1 = """ + + + + + \ +

Start Template 1

\ + \ + \ +

End Template 1

\ +
\ +
\ +
"""; + + String doc2 = """ + + + + +

Start Template 2

\ + \ +

End Template 2

\ +
\ +
"""; + + String doc3 = """ + + + +

Template 3

\ +
\ +
"""; addXMLDocument(xsl1, doc1, "1.xsl"); addXMLDocument(xsl2, doc2, "2.xsl"); diff --git a/exist-core/src/test/java/org/exist/xquery/ValueIndexTest.java b/exist-core/src/test/java/org/exist/xquery/ValueIndexTest.java index 40224469f07..e21f6e11ab1 100644 --- a/exist-core/src/test/java/org/exist/xquery/ValueIndexTest.java +++ b/exist-core/src/test/java/org/exist/xquery/ValueIndexTest.java @@ -24,7 +24,6 @@ import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Path; -import java.nio.file.Paths; import org.exist.test.ExistXmldbEmbeddedServer; import org.exist.xmldb.IndexQueryService; @@ -306,18 +305,20 @@ public void qnameIndex() throws XMLDBException, URISyntaxException { public void indexScan() throws XMLDBException, URISyntaxException { configureCollection(CONFIG_PATH); String queryBody = - "declare namespace f=\'http://exist-db.org/xquery/test\';\n" + - "declare namespace mods='http://www.loc.gov/mods/v3';\n" + - "import module namespace u=\'http://exist-db.org/xquery/util\';\n" + - "\n" + - "declare function f:term-callback($term as item(), $data as xs:int+)\n" + - "as element()+ {\n" + - " \n" + - " {$term}\n" + - " {$data[1]}\n" + - " \n" + - "};\n" + - "\n"; + """ + declare namespace f='http://exist-db.org/xquery/test'; + declare namespace mods='http://www.loc.gov/mods/v3'; + import module namespace u='http://exist-db.org/xquery/util'; + + declare function f:term-callback($term as item(), $data as xs:int+) + as element()+ { + + {$term} + {$data[1]} + + }; + + """; XPathQueryService service = storeXMLFileAndGetQueryService(ITEMS_FILENAME, ITEMS_FILE); String query = queryBody + "u:index-keys(//item/name, \'\', util:function(xs:QName(\'f:term-callback\'), 2), 1000)"; @@ -427,10 +428,10 @@ private ResourceSet queryResource(XPathQueryService service, protected XPathQueryService storeXMLFileAndGetQueryService( String documentName, final URL srcFile) throws XMLDBException, URISyntaxException { XMLResource doc = testCollection.createResource(documentName, XMLResource.class); - Path f = Paths.get(srcFile.toURI()); + Path f = Path.of(srcFile.toURI()); doc.setContent(f); testCollection.storeResource(doc); XPathQueryService service = testCollection.getService(XPathQueryService.class); return service; } -} \ No newline at end of file +} diff --git a/exist-core/src/test/java/org/exist/xquery/VariablesTest.java b/exist-core/src/test/java/org/exist/xquery/VariablesTest.java index befd1e6586a..b78322118e2 100644 --- a/exist-core/src/test/java/org/exist/xquery/VariablesTest.java +++ b/exist-core/src/test/java/org/exist/xquery/VariablesTest.java @@ -45,24 +45,26 @@ public class VariablesTest { public static final ExistXmldbEmbeddedServer existEmbeddedServer = new ExistXmldbEmbeddedServer(false, true, true); private final static String MODULE = - "module namespace mod1 = \"http://mod1\";\n" + - "\n" + - "declare variable $mod1:OPEN_GRAPH as map(xs:string, function(*)) := map {\n" + - " \"og:title\" : function($node, $model) {\n" + - " \n" + - " }\n" + - "};\n" + - "\n" + - "declare variable $mod1:PUBLICATIONS := map {\n" + - " \"open-graph\" : map:merge((\n" + - " $mod1:OPEN_GRAPH,\n" + - " map {\n" + - " \"og:image\" : function($node, $model) {\n" + - " \n" + - " }\n" + - " }\n" + - " ))\n" + - "};"; + """ + module namespace mod1 = "http://mod1"; + + declare variable $mod1:OPEN_GRAPH as map(xs:string, function(*)) := map { + "og:title" : function($node, $model) { + + } + }; + + declare variable $mod1:PUBLICATIONS := map { + "open-graph" : map:merge(( + $mod1:OPEN_GRAPH, + map { + "og:image" : function($node, $model) { + + } + } + )) + };\ + """; @BeforeClass public static void setup() throws XMLDBException { @@ -73,8 +75,9 @@ public static void setup() throws XMLDBException { @Test public void callModule() throws XMLDBException { final String query = - "import module namespace mod1 = \"http://mod1\" at \"xmldb:exist:///db/variables-test/mod1.xqm\";\n" + - "$mod1:PUBLICATIONS(\"open-graph\")"; + """ + import module namespace mod1 = "http://mod1" at "xmldb:exist:///db/variables-test/mod1.xqm"; + $mod1:PUBLICATIONS("open-graph")"""; final ResourceSet rs = existEmbeddedServer.executeQuery(query); assertEquals(1, rs.getSize()); diff --git a/exist-core/src/test/java/org/exist/xquery/WindowClauseTest.java b/exist-core/src/test/java/org/exist/xquery/WindowClauseTest.java index a05ff8491c0..3a335b88457 100644 --- a/exist-core/src/test/java/org/exist/xquery/WindowClauseTest.java +++ b/exist-core/src/test/java/org/exist/xquery/WindowClauseTest.java @@ -46,11 +46,12 @@ public class WindowClauseTest { @Test void simpleWindowConditions() throws RecognitionException, XPathException, TokenStreamException { - final String query = "xquery version \"3.1\";\n" + - "for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)\n" + - " start at $s when fn:true()\n" + - " only end at $e when $e - $s eq 2\n" + - "return { $w }"; + final String query = """ + xquery version "3.1"; + for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) + start at $s when fn:true() + only end at $e when $e - $s eq 2 + return { $w }"""; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); @@ -76,11 +77,12 @@ void simpleWindowConditions() throws RecognitionException, XPathException, Token @Test void complexWindowCondition() throws RecognitionException, XPathException, TokenStreamException { - final String query = "xquery version \"3.1\";\n" + - "for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)\n" + - " start $first next $second when $first/price < $second/price\n" + - " end $last next $beyond when $last/price > $beyond/price\n" + - "return { $w }"; + final String query = """ + xquery version "3.1"; + for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) + start $first next $second when $first/price < $second/price + end $last next $beyond when $last/price > $beyond/price + return { $w }"""; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); @@ -105,10 +107,11 @@ void complexWindowCondition() throws RecognitionException, XPathException, Token @Test void noEndWindowCondition() throws RecognitionException, XPathException, TokenStreamException { - final String query = "xquery version \"3.1\";\n" + - "for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)\n" + - " start $first next $second when $first/price < $second/price\n" + - "return { $w }"; + final String query = """ + xquery version "3.1"; + for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) + start $first next $second when $first/price < $second/price + return { $w }"""; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); @@ -133,11 +136,12 @@ void noEndWindowCondition() throws RecognitionException, XPathException, TokenSt @Test void slidingWindowClause() throws RecognitionException, XPathException, TokenStreamException { - final String query = "xquery version \"3.1\";\n" + - "for sliding window $w in (2, 4, 6, 8, 10, 12, 14)\n" + - " start at $s when fn:true()\n" + - " only end at $e when $e - $s eq 2\n" + - "return { $w }"; + final String query = """ + xquery version "3.1"; + for sliding window $w in (2, 4, 6, 8, 10, 12, 14) + start at $s when fn:true() + only end at $e when $e - $s eq 2 + return { $w }"""; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); @@ -164,12 +168,14 @@ void slidingWindowClause() throws RecognitionException, XPathException, TokenStr @Test void allWindowsVars() throws RecognitionException, XPathException, TokenStreamException, QName.IllegalQNameException { - final String query = "xquery version \"3.1\";\n" + - "for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)\n" + - "start $first at $s previous $start-previous next $start-next when fn:true()\n" + - "only end $last at $e previous $end-previous next $end-next when $e - $s eq 2\n" + - "return\n" + - " {$first, $last}\n"; + final String query = """ + xquery version "3.1"; + for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) + start $first at $s previous $start-previous next $start-next when fn:true() + only end $last at $e previous $end-previous next $end-next when $e - $s eq 2 + return + {$first, $last} + """; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); @@ -204,12 +210,14 @@ void allWindowsVars() throws RecognitionException, XPathException, TokenStreamEx @Test void tumblingWindowAllWindowVarsNoOnly() throws RecognitionException, XPathException, TokenStreamException, QName.IllegalQNameException { - final String query = "xquery version \"3.1\";\n" + - "for tumbling window $w in (2, 4, 6, 8, 10)\n" + - " start $s at $spos previous $sprev next $snext when fn:true() \n" + - " end $e at $epos previous $eprev next $enext when fn:true()\n" + - "return\n" + - " {$first, $last}\n"; + final String query = """ + xquery version "3.1"; + for tumbling window $w in (2, 4, 6, 8, 10) + start $s at $spos previous $sprev next $snext when fn:true()\s + end $e at $epos previous $eprev next $enext when fn:true() + return + {$first, $last} + """; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); @@ -245,11 +253,12 @@ void tumblingWindowAllWindowVarsNoOnly() throws RecognitionException, XPathExcep @Test void tumblingWindowAvgReturn() throws RecognitionException, XPathException, TokenStreamException, QName.IllegalQNameException { - final String query = "xquery version \"3.1\";\n" + - "for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)\n" + - " start at $s when fn:true()\n" + - " only end at $e when $e - $s eq 2\n" + - "return avg($w)"; + final String query = """ + xquery version "3.1"; + for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) + start at $s when fn:true() + only end at $e when $e - $s eq 2 + return avg($w)"""; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); @@ -284,10 +293,11 @@ void tumblingWindowAvgReturn() throws RecognitionException, XPathException, Toke @Test void tumblingWindowNoEndWindowConditionPositional() throws RecognitionException, XPathException, TokenStreamException, QName.IllegalQNameException { - final String query = "xquery version \"3.1\";\n" + - "for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)\n" + - " start at $s when $s mod 3 = 1\n" + - "return { $w }"; + final String query = """ + xquery version "3.1"; + for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) + start at $s when $s mod 3 = 1 + return { $w }"""; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); @@ -317,10 +327,11 @@ void tumblingWindowNoEndWindowConditionPositional() throws RecognitionException, @Test void tumblingWindowNoEndWindowConditionCurrentItem() throws RecognitionException, XPathException, TokenStreamException { - final String query = "xquery version \"3.1\";\n" + - "for tumbling window $w in (2, 4, 6, 8, 10, 12, 14)\n" + - " start $first when $first mod 3 = 0\n" + - "return { $w }"; + final String query = """ + xquery version "3.1"; + for tumbling window $w in (2, 4, 6, 8, 10, 12, 14) + start $first when $first mod 3 = 0 + return { $w }"""; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); @@ -350,11 +361,12 @@ void tumblingWindowNoEndWindowConditionCurrentItem() throws RecognitionException @Test void slidingWindowAvgReturn() throws RecognitionException, XPathException, TokenStreamException, QName.IllegalQNameException { - final String query = "xquery version \"3.1\";\n" + - "for sliding window $w in (2, 4, 6, 8, 10, 12, 14)\n" + - " start at $s when fn:true()\n" + - " only end at $e when $e - $s eq 2\n" + - "return avg($w)"; + final String query = """ + xquery version "3.1"; + for sliding window $w in (2, 4, 6, 8, 10, 12, 14) + start at $s when fn:true() + only end at $e when $e - $s eq 2 + return avg($w)"""; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); @@ -389,11 +401,12 @@ void slidingWindowAvgReturn() throws RecognitionException, XPathException, Token @Test void slidingWindowEndWithoutOnly() throws RecognitionException, XPathException, TokenStreamException, QName.IllegalQNameException { - final String query = "xquery version \"3.1\";\n" + - "for sliding window $w in (2, 4, 6, 8, 10, 12, 14)\n" + - " start at $s when fn:true()\n" + - " end at $e when $e - $s eq 2\n" + - "return { $w }"; + final String query = """ + xquery version "3.1"; + for sliding window $w in (2, 4, 6, 8, 10, 12, 14) + start at $s when fn:true() + end at $e when $e - $s eq 2 + return { $w }"""; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); @@ -428,17 +441,18 @@ void slidingWindowEndWithoutOnly() throws RecognitionException, XPathException, @Test void tumblingWindowRunUp() throws RecognitionException, XPathException, TokenStreamException, QName.IllegalQNameException { - final String query = "xquery version \"3.1\";\n" + - "for tumbling window $w in $closings\n" + - " start $first next $second when $first/price < $second/price\n" + - " end $last next $beyond when $last/price > $beyond/price\n" + - "return\n" + - " \n" + - " {fn:data($first/date)}\n" + - " {fn:data($first/price)}\n" + - " {fn:data($last/date)}\n" + - " {fn:data($last/price)}\n" + - " "; + final String query = """ + xquery version "3.1"; + for tumbling window $w in $closings + start $first next $second when $first/price < $second/price + end $last next $beyond when $last/price > $beyond/price + return + + {fn:data($first/date)} + {fn:data($first/price)} + {fn:data($last/date)} + {fn:data($last/price)} + """; // parse the query into the internal syntax tree final XQueryContext context = new XQueryContext(); diff --git a/exist-core/src/test/java/org/exist/xquery/XPathQueryTest.java b/exist-core/src/test/java/org/exist/xquery/XPathQueryTest.java index 024aad3379b..a5ae2e01f35 100644 --- a/exist-core/src/test/java/org/exist/xquery/XPathQueryTest.java +++ b/exist-core/src/test/java/org/exist/xquery/XPathQueryTest.java @@ -156,18 +156,20 @@ private final String getBaseUri() { private final static String siblings_attr = ""; private final static String siblings_named1 = - "\n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + """; private final static String siblings_named2 = - "\n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + """; private final static String ids_content = "" + @@ -206,17 +208,18 @@ private final String getBaseUri() { "HelloWorld!"; private final static String predicates = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " val1\n" + - " \n" + - " \n" + - " val2\n" + - " \n" + - ""; + """ + + + + + + val1 + + + val2 + + """; // Added by Geoff Shuetrim (geoff@galexy.net) to highlight problems with XPath queries of elements called 'xpointer'. private final static String xpointerElementName = @@ -231,7 +234,7 @@ private final String getBaseUri() { public void setUp() throws Exception { // initialize driver Class cl = Class.forName("org.exist.xmldb.DatabaseImpl"); - Database database = (Database) cl.newInstance(); + Database database = (Database) cl.getDeclaredConstructor().newInstance(); database.setProperty("create-database", "true"); DatabaseManager.registerDatabase(database); @@ -1904,8 +1907,8 @@ public void membersAsResource() throws XMLDBException, IOException { final Resource r = result.getMembersAsResource(); final Object rawContent = r.getContent(); String content = null; - if(rawContent instanceof File) { - final Path p = ((File) rawContent).toPath(); + if(rawContent instanceof File file) { + final Path p = file.toPath(); content = new String(Files.readAllBytes(p), UTF_8); } else { content = (String)r.getContent(); @@ -2066,10 +2069,14 @@ public void convertToBoolean() throws XMLDBException { public void compile() throws XMLDBException { final String invalidQuery = "for $i in (1 to 10)\n return $b"; final String validQuery = "for $i in (1 to 10) return $i"; - final String validModule = "module namespace foo=\"urn:foo\";\n" + - "declare function foo:test() { \"Hello World!\" };"; - final String invalidModule = "module namespace foo=\"urn:foo\";\n" + - "declare function foo:test() { \"Hello World! };"; + final String validModule = """ + module namespace foo="urn:foo"; + declare function foo:test() { "Hello World!" };\ + """; + final String invalidModule = """ + module namespace foo="urn:foo"; + declare function foo:test() { "Hello World! };\ + """; final EXistXQueryService service = (EXistXQueryService) getQueryService(); boolean exceptionOccurred = false; @@ -2116,14 +2123,15 @@ public void xpointerElementNameHandling() throws XMLDBException { @Test public void atomization() throws XMLDBException, IOException, SAXException { final String query = - "declare namespace ex = \"http://example.org\";\n" + - "declare function ex:elementName() as xs:QName {\n" + - " QName(\"http://test.org\", \"test:name\")\n" + - "};\n" + - "{\n" + - " element {QName(\"http://test.org\", \"test:name\") }{},\n" + - " element {ex:elementName()} {}\n" + - "}"; + """ + declare namespace ex = "http://example.org"; + declare function ex:elementName() as xs:QName { + QName("http://test.org", "test:name") + }; + { + element {QName("http://test.org", "test:name") }{}, + element {ex:elementName()} {} + }"""; final EXistXQueryService service = (EXistXQueryService)getQueryService(); service.setProperty(OutputKeys.INDENT, "no"); @@ -2164,9 +2172,11 @@ public void cdataPersistentDom() throws XMLDBException { assertEquals(expected, result.getResource(0).getContent().toString()); query = - "declare namespace output = \"http://www.w3.org/2010/xslt-xquery-serialization\";\n" + - "declare option output:cdata-section-elements \"elem1\";\n" + - "/elem1\n"; + """ + declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization"; + declare option output:cdata-section-elements "elem1"; + /elem1 + """; result = queryResource(service, docName, query, 1); assertEquals(cdata_xml, result.getResource(0).getContent().toString()); diff --git a/exist-core/src/test/java/org/exist/xquery/XQueryContextAttributesTest.java b/exist-core/src/test/java/org/exist/xquery/XQueryContextAttributesTest.java index 46bed3c8f22..af097972398 100644 --- a/exist-core/src/test/java/org/exist/xquery/XQueryContextAttributesTest.java +++ b/exist-core/src/test/java/org/exist/xquery/XQueryContextAttributesTest.java @@ -112,8 +112,10 @@ public void attributesOfLibraryModuleContextCleared() throws EXistException, Loc final XmldbURI libraryQueryUri = XmldbURI.create("/db/mod1.xqm"); final InputSource libraryQuery = new StringInputSource( - ("module namespace mod1 = 'http://mod1';\n" + - "declare function mod1:f1() { };").getBytes(UTF_8) + (""" + module namespace mod1 = 'http://mod1'; + declare function mod1:f1() { };\ + """).getBytes(UTF_8) ); storeQuery(broker, transaction, libraryQueryUri, libraryQuery); diff --git a/exist-core/src/test/java/org/exist/xquery/XQueryDeclareContextItemTest.java b/exist-core/src/test/java/org/exist/xquery/XQueryDeclareContextItemTest.java index b66e30f63a2..72fd2bd568a 100644 --- a/exist-core/src/test/java/org/exist/xquery/XQueryDeclareContextItemTest.java +++ b/exist-core/src/test/java/org/exist/xquery/XQueryDeclareContextItemTest.java @@ -106,9 +106,10 @@ public static void cleanup() throws EXistException, PermissionDeniedException, I @Test public void declareContextItem() throws EXistException, PermissionDeniedException, XPathException { final String query = - "xquery version \"3.0\";\n" + - "declare context item := 3; \n" + - ". + 4"; + """ + xquery version "3.0"; + declare context item := 3;\s + . + 4"""; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final XQuery xquery = pool.getXQueryService(); @@ -126,9 +127,10 @@ public void declareContextItem() throws EXistException, PermissionDeniedExceptio @Test public void declareContextItemIsDocument() throws EXistException, PermissionDeniedException, XPathException { final String query = - "xquery version \"3.0\";\n" + - "declare context item := document { foobaz }; \n" + - "(/) instance of document-node()"; + """ + xquery version "3.0"; + declare context item := document { foobaz };\s + (/) instance of document-node()"""; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final XQuery xquery = pool.getXQueryService(); @@ -143,9 +145,10 @@ public void declareContextItemIsDocument() throws EXistException, PermissionDeni @Test public void declareContextItemTyped() throws EXistException, PermissionDeniedException, XPathException { final String query = - "xquery version \"3.0\";\n" + - "declare context item as xs:integer := 3; \n" + - ". + 4"; + """ + xquery version "3.0"; + declare context item as xs:integer := 3;\s + . + 4"""; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final XQuery xquery = pool.getXQueryService(); @@ -160,9 +163,10 @@ public void declareContextItemTyped() throws EXistException, PermissionDeniedExc @Test public void declareContextItemExternal() throws EXistException, PermissionDeniedException, XPathException { final String query = - "xquery version \"3.0\";\n" + - "declare context item external; \n" + - ". + 4"; + """ + xquery version "3.0"; + declare context item external;\s + . + 4"""; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final XQuery xquery = pool.getXQueryService(); @@ -177,9 +181,10 @@ public void declareContextItemExternal() throws EXistException, PermissionDenied @Test public void declareContextItemExternalDefault() throws EXistException, PermissionDeniedException, XPathException { final String query = - "xquery version \"3.0\";\n" + - "declare context item external := 3; \n" + - ". + 4"; + """ + xquery version "3.0"; + declare context item external := 3;\s + . + 4"""; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final XQuery xquery = pool.getXQueryService(); @@ -194,9 +199,10 @@ public void declareContextItemExternalDefault() throws EXistException, Permissio @Test public void declareContextItemExternalDefaultOverrides() throws EXistException, PermissionDeniedException, XPathException { final String query = - "xquery version \"3.0\";\n" + - "declare context item external := 3; \n" + - ". + 4"; + """ + xquery version "3.0"; + declare context item external := 3;\s + . + 4"""; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final XQuery xquery = pool.getXQueryService(); @@ -211,10 +217,11 @@ public void declareContextItemExternalDefaultOverrides() throws EXistException, @Test public void declareContextItemExternalElement() throws EXistException, PermissionDeniedException, XPathException, SAXException { final String query = - "xquery version \"3.0\";\n" + - "declare namespace env=\"http://www.w3.org/2003/05/soap-envelope\";\n" + - "declare context item as element(env:Envelope) external;\n" + - "{.}"; + """ + xquery version "3.0"; + declare namespace env="http://www.w3.org/2003/05/soap-envelope"; + declare context item as element(env:Envelope) external; + {.}"""; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final XQuery xquery = pool.getXQueryService(); diff --git a/exist-core/src/test/java/org/exist/xquery/XQueryFunctionsTest.java b/exist-core/src/test/java/org/exist/xquery/XQueryFunctionsTest.java index 6443cfee844..6c6b5f8684a 100644 --- a/exist-core/src/test/java/org/exist/xquery/XQueryFunctionsTest.java +++ b/exist-core/src/test/java/org/exist/xquery/XQueryFunctionsTest.java @@ -23,7 +23,6 @@ import java.net.URISyntaxException; import java.nio.file.Path; -import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; @@ -347,10 +346,11 @@ public void max() throws XPathException, XMLDBException { @Test public void exclusiveLock() throws XMLDBException { - String query = "let $query1 := ()\n" + - "let $query2 := (2, 3)\n" + - "let $a := util:exclusive-lock(//*,($query1, $query2))\n" + - "return $a"; + String query = """ + let $query1 := () + let $query2 := (2, 3) + let $a := util:exclusive-lock(//*,($query1, $query2)) + return $a"""; ResourceSet result = existEmbeddedServer.executeQuery(query); assertEquals(3, result.getSize()); String r = (String) result.getResource(0).getContent(); @@ -360,10 +360,11 @@ public void exclusiveLock() throws XMLDBException { r = (String) result.getResource(2).getContent(); assertEquals("3", r); - query = "let $query1 := ()\n" + - "let $query2 := (2, 3)\n" + - "let $a := util:exclusive-lock((),($query1, $query2))\n" + - "return $a"; + query = """ + let $query1 := () + let $query2 := (2, 3) + let $a := util:exclusive-lock((),($query1, $query2)) + return $a"""; result = existEmbeddedServer.executeQuery(query); assertEquals(3, result.getSize()); r = (String) result.getResource(0).getContent(); @@ -373,10 +374,11 @@ public void exclusiveLock() throws XMLDBException { r = (String) result.getResource(2).getContent(); assertEquals("3", r); - query = "let $query1 := ()\n" + - "let $query2 := (2, 3)\n" + - "let $a := util:exclusive-lock((),($query1, $query2))\n" + - "return $a"; + query = """ + let $query1 := () + let $query2 := (2, 3) + let $a := util:exclusive-lock((),($query1, $query2)) + return $a"""; result = existEmbeddedServer.executeQuery(query); assertEquals(3, result.getSize()); r = (String) result.getResource(0).getContent(); @@ -386,8 +388,9 @@ public void exclusiveLock() throws XMLDBException { r = (String) result.getResource(2).getContent(); assertEquals("3", r); - query = "let $a := util:exclusive-lock(//*,)\n" + - "return $a"; + query = """ + let $a := util:exclusive-lock(//*,) + return $a"""; result = existEmbeddedServer.executeQuery(query); r = (String) result.getResource(0).getContent(); assertEquals("", r); @@ -415,11 +418,13 @@ public void utilEval2() throws XMLDBException { @Test public void utilEvalForFunction() throws XMLDBException { - String query = "declare function local:home()\n" - + "{\n" - + "HOME\n" - + "};\n" - + "util:eval(\"local:home()\")\n"; + String query = """ + declare function local:home() + { + HOME + }; + util:eval("local:home()") + """; ResourceSet result = existEmbeddedServer.executeQuery(query); assertEquals(1, result.getSize()); @@ -427,10 +432,11 @@ public void utilEvalForFunction() throws XMLDBException { @Test public void sharedLock() throws XMLDBException { - String query = "let $query1 := ()\n" + - "let $query2 := (2, 3)\n" + - "let $a := util:shared-lock(//*,($query1, $query2))\n" + - "return $a"; + String query = """ + let $query1 := () + let $query2 := (2, 3) + let $a := util:shared-lock(//*,($query1, $query2)) + return $a"""; ResourceSet result = existEmbeddedServer.executeQuery(query); assertEquals(3, result.getSize()); String r = (String) result.getResource(0).getContent(); @@ -440,10 +446,11 @@ public void sharedLock() throws XMLDBException { r = (String) result.getResource(2).getContent(); assertEquals("3", r); - query = "let $query1 := ()\n" + - "let $query2 := (2, 3)\n" + - "let $a := util:shared-lock((),($query1, $query2))\n" + - "return $a"; + query = """ + let $query1 := () + let $query2 := (2, 3) + let $a := util:shared-lock((),($query1, $query2)) + return $a"""; result = existEmbeddedServer.executeQuery(query); assertEquals(3, result.getSize()); r = (String) result.getResource(0).getContent(); @@ -453,10 +460,11 @@ public void sharedLock() throws XMLDBException { r = (String) result.getResource(2).getContent(); assertEquals("3", r); - query = "let $query1 := ()\n" + - "let $query2 := (2, 3)\n" + - "let $a := util:shared-lock((),($query1, $query2))\n" + - "return $a"; + query = """ + let $query1 := () + let $query2 := (2, 3) + let $a := util:shared-lock((),($query1, $query2)) + return $a"""; result = existEmbeddedServer.executeQuery(query); assertEquals(3, result.getSize()); r = (String) result.getResource(0).getContent(); @@ -466,8 +474,9 @@ public void sharedLock() throws XMLDBException { r = (String) result.getResource(2).getContent(); assertEquals("3", r); - query = "let $a := util:shared-lock(//*,)\n" + - "return $a"; + query = """ + let $a := util:shared-lock(//*,) + return $a"""; result = existEmbeddedServer.executeQuery(query); r = (String) result.getResource(0).getContent(); assertEquals("", r); @@ -672,7 +681,7 @@ public void currentDateTime() throws XMLDBException { "('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', " + "'Oct', 'Nov', 'Dec')[month-from-dateTime(current-dateTime())]"); String r = (String) result.getResource(0).getContent(); - SimpleDateFormat df = new SimpleDateFormat("MMM", new Locale("en", "US")); + SimpleDateFormat df = new SimpleDateFormat("MMM", Locale.of("en", "US")); Date date = new Date(); assertEquals(df.format(date), r); @@ -993,7 +1002,7 @@ public void base64BinaryCast() throws XMLDBException, URISyntaxException { Collection testCollection = colService.createCollection(TEST_BINARY_COLLECTION); assertNotNull(testCollection); - final Path fLogo = Paths.get(getClass().getResource("value/logo.jpg").toURI()); + final Path fLogo = Path.of(getClass().getResource("value/logo.jpg").toURI()); //store the eXist logo in the test collection BinaryResource br = testCollection.createResource(BINARY_RESOURCE_FILENAME, BinaryResource.class); diff --git a/exist-core/src/test/java/org/exist/xquery/XQueryProcessingInstructionTest.java b/exist-core/src/test/java/org/exist/xquery/XQueryProcessingInstructionTest.java index da0d84f075d..d588a862159 100644 --- a/exist-core/src/test/java/org/exist/xquery/XQueryProcessingInstructionTest.java +++ b/exist-core/src/test/java/org/exist/xquery/XQueryProcessingInstructionTest.java @@ -43,12 +43,13 @@ public class XQueryProcessingInstructionTest { @Test public void testPI() throws XPathException, SAXException, IOException, XMLDBException { - final String query = "let $xml := " + - "" + - "This is a p." + - "" + - "return\n" + - "$xml"; + final String query = """ + let $xml := \ + \ + This is a p.\ + \ + return + $xml"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); assertXMLEqual(r, "This is a p."); diff --git a/exist-core/src/test/java/org/exist/xquery/XQueryTest.java b/exist-core/src/test/java/org/exist/xquery/XQueryTest.java index 5e91ad1528a..96fb9d3023c 100644 --- a/exist-core/src/test/java/org/exist/xquery/XQueryTest.java +++ b/exist-core/src/test/java/org/exist/xquery/XQueryTest.java @@ -58,6 +58,7 @@ import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; +import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.util.Arrays; @@ -96,51 +97,72 @@ public class XQueryTest { private static final String CHILD1_MODULE_NAME = "child1.xqm"; private static final String CHILD2_MODULE_NAME = "child2.xqm"; private static final String NAMESPACED_NAME = "namespaced.xml"; - private final static String URI = XmldbURI.LOCAL_DB; + private final static String LOCAL_URI = XmldbURI.LOCAL_DB; private final static String numbers = "" + "5.622" + "7.443" + "18.45" + "65.5416" + ""; private final static String module1 = - "module namespace blah=\"blah\";\n" + "declare variable $blah:param := \"value-1\";"; + """ + module namespace blah="blah"; + declare variable $blah:param := "value-1"; + """; private final static String module2 = - "module namespace foo=\"\";\n" + "declare variable $foo:bar := \"bar\";"; + """ + module namespace foo=""; + declare variable $foo:bar := "bar"; + """; private final static String module3 = - "module namespace foo=\"foo\";\n" + "declare variable $bar:bar := \"bar\";"; + """ + module namespace foo="foo"; + declare variable $bar:bar := "bar"; + """; private final static String module4 = "module namespace foo=\"foo\";\n" //An external prefix in the statically known namespaces + "declare variable $exist:bar external;\n" + "declare function foo:bar() {\n" + "$exist:bar\n" + "};"; private final static String module5 = - "module namespace foo=\"foo\";\n" + "declare variable $foo:bar := \"bar\";"; + """ + module namespace foo="foo"; + declare variable $foo:bar := "bar"; + """; private final static String module6 = - "module namespace foo=\"foo\";\n" + "declare variable $foo:bar := \"bar\";" + "declare variable $foo:bar := \"bar\";"; + """ + module namespace foo="foo"; + declare variable $foo:bar := "bar"; + declare variable $foo:bar := "bar"; + """; private final static String module7 = - "module namespace foo=\"foo\";\n" + - "declare namespace xhtml=\"http://www.w3.org/1999/xhtml\";\n" + - "declare function foo:link() { Link };" + - "declare function foo:copy($node) { element { node-name($node) } { $node/text() } };"; + """ + module namespace foo="foo"; + declare namespace xhtml="http://www.w3.org/1999/xhtml"; + declare function foo:link() { Link }; + declare function foo:copy($node) { element { node-name($node) } { $node/text() } }; + """; private final static String module8 = - "module namespace dr = \"double-root2\"; \n" - +"declare function dr:documentIn() as document-node() { \n" - +" let $doc := \n" - +" return document { $doc } \n" - +"};"; + """ + module namespace dr = "double-root2";\s + declare function dr:documentIn() as document-node() {\s + let $doc := \s + return document { $doc }\s + }; + """; private final static String fatherModule = - "module namespace foo=\"foo\";\n" + "import module namespace foo1=\"foo1\" at \"" + URI + "/test/" + CHILD1_MODULE_NAME + "\";\n" + "import module namespace foo2=\"foo2\" at \"" + URI + "/test/" + CHILD2_MODULE_NAME + "\";\n" + "declare variable $foo:bar := \"bar\";\n " + "declare variable $foo:bar1 := $foo1:bar;\n" + "declare variable $foo:bar2 := $foo2:bar;\n"; + "module namespace foo=\"foo\";\n" + "import module namespace foo1=\"foo1\" at \"" + LOCAL_URI + "/test/" + CHILD1_MODULE_NAME + "\";\n" + "import module namespace foo2=\"foo2\" at \"" + LOCAL_URI + "/test/" + CHILD2_MODULE_NAME + "\";\n" + "declare variable $foo:bar := \"bar\";\n " + "declare variable $foo:bar1 := $foo1:bar;\n" + "declare variable $foo:bar2 := $foo2:bar;\n"; private final static String child1Module = - "module namespace foo=\"foo1\";\n" + "import module namespace blah=\"blah\" at \"" + URI + "/test/" + MODULE1_NAME + "\";\n" + "declare variable $foo:bar := \"bar1\";"; + "module namespace foo=\"foo1\";\n" + "import module namespace blah=\"blah\" at \"" + LOCAL_URI + "/test/" + MODULE1_NAME + "\";\n" + "declare variable $foo:bar := \"bar1\";"; private final static String child2Module = - "module namespace foo=\"foo2\";\n" + "import module namespace blah=\"blah\" at \"" + URI + "/test/" + MODULE1_NAME + "\";\n" + "declare variable $foo:bar := \"bar2\";"; + "module namespace foo=\"foo2\";\n" + "import module namespace blah=\"blah\" at \"" + LOCAL_URI + "/test/" + MODULE1_NAME + "\";\n" + "declare variable $foo:bar := \"bar2\";"; private final static String namespacedDocument = - "\n" + - " \n" + - " title\n" + - " creator\n" + - " place\n" + - " place\n" + - " \n" + - ""; + """ + + + title + creator + place + place + + """; private final static String bowling = "" + "" + @@ -277,13 +299,14 @@ public void testFor() throws XMLDBException { @Test public void recursion() throws XMLDBException { String q1 = - "declare function local:append($head, $i) {\n" + - " if ($i < 5000) then\n" + - " local:append(($head, $i), $i + 1)\n" + - " else\n" + - " $head\n" + - "};\n" + - "local:append((), 0)"; + """ + declare function local:append($head, $i) { + if ($i < 5000) then + local:append(($head, $i), $i + 1) + else + $head + }; + local:append((), 0)"""; XPathQueryService service = getTestCollection().getService(XPathQueryService.class); ResourceSet result = service.query(q1); @@ -307,24 +330,30 @@ public void combiningNodeSequences() throws XMLDBException { XPathQueryService service = getTestCollection().getService(XPathQueryService.class); - query = "let $a := \n" + - "let $aa := ($a, $a) \n" + - "for $b in ($aa intersect $aa \n)" + - "return $b"; + query = """ + let $a := \s + let $aa := ($a, $a)\s + for $b in ($aa intersect $aa\s + )\ + return $b"""; result = service.query(query); assertEquals("XQuery: " + query, 1, result.getSize()); assertEquals("XQuery: " + query, "", result.getResource(0).getContent()); - query = "let $a := \n" + - "let $aa := ($a, $a) \n" + - "for $b in ($aa union $aa \n)" + - "return $b"; + query = """ + let $a := \s + let $aa := ($a, $a)\s + for $b in ($aa union $aa\s + )\ + return $b"""; result = service.query(query); assertEquals("XQuery: " + query, 1, result.getSize()); assertEquals("XQuery: " + query, "", result.getResource(0).getContent()); - query = "let $a := \n" + - "let $aa := ($a, $a) \n" + - "for $b in ($aa except $aa \n)" + - "return $b"; + query = """ + let $a := \s + let $aa := ($a, $a)\s + for $b in ($aa except $aa\s + )\ + return $b"""; result = service.query(query); assertEquals("XQuery: " + query, 0, result.getSize()); } @@ -821,7 +850,7 @@ public void namespace() throws XMLDBException, IOException, SAXException { XPathQueryService service = testCollection.getService(XPathQueryService.class); - query = "xquery version \"1.0\";\n" + "import module namespace blah=\"blah\" at \"" + URI + "/test/" + MODULE1_NAME + "\";\n" + "(:: redefine existing prefix ::)\n" + "declare namespace blah=\"bla\";\n" + "$blah:param"; + query = "xquery version \"1.0\";\n" + "import module namespace blah=\"blah\" at \"" + LOCAL_URI + "/test/" + MODULE1_NAME + "\";\n" + "(:: redefine existing prefix ::)\n" + "declare namespace blah=\"bla\";\n" + "$blah:param"; try { message = ""; result = service.query(query); @@ -829,7 +858,7 @@ public void namespace() throws XMLDBException, IOException, SAXException { message = e.getMessage(); } assertTrue(message.indexOf("XQST0033") > -1); - query = "xquery version \"1.0\";\n" + "import module namespace blah=\"blah\" at \"" + URI + "/test/" + MODULE1_NAME + "\";\n" + "(:: redefine existing prefix with same getUri ::)\n" + "declare namespace blah=\"blah\";\n" + "declare variable $blah:param := \"value-2\";\n" + "$blah:param"; + query = "xquery version \"1.0\";\n" + "import module namespace blah=\"blah\" at \"" + LOCAL_URI + "/test/" + MODULE1_NAME + "\";\n" + "(:: redefine existing prefix with same getUri ::)\n" + "declare namespace blah=\"blah\";\n" + "declare variable $blah:param := \"value-2\";\n" + "$blah:param"; try { message = ""; result = service.query(query); @@ -837,7 +866,7 @@ public void namespace() throws XMLDBException, IOException, SAXException { message = e.getMessage(); } assertTrue(message.indexOf("XQST0033") > -1); - query = "xquery version \"1.0\";\n" + "import module namespace foo=\"ho\" at \"" + URI + "/test/" + MODULE1_NAME + "\";\n" + "$foo:bar"; + query = "xquery version \"1.0\";\n" + "import module namespace foo=\"ho\" at \"" + LOCAL_URI + "/test/" + MODULE1_NAME + "\";\n" + "$foo:bar"; try { message = ""; result = service.query(query); @@ -845,7 +874,7 @@ public void namespace() throws XMLDBException, IOException, SAXException { message = e.getMessage(); } assertTrue(message.indexOf("does not match namespace URI") > -1); - query = "xquery version \"1.0\";\n" + "import module namespace foo=\"ho\" at \"" + URI + "/test/" + MODULE2_NAME + "\";\n" + "$bar"; + query = "xquery version \"1.0\";\n" + "import module namespace foo=\"ho\" at \"" + LOCAL_URI + "/test/" + MODULE2_NAME + "\";\n" + "$bar"; try { message = ""; result = service.query(query); @@ -853,7 +882,7 @@ public void namespace() throws XMLDBException, IOException, SAXException { message = e.getMessage(); } assertTrue(message.indexOf("No namespace defined for prefix") > -1); - query = "xquery version \"1.0\";\n" + "import module namespace foo=\"blah\" at \"" + URI + "/test/" + MODULE2_NAME + "\";\n" + "$bar"; + query = "xquery version \"1.0\";\n" + "import module namespace foo=\"blah\" at \"" + LOCAL_URI + "/test/" + MODULE2_NAME + "\";\n" + "$bar"; try { message = ""; result = service.query(query); @@ -877,26 +906,28 @@ public void namespace() throws XMLDBException, IOException, SAXException { query = "{//rdf:Description}"; result = service.query(query); assertEquals(query, - "\n" + - " \n" + - " title\n" + - " creator\n" + - " place\n" + - " place\n" + - " \n" + - "", + """ + + + title + creator + place + place + + """, result.getResource(0).getContent()); query = "{//Description}"; result = service.query(query); assertEquals("XQuery: " + query, - "\n" + - " \n" + - " title\n" + - " creator\n" + - " place\n" + - " place\n" + - " \n" + - "", + """ + + + title + creator + place + place + + """, result.getResource(0).getContent()); //Interesting one : let's see with XQuery gurus :-) @@ -921,23 +952,24 @@ public void namespaceWithTransform() throws XMLDBException { XPathQueryService service = getTestCollection().getService(XPathQueryService.class); String query = - "xquery version \"1.0\";\n" + - "declare namespace transform=\"http://exist-db.org/xquery/transform\";\n" + - "declare variable $xml := \n" + - " text\n" + - ";\n" + - "declare variable $xslt := \n" + - " \n" + - " \n" + - "
\n" + - "
\n" + - "
\n" + - ";\n" + - "\n" + - " \n" + - " {transform:transform($xml, $xslt, ())}\n" + - " \n" + - ""; + """ + xquery version "1.0"; + declare namespace transform="http://exist-db.org/xquery/transform"; + declare variable $xml :=\s + text + ; + declare variable $xslt :=\s + + +
+
+
+ ; + + + {transform:transform($xml, $xslt, ())} + + """; ResourceSet result = service.query(query); @@ -994,7 +1026,7 @@ public void module() throws XMLDBException { XPathQueryService service = testCollection.getService( XPathQueryService.class); - query = "xquery version \"1.0\";\n" + "import module namespace blah=\"blah\" at \"" + URI + "/test/" + MODULE1_NAME + "\";\n" + "$blah:param"; + query = "xquery version \"1.0\";\n" + "import module namespace blah=\"blah\" at \"" + LOCAL_URI + "/test/" + MODULE1_NAME + "\";\n" + "$blah:param"; result = service.query(query); assertEquals("XQuery: " + query, 1, result.getSize()); assertEquals("XQuery: " + query, "value-1", result.getResource(0).getContent()); @@ -1007,11 +1039,11 @@ public void module() throws XMLDBException { // message = e.getMessage(); // } // assertTrue(message.indexOf("XQST0049") > -1); - query = "xquery version \"1.0\";\n" + "import module namespace blah=\"blah\" at \"" + URI + "/test/" + MODULE1_NAME + "\";\n" + "declare namespace blah2=\"blah\";\n" + "$blah2:param"; + query = "xquery version \"1.0\";\n" + "import module namespace blah=\"blah\" at \"" + LOCAL_URI + "/test/" + MODULE1_NAME + "\";\n" + "declare namespace blah2=\"blah\";\n" + "$blah2:param"; result = service.query(query); assertEquals("XQuery: " + query, 1, result.getSize()); assertEquals("XQuery: " + query, "value-1", result.getResource(0).getContent()); - query = "xquery version \"1.0\";\n" + "import module namespace blah=\"bla\" at \"" + URI + "/test/" + MODULE1_NAME + "\";\n" + "$blah:param"; + query = "xquery version \"1.0\";\n" + "import module namespace blah=\"bla\" at \"" + LOCAL_URI + "/test/" + MODULE1_NAME + "\";\n" + "$blah:param"; try { message = ""; result = service.query(query); @@ -1019,7 +1051,7 @@ public void module() throws XMLDBException { message = e.getMessage(); } assertTrue(message.indexOf("does not match namespace URI") > -1); - query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + URI + "/test/" + FATHER_MODULE_NAME + "\";\n" + "$foo:bar, $foo:bar1, $foo:bar2"; + query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + LOCAL_URI + "/test/" + FATHER_MODULE_NAME + "\";\n" + "$foo:bar, $foo:bar1, $foo:bar2"; result = service.query(query); assertEquals("XQuery: " + query, 3, result.getSize()); assertEquals("XQuery: " + query, "bar", result.getResource(0).getContent()); @@ -1027,7 +1059,7 @@ public void module() throws XMLDBException { assertEquals("XQuery: " + query, "bar2", result.getResource(2).getContent()); // Non-transitive inheritance check - query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + URI + "/test/" + FATHER_MODULE_NAME + "\";\n" + "declare namespace foo1=\"foo1\"; \n" + "$foo1:bar"; + query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + LOCAL_URI + "/test/" + FATHER_MODULE_NAME + "\";\n" + "declare namespace foo1=\"foo1\"; \n" + "$foo1:bar"; try { message = ""; result = service.query(query); @@ -1037,7 +1069,7 @@ public void module() throws XMLDBException { assertTrue(message.indexOf("XPST0008") > -1); // Non-transitive inheritance check - query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + URI + "/test/" + FATHER_MODULE_NAME + "\";\n" + "declare namespace foo2=\"foo2\"; \n" + "$foo2:bar"; + query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + LOCAL_URI + "/test/" + FATHER_MODULE_NAME + "\";\n" + "declare namespace foo2=\"foo2\"; \n" + "$foo2:bar"; try { message = ""; result = service.query(query); @@ -1045,7 +1077,7 @@ public void module() throws XMLDBException { message = e.getMessage(); } assertTrue(message.indexOf("XPST0008") > -1); - query = "xquery version \"1.0\";\n" + "import module namespace foo1=\"foo\" at \"" + URI + "/test/" + CHILD1_MODULE_NAME + "\";\n" + "import module namespace foo2=\"foo\" at \"" + URI + "/test/" + CHILD1_MODULE_NAME + "\";\n" + "$foo1:bar"; + query = "xquery version \"1.0\";\n" + "import module namespace foo1=\"foo\" at \"" + LOCAL_URI + "/test/" + CHILD1_MODULE_NAME + "\";\n" + "import module namespace foo2=\"foo\" at \"" + LOCAL_URI + "/test/" + CHILD1_MODULE_NAME + "\";\n" + "$foo1:bar"; try { message = ""; result = service.query(query); @@ -1054,7 +1086,7 @@ public void module() throws XMLDBException { } // Should be a XQST0047 error assertTrue(message.indexOf("does not match namespace URI") > -1); - query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + URI + "/test/" + MODULE3_NAME + "\";\n" + "$bar:bar"; + query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + LOCAL_URI + "/test/" + MODULE3_NAME + "\";\n" + "$bar:bar"; try { message = ""; result = service.query(query); @@ -1062,7 +1094,7 @@ public void module() throws XMLDBException { message = e.getMessage(); } assertTrue(message.indexOf("No namespace defined for prefix") > -1); - query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + URI + "/test/" + MODULE4_NAME + "\";\n" + "foo:bar()"; + query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + LOCAL_URI + "/test/" + MODULE4_NAME + "\";\n" + "foo:bar()"; try { message = ""; result = service.query(query); @@ -1088,7 +1120,7 @@ public void modulesAndNS() throws XMLDBException, IOException, SAXException { XPathQueryService service = testCollection.getService(XPathQueryService.class); service.setProperty(OutputKeys.INDENT, "no"); String query = "xquery version \"1.0\";\n" + - "import module namespace foo=\"foo\" at \"" + URI + "/test/" + MODULE7_NAME + "\";\n" + + "import module namespace foo=\"foo\" at \"" + LOCAL_URI + "/test/" + MODULE7_NAME + "\";\n" + "
" + "{ foo:link() }" + "
"; @@ -1099,7 +1131,7 @@ public void modulesAndNS() throws XMLDBException, IOException, SAXException { result.getResource(0).getContent().toString()); query = "xquery version \"1.0\";\n" + - "import module namespace foo=\"foo\" at \"" + URI + "/test/" + MODULE7_NAME + "\";\n" + + "import module namespace foo=\"foo\" at \"" + LOCAL_URI + "/test/" + MODULE7_NAME + "\";\n" + "
"; @@ -1201,7 +1233,7 @@ public void doubleDocNode_2078755() throws XMLDBException { XPathQueryService service = testCollection.getService(XPathQueryService.class); service.setProperty(OutputKeys.INDENT, "no"); - String query = "import module namespace dr = \"double-root2\" at \"" + URI + "/test/" + MODULE8_NAME + "\";\n" + String query = "import module namespace dr = \"double-root2\" at \"" + LOCAL_URI + "/test/" + MODULE8_NAME + "\";\n" +"let $doc1 := dr:documentIn() \n" +"let $count1 := count($doc1/element()) \n" +"let $doc2 := dr:documentIn() \n" @@ -1227,7 +1259,7 @@ public void globalVars() throws XMLDBException { ((EXistResource) doc).setMimeType("application/xquery"); testCollection.storeResource(doc); XQueryService service = (XQueryService) testCollection.getService(XPathQueryService.class); - String query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + URI + "/test/" + MODULE5_NAME + "\";\n" + "$foo:bar"; + String query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + LOCAL_URI + "/test/" + MODULE5_NAME + "\";\n" + "$foo:bar"; ResourceSet result = service.query(query); assertEquals(result.getSize(), 1); assertEquals(result.getResource(0).getContent(), "bar"); @@ -1237,7 +1269,7 @@ public void globalVars() throws XMLDBException { assertEquals(result.getResource(0).getContent(), "abc"); boolean gotException = false; try { - query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + URI + "/test/" + MODULE6_NAME + "\";\n" + "$foo:bar"; + query = "xquery version \"1.0\";\n" + "import module namespace foo=\"foo\" at \"" + LOCAL_URI + "/test/" + MODULE6_NAME + "\";\n" + "$foo:bar"; result = service.query(query); } catch (XMLDBException e) { assertTrue("Test should generate err:XQST0049, got: " + e.getMessage(), e.getMessage().indexOf("err:XQST0049") > -1); @@ -1312,7 +1344,7 @@ public void functionDocExternal() throws XMLDBException { //Checking that we have an Internet Access try { - URL url = new URL("http://www.w3.org/"); + URL url = URI.create("http://www.w3.org/").toURL(); URLConnection con = url.openConnection(); if (con instanceof HttpURLConnection httpConnection) { hasInternetAccess = (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK); @@ -1640,21 +1672,21 @@ public void retrieveLargeAttribute() throws XMLDBException { @Test public void largeAttributeText() throws XMLDBException { - final String large = "challengesininformationretrievalandlanguagemodelingreportofaworkshopheldatthecenterforintelligentinformationretrievaluniversityofmassachusettsamherstseptember2002-extdocid-howardturtlemarksandersonnorbertfuhralansmeatonjayaslamdragomirradevwesselkraaijellenvoorheesamitsinghaldonnaharmanjaypontejamiecallannicholasbelkinjohnlaffertylizliddyronirosenfeldvictorlavrenkodavidjharperrichschwartzjohnpragerchengxiangzhaijinxixusalimroukosstephenrobertsonandrewmccallumbrucecroftrmanmathasuedumaisdjoerdhiemstraeduardhovyralphweischedelthomashofmannjamesallanchrisbuckleyphilipresnikdavidlewis2003"; - String xml = "
"; final String FILE_NAME = "detail_xml.xml"; XPathQueryService service = storeXMLStringAndGetQueryService(FILE_NAME, xml); - String query = "doc('" + FILE_NAME + "') / details/metadata[@docid= '" + large + "' ]"; + String query = "doc('" + FILE_NAME + "') / details/metadata[@docid= '" + largeText + "' ]"; ResourceSet result = service.queryResource(FILE_NAME, query); assertEquals(1, result.getSize()); - xml = "
" + large + + xml = "
" + largeText + "
"; service = storeXMLStringAndGetQueryService(FILE_NAME, xml); - query = "doc('"+ FILE_NAME+"') / details/metadata[ docid= '" + large + "' ]"; + query = "doc('"+ FILE_NAME+"') / details/metadata[ docid= '" + largeText + "' ]"; result = service.queryResource(FILE_NAME, query); assertEquals(1, result.getSize()); } @@ -1757,15 +1789,16 @@ public void order_1691112() throws XMLDBException { " tt:function($funcs)"; String expectedresult = - "\n" + - " Airmount 1\n" + - " \n" + - " Position\n" + - " \n" + - " \n" + - " Velocity\n" + - " \n" + - ""; + """ + + Airmount 1 + + Position + + + Velocity + + """; for (int i = 0; i < 25; i++) { // repeat a few times @@ -2341,17 +2374,19 @@ public void cardinalityAttributeNamespace_1884360() throws XMLDBException { @Test public void currentDateTimeInModules_1894009() throws XMLDBException { - String module = "module namespace dt = \"dt\";\n" + - "\n" + - "declare function dt:fib($n) {\n" + - " if ($n < 2) then $n else dt:fib($n - 1) + dt:fib($n - 2) \n" + - "};\n" + - "\n" + - "declare function dt:dateTime() {\n" + - " (: Do something time consuming first. :) \n" + - " let $a := dt:fib(25)" + - " return current-dateTime()\n" + - "};"; + String module = """ + module namespace dt = "dt"; + + declare function dt:fib($n) { + if ($n < 2) then $n else dt:fib($n - 1) + dt:fib($n - 2)\s + }; + + declare function dt:dateTime() { + (: Do something time consuming first. :) \s + let $a := dt:fib(25)\ + return current-dateTime() + };\ + """; String module_name = "dt.xqm"; Resource doc; @@ -2517,9 +2552,10 @@ public void divErrorArgVariable() throws XMLDBException { */ @Test public void divErrorArgVariable2() throws XMLDBException { - String query = "let $x := 2 \n" + - "let $y := 1 div $x * 4\n" + - "return $y"; + String query = """ + let $x := 2\s + let $y := 1 div $x * 4 + return $y"""; XPathQueryService service = getTestCollection().getService(XPathQueryService.class); ResourceSet result = service.query(query); @@ -2605,8 +2641,9 @@ public void resolveBaseURIErrorCases() throws XMLDBException { */ @Test public void xpty0018_mixedsequences_2429093() throws XMLDBException { - String query = "declare variable $a := ;\n" + - "($a/B, \"delete\") "; + String query = """ + declare variable $a := ; + ($a/B, "delete") """; XPathQueryService service = getTestCollection().getService(XPathQueryService.class); ResourceSet result = service.query(query); @@ -2620,10 +2657,11 @@ public void xpty0018_mixedsequences_2429093() throws XMLDBException { @Test public void messageDigester() throws XMLDBException { - String query = "let $value:=\"ABCDEF\"\n" + - "let $alg:=\"MD5\"\n" + - "return\n" + - "(util:hash($value, $alg), util:hash($value, $alg, xs:boolean('true')))"; + String query = """ + let $value:="ABCDEF" + let $alg:="MD5" + return + (util:hash($value, $alg), util:hash($value, $alg, xs:boolean('true')))"""; XPathQueryService service = getTestCollection().getService(XPathQueryService.class); ResourceSet result = service.query(query); @@ -2634,10 +2672,11 @@ public void messageDigester() throws XMLDBException { assertEquals(query, "iCekESKlAouYCMe/hLn89g==", result.getResource(1).getContent().toString()); - query = "let $value:=\"ABCDEF\"\n" + - "let $alg:=\"SHA-1\"\n" + - "return\n" + - "(util:hash($value, $alg), util:hash($value, $alg, xs:boolean('true')))"; + query = """ + let $value:="ABCDEF" + let $alg:="SHA-1" + return + (util:hash($value, $alg), util:hash($value, $alg, xs:boolean('true')))"""; service = getTestCollection().getService(XPathQueryService.class); result = service.query(query); @@ -2648,10 +2687,11 @@ public void messageDigester() throws XMLDBException { assertEquals(query, "lwCTZ4sYISf2C7UbivLJTVOeyjo=", result.getResource(1).getContent().toString()); - query = "let $value:=\"ABCDEF\"\n" + - "let $alg:=\"SHA-256\"\n" + - "return\n" + - "(util:hash($value, $alg), util:hash($value, $alg, xs:boolean('true')))"; + query = """ + let $value:="ABCDEF" + let $alg:="SHA-256" + return + (util:hash($value, $alg), util:hash($value, $alg, xs:boolean('true')))"""; service = getTestCollection().getService(XPathQueryService.class); result = service.query(query); @@ -2921,16 +2961,19 @@ public void attributesSerialization() throws XMLDBException { } catch (Exception e) { //SENR0001 : OK - this is expected } - query = "declare option exist:serialize 'method=text'; \n" - + "//@* \n"; + query = """ + declare option exist:serialize 'method=text';\s + //@*\s + """; result = service.query(query); assertEquals("XQuery: " + query, 3, result.getSize()); } @Test(expected=XPathException.class) public void pathOperatorContainingNodesAndNonNodes() throws XMLDBException, XPathException { - final String query = "declare function local:test() { (1,) };\n" + - "/local:test()"; + final String query = """ + declare function local:test() { (1,) }; + /local:test()"""; try { existEmbeddedServer.executeQuery(query); } catch(final XMLDBException e) { @@ -2945,8 +2988,9 @@ public void pathOperatorContainingNodesAndNonNodes() throws XMLDBException, XPat @Test public void exprContainingNodesAndNonNodes() throws XMLDBException, XPathException { - final String query = "declare function local:test() { (1,) };\n" + - "local:test()"; + final String query = """ + declare function local:test() { (1,) }; + local:test()"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); assertEquals(2, result.getSize()); @@ -2959,9 +3003,10 @@ public void exprContainingNodesAndNonNodes() throws XMLDBException, XPathExcepti */ @Test public void multipleExprsContainingNodesAndNonNodes() throws XMLDBException, XPathException { - final String query = "declare variable $a := 'a';\n" + - "declare function local:test() { (1,) };\n" + - "local:test()"; + final String query = """ + declare variable $a := 'a'; + declare function local:test() { (1,) }; + local:test()"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); assertEquals(2, result.getSize()); diff --git a/exist-core/src/test/java/org/exist/xquery/XQueryUpdateTest.java b/exist-core/src/test/java/org/exist/xquery/XQueryUpdateTest.java index 59c5da86833..97ed555b27a 100644 --- a/exist-core/src/test/java/org/exist/xquery/XQueryUpdateTest.java +++ b/exist-core/src/test/java/org/exist/xquery/XQueryUpdateTest.java @@ -66,14 +66,15 @@ public void append() throws EXistException, PermissionDeniedException, XPathExce XQuery xquery = pool.getXQueryService(); String query = - " declare variable $i external;\n" + - " update insert\n" + - " \n" + - " Description {$i}\n" + - " {$i + 1.0}\n" + - " {$i * 10}\n" + - " \n" + - " into /products"; + """ + declare variable $i external; + update insert + + Description {$i} + {$i + 1.0} + {$i * 10} + + into /products"""; XQueryContext context = new XQueryContext(pool); CompiledXQuery compiled = xquery.compile(context, query); for (int i = 0; i < ITEMS_TO_APPEND; i++) { @@ -109,10 +110,11 @@ public void appendAttributes() throws EXistException, PermissionDeniedException, XQuery xquery = pool.getXQueryService(); String query = - " declare variable $i external;\n" + - " update insert\n" + - " attribute name { concat('n', $i) }\n" + - " into //product[@num = $i]"; + """ + declare variable $i external; + update insert + attribute name { concat('n', $i) } + into //product[@num = $i]"""; XQueryContext context = new XQueryContext(pool); CompiledXQuery compiled = xquery.compile(context, query); for (int i = 0; i < ITEMS_TO_APPEND; i++) { @@ -155,13 +157,14 @@ public void insertBefore() throws EXistException, PermissionDeniedException, XPa try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { String query = - " update insert\n" + - " \n" + - " Description\n" + - " 0\n" + - " 10\n" + - " \n" + - " into /products"; + """ + update insert + + Description + 0 + 10 + + into /products"""; XQuery xquery = pool.getXQueryService(); xquery.execute(broker, query, null); @@ -170,14 +173,15 @@ public void insertBefore() throws EXistException, PermissionDeniedException, XPa assertEquals(1, seq.getItemCount()); query = - " declare variable $i external;\n" + - " update insert\n" + - " \n" + - " Description {$i}\n" + - " {$i + 1.0}\n" + - " {$i * 10}\n" + - " \n" + - " preceding /products/product[1]"; + """ + declare variable $i external; + update insert + + Description {$i} + {$i + 1.0} + {$i * 10} + + preceding /products/product[1]"""; XQueryContext context = new XQueryContext(pool); CompiledXQuery compiled = xquery.compile(context, query); for (int i = 0; i < ITEMS_TO_APPEND; i++) { @@ -209,13 +213,14 @@ public void insertAfter() throws EXistException, PermissionDeniedException, XPat try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { String query = - " update insert\n" + - " \n" + - " Description\n" + - " 0\n" + - " 10\n" + - " \n" + - " into /products"; + """ + update insert + + Description + 0 + 10 + + into /products"""; XQuery xquery = pool.getXQueryService(); xquery.execute(broker, query, null); @@ -224,14 +229,15 @@ public void insertAfter() throws EXistException, PermissionDeniedException, XPat assertEquals(1, seq.getItemCount()); query = - " declare variable $i external;\n" + - " update insert\n" + - " \n" + - " Description {$i}\n" + - " {$i + 1.0}\n" + - " {$i * 10}\n" + - " \n" + - " following /products/product[1]"; + """ + declare variable $i external; + update insert + + Description {$i} + {$i + 1.0} + {$i * 10} + + following /products/product[1]"""; XQueryContext context = new XQueryContext(pool); CompiledXQuery compiled = xquery.compile(context, query); for (int i = 0; i < ITEMS_TO_APPEND; i++) { @@ -268,10 +274,11 @@ public void update() throws EXistException, PermissionDeniedException, XPathExce XQuery xquery = pool.getXQueryService(); String query = - "declare option exist:output-size-limit '-1';\n" + - "for $prod at $i in //product return\n" + - " update value $prod/description\n" + - " with 'Updated Description ' || $i"; + """ + declare option exist:output-size-limit '-1'; + for $prod at $i in //product return + update value $prod/description + with 'Updated Description ' || $i"""; Sequence seq = xquery.execute(broker, query, null); seq = xquery.execute(broker, "count(//product[starts-with(description, 'Updated')])", null); @@ -298,10 +305,11 @@ public void update() throws EXistException, PermissionDeniedException, XPathExce assertEquals(1, seq.getItemCount()); query = - "declare option exist:output-size-limit '-1';\n" + - "for $prod in //product return\n" + - " update value $prod/stock\n" + - " with (10,1)"; + """ + declare option exist:output-size-limit '-1'; + for $prod in //product return + update value $prod/stock + with (10,1)"""; seq = xquery.execute(broker, query, null); seq = xquery.execute(broker, "//product/stock/external[. cast as xs:integer eq 1]", null); @@ -319,8 +327,10 @@ public void remove() throws EXistException, PermissionDeniedException, XPathExce XQuery xquery = pool.getXQueryService(); String query = - "for $prod in //product return\n" + - " update delete $prod\n"; + """ + for $prod in //product return + update delete $prod + """; Sequence seq = xquery.execute(broker, query, null); seq = xquery.execute(broker, "//product", null); @@ -340,16 +350,20 @@ public void rename() throws EXistException, PermissionDeniedException, XPathExce XQuery xquery = pool.getXQueryService(); String query = - "for $prod in //product return\n" + - " update rename $prod/description as 'desc'\n"; + """ + for $prod in //product return + update rename $prod/description as 'desc' + """; Sequence seq = xquery.execute(broker, query, null); seq = xquery.execute(broker, "//product/desc", null); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); query = - "for $prod in //product return\n" + - " update rename $prod/@num as 'count'\n"; + """ + for $prod in //product return + update rename $prod/@num as 'count' + """; seq = xquery.execute(broker, query, null); seq = xquery.execute(broker, "//product/@count", null); @@ -369,24 +383,30 @@ public void replace() throws EXistException, PermissionDeniedException, XPathExc XQuery xquery = pool.getXQueryService(); String query = - "for $prod in //product return\n" + - " update replace $prod/description with An updated description.\n"; + """ + for $prod in //product return + update replace $prod/description with An updated description. + """; Sequence seq = xquery.execute(broker, query, null); seq = xquery.execute(broker, "//product/desc", null); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); query = - "for $prod in //product return\n" + - " update replace $prod/@num with '1'\n"; + """ + for $prod in //product return + update replace $prod/@num with '1' + """; seq = xquery.execute(broker, query, null); seq = xquery.execute(broker, "//product/@num", null); assertEquals(seq.getItemCount(), ITEMS_TO_APPEND); query = - "for $prod in //product return\n" + - " update replace $prod/desc/text() with 'A new update'\n"; + """ + for $prod in //product return + update replace $prod/desc/text() with 'A new update' + """; seq = xquery.execute(broker, query, null); seq = xquery.execute(broker, "//product[starts-with(desc, 'A new')]", null); @@ -401,13 +421,14 @@ public void attrUpdate() throws EXistException, LockException, SAXException, Per store(broker, "test.xml", UPDATE_XML); String query = - "let $progress := /progress\n" + - "for $i in 1 to 100\n" + - "let $done := $progress/@done\n" + - "return (\n" + - " update value $done with xs:int($done + 1),\n" + - " xs:int(/progress/@done)\n" + - ")"; + """ + let $progress := /progress + for $i in 1 to 100 + let $done := $progress/@done + return ( + update value $done with xs:int($done + 1), + xs:int(/progress/@done) + )"""; XQuery xquery = pool.getXQueryService(); @SuppressWarnings("unused") Sequence result = xquery.execute(broker, query, null); @@ -421,11 +442,12 @@ public void appendCDATA() throws EXistException, PermissionDeniedException, XPat XQuery xquery = pool.getXQueryService(); String query = - " update insert\n" + - " \n" + - " ]]>\n" + - " \n" + - " into /products"; + """ + update insert + + ]]> + + into /products"""; XQueryContext context = new XQueryContext(pool); CompiledXQuery compiled = xquery.compile(context, query); for (int i = 0; i < ITEMS_TO_APPEND; i++) { diff --git a/exist-core/src/test/java/org/exist/xquery/functions/securitymanager/PermissionsFunctionChmodTest.java b/exist-core/src/test/java/org/exist/xquery/functions/securitymanager/PermissionsFunctionChmodTest.java index ad5e5ed4145..c163b407505 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/securitymanager/PermissionsFunctionChmodTest.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/securitymanager/PermissionsFunctionChmodTest.java @@ -122,7 +122,7 @@ public void changeCollectionModeAsNonOwner() throws AuthenticationException, XPa } @Test - public void changeDocumentModeAsDBA_preservesSetGid() throws AuthenticationException, EXistException, PermissionDeniedException, XPathException { ; + public void changeDocumentModeAsDBA_preservesSetGid() throws AuthenticationException, EXistException, PermissionDeniedException, XPathException { final Subject adminUser = existWebServer.getBrokerPool().getSecurityManager().authenticate(TestUtils.ADMIN_DB_USER, TestUtils.ADMIN_DB_PWD); // check the setGid bit is set before we begin @@ -274,8 +274,9 @@ public void setup() throws EXistException, PermissionDeniedException, LockExcept broker.storeDocument(transaction, USER1_DOC1, new StringInputSource(xml1), MimeType.XML_TYPE, collection); final String xquery1 = - "import module namespace sm = 'http://exist-db.org/xquery/securitymanager';\n" + - "sm:id()"; + """ + import module namespace sm = 'http://exist-db.org/xquery/securitymanager'; + sm:id()"""; broker.storeDocument(transaction, USER1_XQUERY1, new StringInputSource(xquery1.getBytes(UTF_8)), MimeType.XQUERY_TYPE, collection); PermissionFactory.chmod_str(broker, transaction, collection.getURI().append(USER1_XQUERY1), Optional.of("u+s,g+s"), Optional.empty()); diff --git a/exist-core/src/test/java/org/exist/xquery/functions/securitymanager/PermissionsFunctionChownTest.java b/exist-core/src/test/java/org/exist/xquery/functions/securitymanager/PermissionsFunctionChownTest.java index d43f27943bf..89037a74333 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/securitymanager/PermissionsFunctionChownTest.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/securitymanager/PermissionsFunctionChownTest.java @@ -1671,8 +1671,9 @@ public void setup() throws EXistException, PermissionDeniedException, LockExcept broker.storeDocument(transaction, USER1_DOC1, new StringInputSource(xml1), MimeType.XML_TYPE, collection); final String xquery1 = - "import module namespace sm = 'http://exist-db.org/xquery/securitymanager';\n" + - "sm:id()"; + """ + import module namespace sm = 'http://exist-db.org/xquery/securitymanager'; + sm:id()"""; broker.storeDocument(transaction, USER1_XQUERY1, new StringInputSource(xquery1.getBytes(UTF_8)), MimeType.XQUERY_TYPE, collection); PermissionFactory.chmod_str(broker, transaction, collection.getURI().append(USER1_XQUERY1), Optional.of("u+s,g+s"), Optional.empty()); diff --git a/exist-core/src/test/java/org/exist/xquery/functions/transform/ImportLocalStylesheetTest.java b/exist-core/src/test/java/org/exist/xquery/functions/transform/ImportLocalStylesheetTest.java index 37110357ff7..50ae804bd1d 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/transform/ImportLocalStylesheetTest.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/transform/ImportLocalStylesheetTest.java @@ -28,7 +28,6 @@ import java.net.URISyntaxException; import java.nio.file.Path; -import java.nio.file.Paths; import static com.ibm.icu.impl.Assert.fail; import static org.junit.Assert.assertEquals; @@ -53,7 +52,7 @@ private static Path getConfigFile() { final String packagePath = ImportLocalStylesheetTest.class.getPackage().getName().replace('.', separator); try { - return Paths.get(loader.getResource(packagePath + separator + "conf.xml").toURI()); + return Path.of(loader.getResource(packagePath + separator + "conf.xml").toURI()); } catch (final URISyntaxException e) { fail(e); return null; diff --git a/exist-core/src/test/java/org/exist/xquery/functions/transform/TransformTest.java b/exist-core/src/test/java/org/exist/xquery/functions/transform/TransformTest.java index 3b34abf7b6d..83ac47758ef 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/transform/TransformTest.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/transform/TransformTest.java @@ -74,59 +74,62 @@ public class TransformTest { private static final XmldbURI INPUT_LIST_XML_NAME = XmldbURI.create("inputListOps.xml"); private static final String INPUT_XML = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + + """; private static final XmldbURI DICTIONARY_XML_NAME = XmldbURI.create("listOpsErr.xml"); private static final String DICTIONARY_XML = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + + + """; private static final XmldbURI LIST_OPS_XSLT_NAME = XmldbURI.create("testListOps.xsl"); private static final String LIST_OPS_XSLT = - "\n" + - " \n" + - " \n" + - " \n" + - "\n" + - " \n" + - " \n" + - "\n" + - " \n" + - "\n" + - " \n" + - " \n" + - " \n" + - " Could not find listOpsFileUri document\n" + - " \n" + - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + + + + + + + + + + Could not find listOpsFileUri document + + + + + + + + + + + + + + + + + + """; private static final String LIST_OPS_XQUERY = "xquery version \"3.0\";\n" + @@ -148,11 +151,12 @@ public class TransformTest { private static final XmldbURI DOCUMENT_XSLT_NAME = XmldbURI.create("xsl-doc.xslt"); private static final String DOCUMENT_XSLT = - "\n" + - "\t\n" + - "\t\t\n" + - "\t\n" + - ""; + """ + + + + + """; private static final String DOCUMENT_XSLT_QUERY = "import module namespace transform=\"http://exist-db.org/xquery/transform\";\n" + @@ -170,12 +174,14 @@ public class TransformTest { ""; private static final String SIMPLE_XML_WITH_COMMENT = - "\n" + - ""; + """ + + """; private static final String SIMPLE_XML_WITH_TWO_COMMENTS = - "\n" + - ""; + """ + + """; private static final XmldbURI COUNT_DESCENDANTS_XSLT_NAME = XmldbURI.create("count-descendants.xslt"); diff --git a/exist-core/src/test/java/org/exist/xquery/functions/util/EvalTest.java b/exist-core/src/test/java/org/exist/xquery/functions/util/EvalTest.java index c739dbac4e4..24ab8e6aded 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/util/EvalTest.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/util/EvalTest.java @@ -71,9 +71,10 @@ public static void tearDown() throws Exception { @Test public void eval() throws XPathException, XMLDBException { - final String query = "let $query := 'let $a := 1 return $a'\n" + - "return\n" + - "util:eval($query)"; + final String query = """ + let $query := 'let $a := 1 return $a' + return + util:eval($query)"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); assertEquals("1", r); @@ -93,9 +94,10 @@ public void evalWithExternalVars() throws XPathException, XMLDBException { @Test public void evalwithPI() throws XPathException, XMLDBException { - final String query = "let $query := 'let $a := return count($a//processing-instruction())'\n" + - "return\n" + - "util:eval($query)"; + final String query = """ + let $query := 'let $a := return count($a//processing-instruction())' + return + util:eval($query)"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); assertEquals("1", r); @@ -103,10 +105,11 @@ public void evalwithPI() throws XPathException, XMLDBException { @Test public void evalInline() throws XPathException, XMLDBException { - final String query = "let $xml := document{}\n" + - "let $query := 'count(.//*)'\n" + - "return\n" + - "util:eval-inline($xml,$query)"; + final String query = """ + let $xml := document{} + let $query := 'count(.//*)' + return + util:eval-inline($xml,$query)"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); assertEquals("3", r); @@ -114,13 +117,14 @@ public void evalInline() throws XPathException, XMLDBException { @Test public void testEvalWithContextVariable() throws XPathException, XMLDBException { - final String query = "let $xml := \n" + - "let $context := \n" + - "{$xml}\n" + - "\n" + - "let $query := 'count($xml//*) mod 2 = 0'\n" + - "return\n" + - "util:eval-with-context($query, $context, false())"; + final String query = """ + let $xml := + let $context := + {$xml} + + let $query := 'count($xml//*) mod 2 = 0' + return + util:eval-with-context($query, $context, false())"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); assertEquals("true", r); @@ -128,13 +132,14 @@ public void testEvalWithContextVariable() throws XPathException, XMLDBException @Test public void testEvalSupplyingContext() throws XPathException, XMLDBException { - final String query = "let $xml := \n" + - "let $context := \n" + - "{$xml}\n" + - "\n" + - "let $query := 'count(.//*) mod 2 = 0'\n" + - "return\n" + - "util:eval-with-context($query, $context, false())"; + final String query = """ + let $xml := + let $context := + {$xml} + + let $query := 'count(.//*) mod 2 = 0' + return + util:eval-with-context($query, $context, false())"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); assertEquals("true", r); @@ -142,14 +147,15 @@ public void testEvalSupplyingContext() throws XPathException, XMLDBException { @Test public void testEvalSupplyingContextAndVariable() throws XPathException, XMLDBException { - final String query = "let $xml := \n" + - "let $context := \n" + - "{$xml}\n" + - "{$xml}\n" + - "\n" + - "let $query := 'count($xml//*) + count(.//*)'\n" + - "return\n" + - "util:eval-with-context($query, $context, false())"; + final String query = """ + let $xml := + let $context := + {$xml} + {$xml} + + let $query := 'count($xml//*) + count(.//*)' + return + util:eval-with-context($query, $context, false())"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); assertEquals("3", r); @@ -157,10 +163,11 @@ public void testEvalSupplyingContextAndVariable() throws XPathException, XMLDBEx @Test public void testEvalSupplyingContextItem() throws XPathException, XMLDBException { - final String query = "let $context := 'London'\n" + - "let $query := '.'\n" + - "return\n" + - "util:eval-with-context($query, (), false(), $context)"; + final String query = """ + let $context := 'London' + let $query := '.' + return + util:eval-with-context($query, (), false(), $context)"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); assertEquals("London", r); @@ -282,9 +289,10 @@ private Collection createCollection(String collectionName) throws XMLDBException @Test public void evalAndSerialize() throws XMLDBException { - final String query = "let $query := \"hello\"\n" + - "return\n" + - "util:eval-and-serialize($query, ())"; + final String query = """ + let $query := "hello" + return + util:eval-and-serialize($query, ())"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final Resource r = result.getResource(0); assertEquals("hello", r.getContent()); @@ -292,20 +300,22 @@ public void evalAndSerialize() throws XMLDBException { @Test public void evalAndSerializeDefaultOptions() throws XMLDBException { - String query = "let $query := \"hello\"\n" + - "return\n" + - "util:eval-and-serialize($query, map { \"method\": \"adaptive\" })"; + String query = """ + let $query := "hello" + return + util:eval-and-serialize($query, map { "method": "adaptive" })"""; ResourceSet result = existEmbeddedServer.executeQuery(query); Resource r = result.getResource(0); assertEquals("hello", r.getContent()); // test that XQuery Prolog output options override the default provided options - query = "xquery version \"3.1\";\n" + - "declare namespace output = \"http://www.w3.org/2010/xslt-xquery-serialization\";\n" + - "declare option output:method \"text\";\n" + - "let $query := \"hello\"\n" + - "return\n" + - "util:eval-and-serialize($query, map { \"method\": \"adaptive\" })"; + query = """ + xquery version "3.1"; + declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization"; + declare option output:method "text"; + let $query := "hello" + return + util:eval-and-serialize($query, map { "method": "adaptive" })"""; result = existEmbeddedServer.executeQuery(query); r = result.getResource(0); assertEquals("hello", r.getContent()); @@ -313,9 +323,10 @@ public void evalAndSerializeDefaultOptions() throws XMLDBException { @Test public void evalAndSerializeJson() throws XMLDBException { - String query = "let $query := \"hello\"\n" + - "return\n" + - "util:eval-and-serialize($query, map { \"method\": \"json\" })"; + String query = """ + let $query := "hello" + return + util:eval-and-serialize($query, map { "method": "json" })"""; ResourceSet result = existEmbeddedServer.executeQuery(query); Resource r = result.getResource(0); assertEquals("{\"elem1\":\"hello\"}", r.getContent()); @@ -323,9 +334,10 @@ public void evalAndSerializeJson() throws XMLDBException { @Test public void evalAndSerializeAdaptive() throws XMLDBException { - String query = "let $query := 'map { \"key\": \"value\"}'\n" + - "return\n" + - "util:eval-and-serialize($query, map { \"method\": \"adaptive\" })"; + String query = """ + let $query := 'map { "key": "value"}' + return + util:eval-and-serialize($query, map { "method": "adaptive" })"""; ResourceSet result = existEmbeddedServer.executeQuery(query); Resource r = result.getResource(0); assertEquals("map{\"key\":\"value\"}", r.getContent()); @@ -333,9 +345,10 @@ public void evalAndSerializeAdaptive() throws XMLDBException { @Test public void evalAndSerializeSubsequence() throws XMLDBException { - final String query = "let $query := \"for $i in (1 to 10) return {$i}\"\n" + - "return\n" + - "util:eval-and-serialize($query, (), 1, 4)"; + final String query = """ + let $query := "for $i in (1 to 10) return {$i}" + return + util:eval-and-serialize($query, (), 1, 4)"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final Resource r = result.getResource(0); assertEquals("1234", r.getContent()); @@ -343,12 +356,13 @@ public void evalAndSerializeSubsequence() throws XMLDBException { @Test public void evalErrorInfo() { - final String query = "let $query := \"let $msg := 'some error message'\n" + - "let $code := xs:QName('some-error')\n" + - "return\n" + - " fn:error($code, $msg)\"\n" + - "return\n" + - " util:eval($query, false(), (), false())"; + final String query = """ + let $query := "let $msg := 'some error message' + let $code := xs:QName('some-error') + return + fn:error($code, $msg)" + return + util:eval($query, false(), (), false())"""; try { existEmbeddedServer.executeQuery(query); @@ -362,12 +376,13 @@ public void evalErrorInfo() { @Test public void evalPassErrorInfo() { - final String query = "let $query := \"let $msg := 'some error message'\n" + - "let $code := xs:QName('some-error')\n" + - "return\n" + - " fn:error($code, $msg)\"\n" + - "return\n" + - " util:eval($query, false(), (), true())"; + final String query = """ + let $query := "let $msg := 'some error message' + let $code := xs:QName('some-error') + return + fn:error($code, $msg)" + return + util:eval($query, false(), (), true())"""; try { existEmbeddedServer.executeQuery(query); @@ -392,4 +407,4 @@ private ResourceSet executeModule(final Collection collection, final String modu final XmldbURI moduleUri = ((EXistCollection)collection).getPathURI().append(moduleName); return service.executeStoredQuery(moduleUri.toString()); } -} \ No newline at end of file +} diff --git a/exist-core/src/test/java/org/exist/xquery/functions/util/ExpandTest.java b/exist-core/src/test/java/org/exist/xquery/functions/util/ExpandTest.java index ba065132db6..d5dd91a4cab 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/util/ExpandTest.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/util/ExpandTest.java @@ -60,24 +60,24 @@ public static void setup() throws XMLDBException { public void expandWithDefaultNS() throws XMLDBException { final String expected = "\n \n"; - String query = "" + - "let $doc-path := xmldb:store('/db', 'test.xml', )\n" + - "let $doc := doc($doc-path)\n" + - "return\n" + - "\n" + - "{util:expand($doc)}\n" + - ""; + String query = """ + let $doc-path := xmldb:store('/db', 'test.xml', ) + let $doc := doc($doc-path) + return + + {util:expand($doc)} + """; ResourceSet result = existEmbeddedServer.executeQuery(query); String r = (String) result.getResource(0).getContent(); assertEquals(expected, r); - query = "" + - "let $doc-path := xmldb:store('/db', 'test.xml', )\n" + - "let $doc := doc($doc-path)\n" + - "return\n" + - "\n" + - "{$doc}\n" + - ""; + query = """ + let $doc-path := xmldb:store('/db', 'test.xml', ) + let $doc := doc($doc-path) + return + + {$doc} + """; result = existEmbeddedServer.executeQuery(query); r = (String) result.getResource(0).getContent(); assertEquals(expected, r); @@ -115,8 +115,9 @@ public void expandPersistentDomAttr() throws XMLDBException { @Test public void expandPersistentDomAttrNs() throws XMLDBException { - final String query = "declare namespace x = \"http://x\";\n" + - "util:expand(doc('/db/expand-test/doc4.xml')/doc4/@x:foo)"; + final String query = """ + declare namespace x = "http://x"; + util:expand(doc('/db/expand-test/doc4.xml')/doc4/@x:foo)"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final Resource res = result.getResource(0); assertEquals(XML_RESOURCE, res.getResourceType()); diff --git a/exist-core/src/test/java/org/exist/xquery/functions/validate/AdditionalJingXsdRngTest.java b/exist-core/src/test/java/org/exist/xquery/functions/validate/AdditionalJingXsdRngTest.java index 01c65e8db32..6fc518f6da8 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/validate/AdditionalJingXsdRngTest.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/validate/AdditionalJingXsdRngTest.java @@ -43,26 +43,27 @@ public class AdditionalJingXsdRngTest { @Test public void testValidateXSDwithJing() throws XMLDBException { - final String query = "let $v := \n" + - "\tTitle\n" + - "\t

Some paragraph.

\n" + - "
\n" + - "let $schema := \n" + - "\t\n" + - "\t \n" + - "\t \n" + - "\t \n" + - "\t \n" + - "\t \n" + - "\t \n" + - "\t\n" + - "\t\n" + - "\t\n" + - " \n" + - "return\n" + - "\n" + - "\tvalidation:jing($v,$schema)"; + final String query = """ + let $v := + Title +

Some paragraph.

+
+ let $schema := + + + + + + + + + + + + return + + validation:jing($v,$schema)"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); @@ -71,26 +72,27 @@ public void testValidateXSDwithJing() throws XMLDBException { @Test public void testValidateXSDwithJing_invalid() throws XMLDBException { - final String query = "let $v := \n" + - "\tTitle\n" + - "\t

Some paragraph.

\n" + - "
\n" + - "let $schema := \n" + - "\t\n" + - "\t \n" + - "\t \n" + - "\t \n" + - "\t \n" + - "\t \n" + - "\t \n" + - "\t\n" + - "\t\n" + - "\t\n" + - " \n" + - "return\n" + - "\n" + - "\tvalidation:jing($v,$schema)"; + final String query = """ + let $v := + Title +

Some paragraph.

+
+ let $schema := + + + + + + + + + + + + return + + validation:jing($v,$schema)"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); @@ -99,38 +101,39 @@ public void testValidateXSDwithJing_invalid() throws XMLDBException { @Test public void testValidateRNGwithJing() throws XPathException, XMLDBException { - final String query = "let $v := \n" + - "\tTitle\n" + - "\t

Some paragraph.

\n" + - "
\n" + - "let $schema := \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n" + - "return\n" + - "\n" + - "\tvalidation:jing($v,$schema)"; + final String query = """ + let $v := + Title +

Some paragraph.

+
+ let $schema := + + + + + + + + + + + + + + + + + + + + + + + + + return + + validation:jing($v,$schema)"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); @@ -139,38 +142,39 @@ public void testValidateRNGwithJing() throws XPathException, XMLDBException { @Test public void testValidateRNGwithJing_invalid() throws XMLDBException { - final String query = "let $v := \n" + - "\tTitle\n" + - "\t

Some paragraph.

\n" + - "
\n" + - "let $schema := \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - "\n" + - "return\n" + - "\n" + - "\tvalidation:jing($v,$schema)"; + final String query = """ + let $v := + Title +

Some paragraph.

+
+ let $schema := + + + + + + + + + + + + + + + + + + + + + + + + + return + + validation:jing($v,$schema)"""; final ResourceSet result = existEmbeddedServer.executeQuery(query); final String r = (String) result.getResource(0).getContent(); diff --git a/exist-core/src/test/java/org/exist/xquery/functions/validate/JaxpParseTest.java b/exist-core/src/test/java/org/exist/xquery/functions/validate/JaxpParseTest.java index 6d65aad158f..d1d95001c38 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/validate/JaxpParseTest.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/validate/JaxpParseTest.java @@ -92,10 +92,11 @@ public void parse_and_fill_defaults() throws XMLDBException, IOException, SAXExc "validation:jaxp-parse(xs:anyURI('/db/parse_validate/defaultValue.xml'), true(), ())"; result = execute(query); - String expected = "\n" + - " red\n" + - " 43\n" + - ""; + String expected = """ + + red + 43 + """; XMLAssert.assertXMLEqual(expected, result); } diff --git a/exist-core/src/test/java/org/exist/xquery/functions/xmldb/DbStore2Test.java b/exist-core/src/test/java/org/exist/xquery/functions/xmldb/DbStore2Test.java index aadd2c01baf..7f10fbb9750 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/xmldb/DbStore2Test.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/xmldb/DbStore2Test.java @@ -41,7 +41,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Random; import static org.junit.Assert.assertNotNull; @@ -71,7 +70,7 @@ public class DbStore2Test { private final static Path getConfig() { try { final URL path = DbStoreTest.class.getClassLoader().getResource("org/exist/xmldb/allowAnyUri.xml"); - return Paths.get(path.toURI()); + return Path.of(path.toURI()); } catch (URISyntaxException e) { throw new RuntimeException("unable to parse URI for resource", e); } @@ -160,4 +159,4 @@ public final void testLargeFileStore() throws XMLDBException, IOException { " )"); assertNotNull(rs); } -} \ No newline at end of file +} diff --git a/exist-core/src/test/java/org/exist/xquery/functions/xmldb/DbStoreTest.java b/exist-core/src/test/java/org/exist/xquery/functions/xmldb/DbStoreTest.java index c7b2914861d..cbf59213b9e 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/xmldb/DbStoreTest.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/xmldb/DbStoreTest.java @@ -53,12 +53,13 @@ public final void simpleTest() throws XMLDBException { final XPathQueryService xpqs = testCol.getService(XPathQueryService.class); assertThrows(XMLDBException.class, () -> xpqs.query( - "xmldb:store(\n" + - " '/db',\n" + - " 'image.jpg',\n" + - " xs:anyURI('https://www.example.com/image.jpg'),\n" + - " 'image/png'\n" + - " )")); + """ + xmldb:store( + '/db', + 'image.jpg', + xs:anyURI('https://www.example.com/image.jpg'), + 'image/png' + )""")); } diff --git a/exist-core/src/test/java/org/exist/xquery/functions/xmldb/XMLDBAuthenticateTest.java b/exist-core/src/test/java/org/exist/xquery/functions/xmldb/XMLDBAuthenticateTest.java index c8883cc1d33..74c0f86c1c5 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/xmldb/XMLDBAuthenticateTest.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/xmldb/XMLDBAuthenticateTest.java @@ -103,14 +103,15 @@ public void loginExplicitSessionCreation() throws IOException { assertEquals(HttpStatus.SC_OK, setResponse1.getStatusLine().getStatusCode()); final Source expected = Input.fromString( - "\n" + - " \n" + - " user1\n" + - " \n" + - " user1\n" + - " \n" + - " \n" + - "").build(); + """ + + + user1 + + user1 + + + """).build(); final Source actual = Input.fromString(readEntityAsString(setResponse1.getEntity())).build(); final Diff diff = DiffBuilder.compare(expected) .withTest(actual) @@ -137,14 +138,15 @@ public void loginImplicitSessionCreateSessionFalse() throws IOException { assertEquals(HttpStatus.SC_OK, setResponse1.getStatusLine().getStatusCode()); final Source expected = Input.fromString( - "\n" + - " \n" + - " guest\n" + - " \n" + - " guest\n" + - " \n" + - " \n" + - "").build(); + """ + + + guest + + guest + + + """).build(); final Source actual = Input.fromString(readEntityAsString(setResponse1.getEntity())).build(); final Diff diff = DiffBuilder.compare(expected) .withTest(actual) @@ -171,14 +173,15 @@ public void loginImplicitSessionCreateSessionTrue() throws IOException { assertEquals(HttpStatus.SC_OK, setResponse1.getStatusLine().getStatusCode()); final Source expected = Input.fromString( - "\n" + - " \n" + - " user1\n" + - " \n" + - " user1\n" + - " \n" + - " \n" + - "").build(); + """ + + + user1 + + user1 + + + """).build(); final Source actual = Input.fromString(readEntityAsString(setResponse1.getEntity())).build(); final Diff diff = DiffBuilder.compare(expected) .withTest(actual) @@ -221,14 +224,15 @@ public void loginOnInvalidatedSessionCreateSessionFalseSeparateHttpCalls() throw assertEquals(HttpStatus.SC_OK, setResponse1.getStatusLine().getStatusCode()); final Source expected = Input.fromString( - "\n" + - " \n" + - " guest\n" + - " \n" + - " guest\n" + - " \n" + - " \n" + - "").build(); + """ + + + guest + + guest + + + """).build(); final Source actual = Input.fromString(readEntityAsString(setResponse1.getEntity())).build(); final Diff diff = DiffBuilder.compare(expected) .withTest(actual) @@ -271,14 +275,15 @@ public void loginOnInvalidatedSessionCreateSessionTrueSeparateHttpCalls() throws assertEquals(HttpStatus.SC_OK, setResponse1.getStatusLine().getStatusCode()); final Source expected = Input.fromString( - "\n" + - " \n" + - " user1\n" + - " \n" + - " user1\n" + - " \n" + - " \n" + - "").build(); + """ + + + user1 + + user1 + + + """).build(); final Source actual = Input.fromString(readEntityAsString(setResponse1.getEntity())).build(); final Diff diff = DiffBuilder.compare(expected) .withTest(actual) @@ -314,14 +319,15 @@ public void loginOnInvalidatedSessionCreateSessionFalseSameHttpCall() throws IOE assertEquals(HttpStatus.SC_OK, setResponse1.getStatusLine().getStatusCode()); final Source expected = Input.fromString( - "\n" + - " \n" + - " guest\n" + - " \n" + - " guest\n" + - " \n" + - " \n" + - "").build(); + """ + + + guest + + guest + + + """).build(); final Source actual = Input.fromString(readEntityAsString(setResponse1.getEntity())).build(); final Diff diff = DiffBuilder.compare(expected) .withTest(actual) @@ -357,14 +363,15 @@ public void loginOnInvalidatedSessionCreateSessionTrueSameHttpCall() throws IOEx assertEquals(HttpStatus.SC_OK, setResponse1.getStatusLine().getStatusCode()); final Source expected = Input.fromString( - "\n" + - " \n" + - " user1\n" + - " \n" + - " user1\n" + - " \n" + - " \n" + - "").build(); + """ + + + user1 + + user1 + + + """).build(); final Source actual = Input.fromString(readEntityAsString(setResponse1.getEntity())).build(); final Diff diff = DiffBuilder.compare(expected) .withTest(actual) diff --git a/exist-core/src/test/java/org/exist/xquery/functions/xquery3/DeclareVariableTest.java b/exist-core/src/test/java/org/exist/xquery/functions/xquery3/DeclareVariableTest.java index e2385d96002..7b0ce2333dc 100644 --- a/exist-core/src/test/java/org/exist/xquery/functions/xquery3/DeclareVariableTest.java +++ b/exist-core/src/test/java/org/exist/xquery/functions/xquery3/DeclareVariableTest.java @@ -36,14 +36,15 @@ public class DeclareVariableTest { @Test public void defaultNamespaceTest() throws XMLDBException { - final String query = "xquery version \"3.1\";\n" - + "\n" - + " declare default element namespace \"http://www.w3.org/1999/xhtml\";\n" - + "\n" - + " declare variable $docName := 'test.xml';\n" - + " declare variable $docPath := concat('/db/', $docName);\n" - + "\n" - + " $docPath"; + final String query = """ + xquery version "3.1"; + + declare default element namespace "http://www.w3.org/1999/xhtml"; + + declare variable $docName := 'test.xml'; + declare variable $docPath := concat('/db/', $docName); + + $docPath"""; final ResourceSet results = existEmbeddedServer.executeQuery(query); final String r = (String) results.getResource(0).getContent(); diff --git a/exist-core/src/test/java/org/exist/xquery/value/Base64BinaryValueTypeTest.java b/exist-core/src/test/java/org/exist/xquery/value/Base64BinaryValueTypeTest.java index 97ec6ab9c5f..d16bb77582e 100644 --- a/exist-core/src/test/java/org/exist/xquery/value/Base64BinaryValueTypeTest.java +++ b/exist-core/src/test/java/org/exist/xquery/value/Base64BinaryValueTypeTest.java @@ -26,7 +26,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import org.apache.commons.codec.binary.Base64InputStream; @@ -76,7 +75,7 @@ public void verify_validBase64_passes_3() throws XPathException { @Test public void verify_validBase64_passes_large_string() throws XPathException, IOException, URISyntaxException { Optional home = ConfigurationHelper.getExistHome(); - Path binaryFile = Paths.get(getClass().getResource("logo.jpg").toURI()); + Path binaryFile = Path.of(getClass().getResource("logo.jpg").toURI()); final String base64data; try(final InputStream is = new Base64InputStream(Files.newInputStream(binaryFile), true, -1, null); @@ -103,4 +102,4 @@ protected String formatString(String str) { return super.formatString(str); } } -} \ No newline at end of file +} diff --git a/exist-core/src/test/java/org/exist/xupdate/XUpdateTest.java b/exist-core/src/test/java/org/exist/xupdate/XUpdateTest.java index c4cc650e450..2686ea4eaed 100644 --- a/exist-core/src/test/java/org/exist/xupdate/XUpdateTest.java +++ b/exist-core/src/test/java/org/exist/xupdate/XUpdateTest.java @@ -26,7 +26,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Arrays; import javax.xml.parsers.ParserConfigurationException; @@ -160,7 +159,7 @@ private Path getRelFile(final String relPath) throws IOException, URISyntaxExcep throw new IOException("Can't find file: " + relPath); } - final Path f = Paths.get(url.toURI()); + final Path f = Path.of(url.toURI()); if (!Files.isReadable(f)) { throw new IOException("Can't read file: " + url); } diff --git a/exist-samples/pom.xml b/exist-samples/pom.xml index 2705d0ce6b2..ca7c1188490 100644 --- a/exist-samples/pom.xml +++ b/exist-samples/pom.xml @@ -50,6 +50,12 @@ com.google.code.findbugs jsr305 + + jakarta.annotation + jakarta.annotation-api + 1.3.5 + provided + diff --git a/exist-start/src/main/java/org/exist/start/CompatibleJavaVersionCheck.java b/exist-start/src/main/java/org/exist/start/CompatibleJavaVersionCheck.java index 0ce69e6eba0..e36d1dc5b57 100644 --- a/exist-start/src/main/java/org/exist/start/CompatibleJavaVersionCheck.java +++ b/exist-start/src/main/java/org/exist/start/CompatibleJavaVersionCheck.java @@ -113,7 +113,7 @@ static void checkForCompatibleJavaVersion(final Optional checkJavaVersio // version is NOT compatible! throw new StartException(ERROR_CODE_INCOMPATIBLE_JAVA_DETECTED, - String.format(INCOMPATIBLE_JAVA_VERSION_NOTICE, RUNTIME_JAVA_VERSION.orElse("UKNOWN"))); + INCOMPATIBLE_JAVA_VERSION_NOTICE.formatted(RUNTIME_JAVA_VERSION.orElse("UKNOWN"))); } // version is compatible diff --git a/exist-start/src/main/java/org/exist/start/Main.java b/exist-start/src/main/java/org/exist/start/Main.java index 4008856a6e5..979ab5e5053 100644 --- a/exist-start/src/main/java/org/exist/start/Main.java +++ b/exist-start/src/main/java/org/exist/start/Main.java @@ -29,7 +29,6 @@ import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; /** @@ -118,7 +117,7 @@ public static Main getMain() { private static void setupLog4j2(final Optional existHomeDir) { // Get path from system property - Optional log4jConfigurationFile = Optional.ofNullable(System.getProperty(PROP_LOG4J_CONFIGURATION_FILE)).map(Paths::get); + Optional log4jConfigurationFile = Optional.ofNullable(System.getProperty(PROP_LOG4J_CONFIGURATION_FILE)).map(Path::of); // Try to find configuration file is not already found. if (log4jConfigurationFile.isEmpty()) { @@ -188,7 +187,7 @@ public void startExistdb(String[] args) throws StartException { args = stripFirstElement(args); // try and figure out exist home dir - final Optional existHomeDir = getFromSysPropOrEnv(PROP_EXIST_HOME, ENV_EXIST_HOME).map(Paths::get); + final Optional existHomeDir = getFromSysPropOrEnv(PROP_EXIST_HOME, ENV_EXIST_HOME).map(Path::of); // try to find Jetty if (MODE_JETTY.equals(getMode()) || MODE_STANDALONE.equals(getMode())) { @@ -322,7 +321,7 @@ private String getClassName(final String[] args) { */ private void tweakTempDirectory() { try { - final Path tmpdir = Paths.get(System.getProperty(PROP_JAVA_TEMP_DIR)).toAbsolutePath(); + final Path tmpdir = Path.of(System.getProperty(PROP_JAVA_TEMP_DIR)).toAbsolutePath(); if (Files.isDirectory(tmpdir)) { System.setProperty(PROP_JAVA_TEMP_DIR, tmpdir.toString()); } @@ -353,7 +352,7 @@ private void tweakTempDirectory() { private Path configureForJetty(final Optional existHomeDir) throws StartException { // Get configured path for Jetty config file - Optional existJettyConfigFile = getFromSysPropOrEnv(PROP_EXIST_JETTY_CONFIG, ENV_EXIST_JETTY_CONFIG).map(Paths::get); + Optional existJettyConfigFile = getFromSysPropOrEnv(PROP_EXIST_JETTY_CONFIG, ENV_EXIST_JETTY_CONFIG).map(Path::of); // If configuration was not found if (existJettyConfigFile.isEmpty()) { @@ -364,7 +363,7 @@ private Path configureForJetty(final Optional existHomeDir) throws StartEx : STANDALONE_ENABLED_JETTY_CONFIGS; // Get path for jetty homedir - final Optional jettyHomeDir = getFromSysPropOrEnv(PROP_JETTY_HOME, ENV_JETTY_HOME).map(Paths::get); + final Optional jettyHomeDir = getFromSysPropOrEnv(PROP_JETTY_HOME, ENV_JETTY_HOME).map(Path::of); // Load configuration from Jetty directory if (jettyHomeDir.isPresent() && Files.exists(jettyHomeDir.get().resolve(CONFIG_DIR_NAME))) { diff --git a/exist-start/src/main/java/org/exist/start/classloader/Classpath.java b/exist-start/src/main/java/org/exist/start/classloader/Classpath.java index bd3444f99bc..ab981b9bc31 100644 --- a/exist-start/src/main/java/org/exist/start/classloader/Classpath.java +++ b/exist-start/src/main/java/org/exist/start/classloader/Classpath.java @@ -44,7 +44,6 @@ import java.nio.file.Files; import java.nio.file.InvalidPathException; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import java.util.function.Supplier; @@ -80,7 +79,7 @@ private static Optional or(final Optional left, final Supplierempty(); } }) - .filter(Optional::isPresent) - .map(Optional::get) + .flatMap(Optional::stream) .toArray(URL[]::new); // try and ensure we have a classloader diff --git a/extensions/contentextraction/src/test/java/org/exist/contentextraction/xquery/ContentFunctionsTest.java b/extensions/contentextraction/src/test/java/org/exist/contentextraction/xquery/ContentFunctionsTest.java index 7763512e077..47acd09da0b 100644 --- a/extensions/contentextraction/src/test/java/org/exist/contentextraction/xquery/ContentFunctionsTest.java +++ b/extensions/contentextraction/src/test/java/org/exist/contentextraction/xquery/ContentFunctionsTest.java @@ -96,12 +96,13 @@ public static void teardown() throws EXistException, PermissionDeniedException, @Test public void getMetadataFromPdf() throws EXistException, XPathException, PermissionDeniedException, IOException { final String mainQuery = - "declare namespace html = \"http://www.w3.org/1999/xhtml\";\n" + - "declare namespace contentextraction = \"http://exist-db.org/xquery/contentextraction\";\n" + - "declare namespace util = \"http://exist-db.org/xquery/util\";\n" + - "let $bin := util:binary-doc(\"/db/content-functions-test/minimal.pdf\")\n" + - " return\n" + - " contentextraction:get-metadata($bin)//html:meta[@name = (\"xmpTPg:NPages\", \"Content-Type\")]/@content"; + """ + declare namespace html = "http://www.w3.org/1999/xhtml"; + declare namespace contentextraction = "http://exist-db.org/xquery/contentextraction"; + declare namespace util = "http://exist-db.org/xquery/util"; + let $bin := util:binary-doc("/db/content-functions-test/minimal.pdf") + return + contentextraction:get-metadata($bin)//html:meta[@name = ("xmpTPg:NPages", "Content-Type")]/@content"""; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source mainQuerySource = new StringSource(mainQuery); @@ -125,12 +126,13 @@ public void getMetadataFromPdf() throws EXistException, XPathException, Permissi @Test public void getMetadataAndContentFromPdf() throws EXistException, XPathException, PermissionDeniedException, IOException { final String mainQuery = - "declare namespace html = \"http://www.w3.org/1999/xhtml\";\n" + - "declare namespace contentextraction = \"http://exist-db.org/xquery/contentextraction\";\n" + - "declare namespace util = \"http://exist-db.org/xquery/util\";\n" + - "let $bin := util:binary-doc(\"/db/content-functions-test/minimal.pdf\")\n" + - " return\n" + - " contentextraction:get-metadata-and-content($bin)//html:p[2]/string()"; + """ + declare namespace html = "http://www.w3.org/1999/xhtml"; + declare namespace contentextraction = "http://exist-db.org/xquery/contentextraction"; + declare namespace util = "http://exist-db.org/xquery/util"; + let $bin := util:binary-doc("/db/content-functions-test/minimal.pdf") + return + contentextraction:get-metadata-and-content($bin)//html:p[2]/string()"""; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source mainQuerySource = new StringSource(mainQuery); @@ -154,12 +156,13 @@ public void getMetadataAndContentFromPdf() throws EXistException, XPathException @Test public void getMetadataFromXlsx() throws EXistException, XPathException, PermissionDeniedException, IOException { final String mainQuery = - "declare namespace html = \"http://www.w3.org/1999/xhtml\";\n" + - "declare namespace contentextraction = \"http://exist-db.org/xquery/contentextraction\";\n" + - "declare namespace util = \"http://exist-db.org/xquery/util\";\n" + - "let $bin := util:binary-doc(\"/db/content-functions-test/test.xlsx\")\n" + - " return\n" + - " contentextraction:get-metadata($bin)//html:meta[@name = (\"xmpTPg:NPages\", \"Content-Type\")]/@content"; + """ + declare namespace html = "http://www.w3.org/1999/xhtml"; + declare namespace contentextraction = "http://exist-db.org/xquery/contentextraction"; + declare namespace util = "http://exist-db.org/xquery/util"; + let $bin := util:binary-doc("/db/content-functions-test/test.xlsx") + return + contentextraction:get-metadata($bin)//html:meta[@name = ("xmpTPg:NPages", "Content-Type")]/@content"""; final BrokerPool pool = existEmbeddedServer.getBrokerPool(); final Source mainQuerySource = new StringSource(mainQuery); diff --git a/extensions/expath/src/test/java/org/expath/exist/HttpClientTest.java b/extensions/expath/src/test/java/org/expath/exist/HttpClientTest.java index 2ff3ff03d83..7eecd44bad6 100644 --- a/extensions/expath/src/test/java/org/expath/exist/HttpClientTest.java +++ b/extensions/expath/src/test/java/org/expath/exist/HttpClientTest.java @@ -33,10 +33,7 @@ import org.junit.Test; import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; +import java.net.*; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -52,15 +49,16 @@ public void readResponse() throws XPathException, PermissionDeniedException, EXi assumeTrue("No Internet access: skipping 'readResponse' test", hasInternetAccess()); final String query = - "xquery version \"3.1\";\n" + - "import module namespace http=\"http://expath.org/ns/http-client\";\n" + - "let $url := \"http://www.exist-db.org/exist/apps/homepage/resources/img/existdb.gif\"\n" + - "let $request :=\n" + - " \n" + - "let $response := http:send-request($request)\n" + - "let $str := util:binary-to-string($response[2])\n" + - "return\n" + - " $str"; + """ + xquery version "3.1"; + import module namespace http="http://expath.org/ns/http-client"; + let $url := "http://www.exist-db.org/exist/apps/homepage/resources/img/existdb.gif" + let $request := + + let $response := http:send-request($request) + let $str := util:binary-to-string($response[2]) + return + $str"""; final Sequence result = executeQuery(query); assertEquals(1, result.getItemCount()); @@ -79,7 +77,7 @@ private boolean hasInternetAccess() { //Checking that we have an Internet Access try { - final URL url = new URL("http://www.exist-db.org"); + final URL url = URI.create("http://www.exist-db.org").toURL(); final URLConnection con = url.openConnection(); if (con instanceof HttpURLConnection httpConnection) { hasInternetAccess = (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK); diff --git a/extensions/exquery/modules/request/src/main/java/org/exist/extensions/exquery/modules/request/ParameterFunctions.java b/extensions/exquery/modules/request/src/main/java/org/exist/extensions/exquery/modules/request/ParameterFunctions.java index 64d6986ae14..c74ed961482 100644 --- a/extensions/exquery/modules/request/src/main/java/org/exist/extensions/exquery/modules/request/ParameterFunctions.java +++ b/extensions/exquery/modules/request/src/main/java/org/exist/extensions/exquery/modules/request/ParameterFunctions.java @@ -116,8 +116,8 @@ private Sequence getParameter(final HttpRequest request, final String paramName, result = Objects.requireNonNullElse(defaultValues, Sequence.EMPTY_SEQUENCE); } else { result = new ValueSequence(); - if(queryParamValues instanceof List) { - for(final Object value : (List)queryParamValues) { + if(queryParamValues instanceof List list) { + for(final Object value : list) { result.add(new StringValue(this, value.toString())); } } else { diff --git a/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/ExistXqueryRegistry.java b/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/ExistXqueryRegistry.java index 29494f666e1..48d57eac17a 100644 --- a/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/ExistXqueryRegistry.java +++ b/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/ExistXqueryRegistry.java @@ -383,19 +383,19 @@ private MissingModuleHint extractMissingModuleHint(final RestXqServiceCompilatio if(errorVals != null && errorVals.getItemCount() > 0){ final Item errorVal1 = errorVals.itemAt(0); - if(errorVal1 instanceof StringValue) { + if(errorVal1 instanceof StringValue value) { missingModuleHint = new MissingModuleHint(); - missingModuleHint.moduleHint = ((StringValue)errorVal1).getStringValue(); + missingModuleHint.moduleHint = value.getStringValue(); } if(errorVals.getItemCount() == 2) { final Item errorVal2 = errorVals.itemAt(1); - if(errorVal2 instanceof StringValue) { + if(errorVal2 instanceof StringValue value) { if(missingModuleHint == null) { missingModuleHint = new MissingModuleHint(); } - final String dependantModuleUri = ((StringValue)errorVal2).getStringValue(); + final String dependantModuleUri = value.getStringValue(); //path will be of xmldb:exist:///db/a/c/1.xqm form so change it to /db/a/c/1.xqm form missingModuleHint.dependantModule = makeDbAbsolutePath(dependantModuleUri); diff --git a/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/ResourceFunctionExecutorImpl.java b/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/ResourceFunctionExecutorImpl.java index d30ebd00814..61b88a2a22d 100644 --- a/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/ResourceFunctionExecutorImpl.java +++ b/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/ResourceFunctionExecutorImpl.java @@ -334,12 +334,10 @@ private TypedValue convertToType(final XQueryContext xqueryContext, final //EXQuery XDM should not have any concrete types, just interfaces //some of the abstract code in EXQuery needs to be able to instantiate types. //Consider a factory or java.util.ServiceLoader pattern - if(typedValue instanceof org.exquery.xdm.type.StringTypedValue) { - value = new StringValue(((org.exquery.xdm.type.StringTypedValue)typedValue).getValue()); - } else if(typedValue instanceof org.exquery.xdm.type.Base64BinaryTypedValue) { - value = BinaryValueFromInputStream.getInstance(xqueryContext, new Base64BinaryValueType(), ((org.exquery.xdm.type.Base64BinaryTypedValue)typedValue).getValue(), null); - } else { - value = (Item)typedValue.getValue(); + switch (typedValue) { + case org.exquery.xdm.type.StringTypedValue stringTypedValue -> value = new StringValue(stringTypedValue.getValue()); + case org.exquery.xdm.type.Base64BinaryTypedValue binaryTypedValue -> value = BinaryValueFromInputStream.getInstance(xqueryContext, new Base64BinaryValueType(), binaryTypedValue.getValue(), null); + default -> value = (Item)typedValue.getValue(); } if(existDestinationType == value.getType()) { @@ -429,4 +427,4 @@ public void analyze(final AnalyzeContextInfo contextInfo) throws XPathException public void dump(final ExpressionDumper dumper) { } } -} \ No newline at end of file +} diff --git a/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/RestXqServiceRegistryPersistence.java b/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/RestXqServiceRegistryPersistence.java index fbcdbd57c52..482c421123c 100644 --- a/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/RestXqServiceRegistryPersistence.java +++ b/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/RestXqServiceRegistryPersistence.java @@ -142,7 +142,7 @@ private synchronized void updateRegistryOnDisk(final RestXqService restXqService final Optional optTmpNewRegistry = getRegistryFile(true); - if(!optTmpNewRegistry.isPresent()) { + if(optTmpNewRegistry.isEmpty()) { log.error("Could not save RESTXQ Registry to disk!"); } else { final Path tmpNewRegistry = optTmpNewRegistry.get(); @@ -227,4 +227,4 @@ private Optional getRegistryFile(final boolean temp) { return Optional.empty(); } } -} \ No newline at end of file +} diff --git a/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/XQueryCompiler.java b/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/XQueryCompiler.java index 9ebd460182b..8fb992b79e0 100644 --- a/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/XQueryCompiler.java +++ b/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/XQueryCompiler.java @@ -64,12 +64,12 @@ public static CompiledXQuery compile(final DBBroker broker, final URI xqueryLoca public static CompiledXQuery compile(final DBBroker broker, final DocumentImpl document) throws RestXqServiceCompilationException { try { - if(document instanceof BinaryDocument) { + if(document instanceof BinaryDocument binaryDocument) { if(document.getMimeType().equals(XQUERY_MIME_TYPE)){ //compile the query final XQueryContext context = new XQueryContext(broker.getBrokerPool()); - final DBSource source = new DBSource(broker.getBrokerPool(), (BinaryDocument)document, true); + final DBSource source = new DBSource(broker.getBrokerPool(), binaryDocument, true); //set the module load path for any module imports that are relative context.setModuleLoadPath(XmldbURI.EMBEDDED_SERVER_URI_PREFIX + source.getDocumentPath().removeLastSegment()); @@ -89,4 +89,4 @@ public static CompiledXQuery compile(final DBBroker broker, final DocumentImpl d throw new RestXqServiceCompilationException("Permission to access XQuery denied: " + document.getURI().toString() + ": " + pde.getMessage(), pde); } } -} \ No newline at end of file +} diff --git a/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/adapters/SequenceAdapter.java b/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/adapters/SequenceAdapter.java index 0b9dda780ba..c064a0dac3d 100644 --- a/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/adapters/SequenceAdapter.java +++ b/extensions/exquery/restxq/src/main/java/org/exist/extensions/exquery/restxq/impl/adapters/SequenceAdapter.java @@ -106,8 +106,8 @@ public Type getType() { @Override public Item getValue() { - if (item instanceof NodeProxy) { - return DomEnhancingNodeProxyAdapter.create((NodeProxy) item); //RESTXQ expects to find DOM Nodes not NodeProxys + if (item instanceof NodeProxy proxy) { + return DomEnhancingNodeProxyAdapter.create(proxy); //RESTXQ expects to find DOM Nodes not NodeProxys } else { return item; } @@ -144,4 +144,4 @@ public org.exist.xquery.value.Sequence getExistSequence() { } -} \ No newline at end of file +} diff --git a/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/AbstractIntegrationTest.java b/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/AbstractIntegrationTest.java index f13116f02d0..d2bcaf358e6 100644 --- a/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/AbstractIntegrationTest.java +++ b/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/AbstractIntegrationTest.java @@ -58,12 +58,13 @@ public abstract class AbstractIntegrationTest { private static String COLLECTION_CONFIG = - "\n" + - "\n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + + """; private static ContentType XQUERY_CONTENT_TYPE = ContentType.create("application/xquery", UTF_8); diff --git a/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/MediaTypeIntegrationTest.java b/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/MediaTypeIntegrationTest.java index 2574c373c80..d474fd4fd3e 100644 --- a/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/MediaTypeIntegrationTest.java +++ b/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/MediaTypeIntegrationTest.java @@ -46,52 +46,54 @@ public class MediaTypeIntegrationTest extends AbstractClassIntegrationTest { private static String TEST_COLLECTION = "/db/restxq/media-type-integration-test"; private static String XQUERY1 = - "xquery version \"3.0\";\n" + - "\n" + - "module namespace mod1 = \"http://mod1\";\n" + - "\n" + - "declare namespace rest = \"http://exquery.org/ns/restxq\";\n" + - "declare namespace output = \"http://www.w3.org/2010/xslt-xquery-serialization\";\n" + - "\n" + - "declare %private variable $mod1:data := document { AdamRetter } ;\n" + - "\n" + - "declare\n" + - " %rest:GET\n" + - " %rest:path(\"/media-type-json1\")\n" + - " %output:media-type(\"application/json\")\n" + - " %output:method(\"json\")\n" + - "function mod1:media-type-json1() {\n" + - " $mod1:data\n" + - "};\n" + - "\n" + - "declare\n" + - " %rest:GET\n" + - " %rest:path(\"/media-type-json2\")\n" + - " %output:media-type(\"application/json\")\n" + - " %output:method(\"json\")\n" + - "function mod1:media-type-json2() {\n" + - " $mod1:data/person\n" + - "};\n" + - "\n" + - "declare\n" + - " %rest:GET\n" + - " %rest:path(\"/media-type-xml1\")\n" + - " %output:media-type(\"application/xml\")\n" + - " %output:method(\"xml\")\n" + - " %output:indent(\"no\")\n" + - "function mod1:media-type-xml1() {\n" + - " $mod1:data\n" + - "};\n" + - "\n" + - "declare\n" + - " %rest:GET\n" + - " %rest:path(\"/media-type-xml2\")\n" + - " %output:media-type(\"application/xml\")\n" + - " %output:method(\"xml\")\n" + - " %output:indent(\"no\")\n" + - "function mod1:media-type-xml2() {\n" + - " $mod1:data/person\n" + - "};\n"; + """ + xquery version "3.0"; + + module namespace mod1 = "http://mod1"; + + declare namespace rest = "http://exquery.org/ns/restxq"; + declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization"; + + declare %private variable $mod1:data := document { AdamRetter } ; + + declare + %rest:GET + %rest:path("/media-type-json1") + %output:media-type("application/json") + %output:method("json") + function mod1:media-type-json1() { + $mod1:data + }; + + declare + %rest:GET + %rest:path("/media-type-json2") + %output:media-type("application/json") + %output:method("json") + function mod1:media-type-json2() { + $mod1:data/person + }; + + declare + %rest:GET + %rest:path("/media-type-xml1") + %output:media-type("application/xml") + %output:method("xml") + %output:indent("no") + function mod1:media-type-xml1() { + $mod1:data + }; + + declare + %rest:GET + %rest:path("/media-type-xml2") + %output:media-type("application/xml") + %output:method("xml") + %output:indent("no") + function mod1:media-type-xml2() { + $mod1:data/person + }; + """; private static String XQUERY1_FILENAME = "restxq-tests1.xqm"; @BeforeClass diff --git a/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/SelfImportCircularDependencyIntegrationTest.java b/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/SelfImportCircularDependencyIntegrationTest.java index 8a4d0ba4cd4..791f02b0ab6 100644 --- a/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/SelfImportCircularDependencyIntegrationTest.java +++ b/extensions/exquery/restxq/src/test/java/org/exist/extensions/exquery/restxq/impl/SelfImportCircularDependencyIntegrationTest.java @@ -42,13 +42,15 @@ public class SelfImportCircularDependencyIntegrationTest extends AbstractClassIn private static String XQUERY_FILENAME = "mod1.xqm"; private static String STAGE1_XQUERY = - "xquery version \"3.1\";\n" + - "\n" + - "module namespace test = \"test\";\n" + - "\n" + - "declare function test:f1() {\n" + - " \n" + - "};"; + """ + xquery version "3.1"; + + module namespace test = "test"; + + declare function test:f1() { + + };\ + """; private static String STAGE2_XQUERY = "xquery version \"3.1\";\n" + diff --git a/extensions/indexes/indexes-integration-tests/src/test/java/org/exist/indexing/EnforceIndexUseTest.java b/extensions/indexes/indexes-integration-tests/src/test/java/org/exist/indexing/EnforceIndexUseTest.java index e12fea8a539..faec9ba6747 100644 --- a/extensions/indexes/indexes-integration-tests/src/test/java/org/exist/indexing/EnforceIndexUseTest.java +++ b/extensions/indexes/indexes-integration-tests/src/test/java/org/exist/indexing/EnforceIndexUseTest.java @@ -77,24 +77,27 @@ public static java.util.Collection data() { private ExistEmbeddedServer existEmbeddedServer; private static final String OLD_RANGE_COLLECTION_CONFIG = - "\n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + """; private static final String NEW_RANGE_COLLECTION_CONFIG = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + + + """; private static final String XML = - "\n" + - "\n" + - ""; + """ + + + """; @Test public void matchesWithDiffrentIndexStyles() throws PermissionDeniedException, EXistException, XPathException { @@ -191,4 +194,4 @@ public void cleanup() throws EXistException, PermissionDeniedException, IOExcept existEmbeddedServer.stopDb(true); existEmbeddedServer = null; } -} \ No newline at end of file +} diff --git a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/AnalyzerConfig.java b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/AnalyzerConfig.java index 626cb293342..42093664502 100644 --- a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/AnalyzerConfig.java +++ b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/AnalyzerConfig.java @@ -189,7 +189,7 @@ static T createInstance(final Class clazz, final Class T createInstance(final Class clazz, final Class getConstructorParameter(final Element param) throws Para //default, assume java.lang.String yield new KeyTypedValue<>(name, value, String.class); } catch (ClassNotFoundException cnfe) { - throw new ParameterException(String.format("Class for type: %s not found. %s", type, cnfe.getMessage()), cnfe); + throw new ParameterException("Class for type: %s not found. %s".formatted(type, cnfe.getMessage()), cnfe); } } }; diff --git a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/BinaryTokenStream.java b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/BinaryTokenStream.java index d25587eea59..448f1b9e4bd 100644 --- a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/BinaryTokenStream.java +++ b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/BinaryTokenStream.java @@ -82,8 +82,8 @@ public void reflectWith(org.apache.lucene.util.AttributeReflector reflector) { @Override public void copyTo(AttributeImpl target) { - if (target instanceof ByteTermAttribute) { - ((ByteTermAttribute) target).setBytesRef(bytes); + if (target instanceof ByteTermAttribute attribute) { + attribute.setBytesRef(bytes); } else if (target instanceof TermToBytesRefAttribute) { // Since we implement TermToBytesRefAttribute, Lucene might expect this // Although TermToBytesRefAttribute doesn't have a setter, diff --git a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneConfig.java b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneConfig.java index 33c1e7c3844..dcd982df202 100644 --- a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneConfig.java +++ b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneConfig.java @@ -361,7 +361,7 @@ public Analyzer getAnalyzer(String field) { if (queryAnalyzer != null) return queryAnalyzer; - LOG.warn(String.format("Failed to substitute %s with %s analyzer", id, qid)); + LOG.warn("Failed to substitute %s with %s analyzer".formatted(id, qid)); } return analyzers.getAnalyzerById(id); } diff --git a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneFieldConfig.java b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneFieldConfig.java index 2312090ff99..4e76cb96d00 100644 --- a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneFieldConfig.java +++ b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneFieldConfig.java @@ -136,7 +136,7 @@ protected void build(DBBroker broker, DocumentImpl document, NodeId nodeId, Docu } private boolean checkCondition(DBBroker broker, DocumentImpl document, NodeId nodeId) throws PermissionDeniedException, XPathException { - if (!condition.isPresent()) { + if (condition.isEmpty()) { return true; } @@ -193,9 +193,8 @@ private Field convertToField(String content) { case Type.UNSIGNED_LONG: final BigInteger big = new BigInteger(content.trim()); if (big.compareTo(LONG_MIN) < 0 || big.compareTo(LONG_MAX) > 0) { - throw new IllegalStateException(String.format( - "Lucene field '%s' of type xs:integer cannot store value outside long range (-9223372036854775808 to 9223372036854775807): %s. See https://github.com/eXist-db/exist/issues/4532", - fieldName, content)); + throw new IllegalStateException("Lucene field '%s' of type xs:integer cannot store value outside long range (-9223372036854775808 to 9223372036854775807): %s. See https://github.com/eXist-db/exist/issues/4532".formatted( + fieldName, content)); } long lvalue = big.longValue(); return new LongField(fieldName, lvalue, Field.Store.YES); diff --git a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneIndexWorker.java b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneIndexWorker.java index c582463ac83..cc9a77fc21f 100644 --- a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneIndexWorker.java +++ b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneIndexWorker.java @@ -806,7 +806,7 @@ private Query buildDocsFilterQuery(final DocumentSet docs) { docIdQueries.add(IntField.newExactQuery(FIELD_DOC_ID, it.next().getDocId())); } if (docIdQueries.size() == 1) { - return docIdQueries.get(0); + return docIdQueries.getFirst(); } final BooleanQuery.Builder b = new BooleanQuery.Builder(); for (final Query q : docIdQueries) { @@ -1213,8 +1213,8 @@ public IndexableField[] getFieldByExistDocId(final int existDocId, final NodeId result[i++] = f; } return result; - } else if (fieldsObj instanceof IndexableField[]) { - return (IndexableField[]) fieldsObj; + } else if (fieldsObj instanceof IndexableField[] indexableFields) { + return indexableFields; } return new IndexableField[0]; }); @@ -1569,7 +1569,7 @@ private static List getQNamesFromNodes(NodeSet nodes) { if (opts.getQueryAnalyzerId() != null) { analyzer = config.getAnalyzerById(opts.getQueryAnalyzerId()); if (analyzer == null) { - String msg = String.format("getAnalyzerById('%s') returned null!", opts.getQueryAnalyzerId()); + String msg = "getAnalyzerById('%s') returned null!".formatted(opts.getQueryAnalyzerId()); LOG.error(msg); } } @@ -1595,7 +1595,7 @@ else if (field == null) { */ public static LuceneConfig getLuceneConfig(DBBroker broker, DocumentSet docs) { for (Iterator i = docs.getCollectionIterator(); i.hasNext(); ) { - try (Collection collection = i.next();) { + try (Collection collection = i.next()) { IndexSpec idxConf = collection.getIndexConfiguration(broker); if (idxConf != null) { LuceneConfig config = (LuceneConfig) idxConf.getCustomIndexSpec(LuceneIndex.ID); @@ -2217,4 +2217,4 @@ private void releaseAttributes() { } } } - } \ No newline at end of file + } diff --git a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneMatchListener.java b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneMatchListener.java index d7d5e8a6c25..29feb3e8104 100644 --- a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneMatchListener.java +++ b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneMatchListener.java @@ -309,7 +309,7 @@ private void scanMatches(final NodeProxy p) { if (stateList.size() == terms.length) { // Phrase match: add one span from first to last term (may cross text nodes, #4584). - stream.restoreState(stateList.get(0)); + stream.restoreState(stateList.getFirst()); final int start = stream.getAttribute(OffsetAttribute.class).startOffset(); stream.restoreState(stateList.get(terms.length - 1)); final int end = stream.getAttribute(OffsetAttribute.class).endOffset(); diff --git a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneVectorFieldConfig.java b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneVectorFieldConfig.java index 4579bc6f290..452380cc10e 100644 --- a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneVectorFieldConfig.java +++ b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/LuceneVectorFieldConfig.java @@ -247,7 +247,7 @@ protected void processResult(final Sequence result, final Document luceneDoc) th if (vectors.isEmpty()) { return; } - final float[] combined = vectors.size() == 1 ? vectors.get(0) : meanPool(vectors); + final float[] combined = vectors.size() == 1 ? vectors.getFirst() : meanPool(vectors); if (combined != null) { luceneDoc.add(new KnnFloatVectorField(fieldName, combined, similarity)); } @@ -272,7 +272,7 @@ private void processResultEmbedding(final Sequence result, final Document lucene if (vectors.isEmpty()) { return; } - final float[] combined = vectors.size() == 1 ? vectors.get(0) : meanPool(vectors); + final float[] combined = vectors.size() == 1 ? vectors.getFirst() : meanPool(vectors); if (combined != null) { luceneDoc.add(new KnnFloatVectorField(fieldName, combined, similarity)); storeVectorIfLocal(combined); diff --git a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/XMLToQuery.java b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/XMLToQuery.java index 476129a6082..82615ac890e 100644 --- a/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/XMLToQuery.java +++ b/extensions/indexes/lucene/src/main/java/org/exist/indexing/lucene/XMLToQuery.java @@ -558,10 +558,9 @@ private Query parseChildren(String field, Element root, Analyzer analyzer, Query if (child.getNodeType() == Node.ELEMENT_NODE) { Query childQuery = parse(field, (Element) child, analyzer, options); if (query != null) { - if (query instanceof BooleanQuery) { + if (query instanceof BooleanQuery existing) { // migrate to builder BooleanQuery.Builder b = new BooleanQuery.Builder(); - BooleanQuery existing = (BooleanQuery) query; for (BooleanClause c : existing) b.add(c); b.add(childQuery, BooleanClause.Occur.SHOULD); query = b.build(); diff --git a/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/Query.java b/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/Query.java index 41ecd71eb4a..04b9924df53 100644 --- a/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/Query.java +++ b/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/Query.java @@ -103,7 +103,7 @@ public Query(final XQueryContext context, final FunctionSignature signature) { public void setArguments(final List arguments) { steps.clear(); - final Expression path = arguments.get(0); + final Expression path = arguments.getFirst(); steps.add(path); Expression arg = arguments.get(1).simplify(); diff --git a/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/QueryOptions.java b/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/QueryOptions.java index fb85e9860b6..5a60ddbe583 100644 --- a/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/QueryOptions.java +++ b/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/QueryOptions.java @@ -289,13 +289,13 @@ private void set(String key, String value) throws XPathException { } public void configureParser(CommonQueryParserConfiguration parser) { - if (parser instanceof QueryParserBase) { + if (parser instanceof QueryParserBase base) { switch (defaultOperator) { case OR: - ((QueryParserBase) parser).setDefaultOperator(QueryParser.OR_OPERATOR); + base.setDefaultOperator(QueryParser.OR_OPERATOR); break; default: - ((QueryParserBase) parser).setDefaultOperator(QueryParser.AND_OPERATOR); + base.setDefaultOperator(QueryParser.AND_OPERATOR); break; } } diff --git a/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/Search.java b/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/Search.java index 7b5d98569b7..073f0dba8b8 100644 --- a/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/Search.java +++ b/extensions/indexes/lucene/src/main/java/org/exist/xquery/modules/lucene/Search.java @@ -58,14 +58,15 @@ public class Search extends BasicFunction { new FunctionParameterSequenceType("fields", Type.STRING, Cardinality.ZERO_OR_MORE, "Fields to return in search results"), new FunctionParameterSequenceType("options", Type.NODE, Cardinality.ZERO_OR_ONE, - "An XML fragment containing options to be passed to Lucene's query parser. The following " + - "options are supported (a description can be found in the docs):\n" + - "\n" + - " and|or\n" + - " number\n" + - " yes|no\n" + - " yes|no\n" + - "") + """ + An XML fragment containing options to be passed to Lucene's query parser. The following \ + options are supported (a description can be found in the docs): + + and|or + number + yes|no + yes|no + """) }, new FunctionReturnSequenceType(Type.NODE, Cardinality.EXACTLY_ONE, "All documents that are match by the query")), diff --git a/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/AnalyzerConfigTest.java b/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/AnalyzerConfigTest.java index dbf06a40628..2841fa88b4e 100644 --- a/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/AnalyzerConfigTest.java +++ b/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/AnalyzerConfigTest.java @@ -53,11 +53,12 @@ public class AnalyzerConfigTest { @Test public void parameterFromCharArray() throws ParserConfigurationException, IOException, SAXException, AnalyzerConfig.ParameterException { final String strParam = - "\n" + - " '\n" + - " -\n" + - " \n" + - ""; + """ + + ' + - + + """; final Element elemParam = parse(strParam).getDocumentElement(); final AnalyzerConfig.KeyTypedValue constructorParameter = AnalyzerConfig.getConstructorParameter(elemParam); @@ -70,11 +71,12 @@ public void parameterFromCharArray() throws ParserConfigurationException, IOExce @Test(expected = AnalyzerConfig.ParameterException.class) public void parameterFromInvalidCharArray() throws ParserConfigurationException, IOException, SAXException, AnalyzerConfig.ParameterException { final String strParam = - "\n" + - " '\n" + - " \n" + - " \n" + - ""; + """ + + ' + + + """; final Element elemParam = parse(strParam).getDocumentElement(); AnalyzerConfig.getConstructorParameter(elemParam); @@ -83,12 +85,13 @@ public void parameterFromInvalidCharArray() throws ParserConfigurationException, @Test public void parameterFromStringArray() throws ParserConfigurationException, IOException, SAXException, AnalyzerConfig.ParameterException { final String strParam = - "\n" + - " hello\n" + - " hi\n" + - " \n" + - " goodbye\n" + - ""; + """ + + hello + hi + + goodbye + """; final Element elemParam = parse(strParam).getDocumentElement(); final AnalyzerConfig.KeyTypedValue constructorParameter = AnalyzerConfig.getConstructorParameter(elemParam); @@ -101,13 +104,14 @@ public void parameterFromStringArray() throws ParserConfigurationException, IOEx @Test public void allParametersIntegerAndSet() throws ParserConfigurationException, IOException, SAXException, AnalyzerConfig.ParameterException { final String strAnalyzer = - "\n" + - " \n" + - " \n" + - " '\n" + - " -\n" + - " \n" + - ""; + """ + + + + ' + - + + """; final Element elemAnalyzer = parse(strAnalyzer).getDocumentElement(); final List> extractedConstructorArgs = AnalyzerConfig.getAllConstructorParameters(elemAnalyzer); @@ -129,13 +133,14 @@ public void allParametersIntegerAndSet() throws ParserConfigurationException, IO @Test public void allParametersIntAndSet() throws ParserConfigurationException, IOException, SAXException, AnalyzerConfig.ParameterException { final String strAnalyzer = - "\n" + - " \n" + - " \n" + - " '\n" + - " -\n" + - " \n" + - ""; + """ + + + + ' + - + + """; final Element elemAnalyzer = parse(strAnalyzer).getDocumentElement(); final List> extractedConstructorArgs = AnalyzerConfig.getAllConstructorParameters(elemAnalyzer); @@ -157,13 +162,14 @@ public void allParametersIntAndSet() throws ParserConfigurationException, IOExce @Test public void allParametersBooleanAndSet() throws ParserConfigurationException, IOException, SAXException, AnalyzerConfig.ParameterException { final String strAnalyzer = - "\n" + - " \n" + - " \n" + - " '\n" + - " -\n" + - " \n" + - ""; + """ + + + + ' + - + + """; final Element elemAnalyzer = parse(strAnalyzer).getDocumentElement(); final List> extractedConstructorArgs = AnalyzerConfig.getAllConstructorParameters(elemAnalyzer); @@ -185,13 +191,14 @@ public void allParametersBooleanAndSet() throws ParserConfigurationException, IO @Test public void allParametersPrimitiveBooleanAndSet() throws ParserConfigurationException, IOException, SAXException, AnalyzerConfig.ParameterException { final String strAnalyzer = - "\n" + - " \n" + - " \n" + - " '\n" + - " -\n" + - " \n" + - ""; + """ + + + + ' + - + + """; final Element elemAnalyzer = parse(strAnalyzer).getDocumentElement(); final List> extractedConstructorArgs = AnalyzerConfig.getAllConstructorParameters(elemAnalyzer); @@ -213,12 +220,13 @@ public void allParametersPrimitiveBooleanAndSet() throws ParserConfigurationExce @Test public void allParametersCharArray() throws ParserConfigurationException, IOException, SAXException, AnalyzerConfig.ParameterException { final String strAnalyzer = - "\n" + - " \n" + - " '\n" + - " -\n" + - " \n" + - ""; + """ + + + ' + - + + """; final Element elemAnalyzer = parse(strAnalyzer).getDocumentElement(); final List> extractedConstructorArgs = AnalyzerConfig.getAllConstructorParameters(elemAnalyzer); @@ -234,12 +242,13 @@ public void allParametersCharArray() throws ParserConfigurationException, IOExce @Test public void allParametersStringArray() throws ParserConfigurationException, IOException, SAXException, AnalyzerConfig.ParameterException { final String strAnalyzer = - "\n" + - " \n" + - " abc\n" + - " def\n" + - " \n" + - ""; + """ + + + abc + def + + """; final Element elemAnalyzer = parse(strAnalyzer).getDocumentElement(); final List> extractedConstructorArgs = AnalyzerConfig.getAllConstructorParameters(elemAnalyzer); diff --git a/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/FacetPollutionJavaReproducerTest.java b/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/FacetPollutionJavaReproducerTest.java index 172e22fdc5a..097000d22ae 100644 --- a/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/FacetPollutionJavaReproducerTest.java +++ b/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/FacetPollutionJavaReproducerTest.java @@ -46,7 +46,6 @@ import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -82,7 +81,7 @@ public void hierarchicalFacetTermsMissingAfterPolluterRemoval() throws Exception final String tempModulesName = "lucene-test-facet-pollution-java-modules-" + System.nanoTime(); final XmldbURI tempModulesUri = XmldbURI.create("/db/" + tempModulesName); - final Path baseDir = Paths.get(System.getProperty("user.dir")); + final Path baseDir = Path.of(System.getProperty("user.dir")); final Path zAnalyzersPath = resolveModulePath(baseDir, "src/test/xquery/lucene/analyzers-field.xqm", "extensions/indexes/lucene/src/test/xquery/lucene/analyzers-field.xqm"); @@ -195,7 +194,7 @@ public void hierarchicalFacetTermsPresentWithoutPolluter() throws Exception { final String tempModulesName = "lucene-test-facet-pollution-java-modules-" + System.nanoTime(); final XmldbURI tempModulesUri = XmldbURI.create("/db/" + tempModulesName); - final Path baseDir = Paths.get(System.getProperty("user.dir")); + final Path baseDir = Path.of(System.getProperty("user.dir")); final Path ftFacetsPath = resolveModulePath(baseDir, "src/test/xquery/lucene/ft-facets.xqm", "extensions/indexes/lucene/src/test/xquery/lucene/ft-facets.xqm"); diff --git a/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/LuceneIndexTest.java b/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/LuceneIndexTest.java index 22b069816be..1c629cbdb31 100644 --- a/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/LuceneIndexTest.java +++ b/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/LuceneIndexTest.java @@ -85,11 +85,14 @@ public class LuceneIndexTest { ""; private static final String XML2 = - "" + - " Chair" + - " Table\ngood" + - " Cabinet\nbad" + - ""; + """ + \ + Chair\ + Table + good\ + Cabinet + bad\ + """; private static final String XML3 = "
" + @@ -325,19 +328,20 @@ public void moreElaborateQueries() throws EXistException, CollectionConfiguratio ""; final String COLLECTION_CONFIG10 = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + + + + + + + \s + + """; final DocumentSet docs = configureAndStore(COLLECTION_CONFIG10, XML10, "test.xml"); diff --git a/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/LuceneMatchListenerTest.java b/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/LuceneMatchListenerTest.java index 445545ec67b..bd2974ca5f0 100644 --- a/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/LuceneMatchListenerTest.java +++ b/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/LuceneMatchListenerTest.java @@ -89,29 +89,30 @@ public class LuceneMatchListenerTest { ""; private static String XML2 = - "

\n" + - " из\n" + - " новина\n" + - " и\n" + - " од\n" + - " \n" + - " \n" + - " других\n" + - " људи\n" + - " дознајем, ма\n" + - " се\n" + - " не\n" + - " прорезује\n" + - " право\n" + - " по\n" + - " имућству, те\n" + - " се\n" + - " на\n" + - " то\n" + - " видим\n" + - " многи\n" + - " љуте.\n" + - "

"; + """ +

+ из + новина + и + од + + + других + људи + дознајем, ма + се + не + прорезује + право + по + имућству, те + се + на + то + видим + многи + љуте. +

"""; private static String CONF1 = "" + @@ -150,15 +151,16 @@ public class LuceneMatchListenerTest { private static String CONF5 = - "\n" + - " " + - " " + - " " + - " " + - " " + - " " + - " " + - ""; + """ + + \ + \ + \ + \ + \ + \ + \ + """; private static String MATCH_START = ""; private static String MATCH_END = ""; @@ -208,8 +210,9 @@ public void indexByQName() throws EXistException, PermissionDeniedException, XPa MATCH_START + "match" + MATCH_END + "", result); seq = xquery.execute(broker, - "for $para in //para[ft:query(., '+double +match')] return\n" + - " {$para}", null); + """ + for $para in //para[ft:query(., '+double +match')] return + {$para}""", null); assertNotNull(seq); assertEquals(1, seq.getItemCount()); result = queryResult2String(broker, seq); diff --git a/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/SerializeAttrMatchesTest.java b/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/SerializeAttrMatchesTest.java index c9e70017a78..531d494e333 100644 --- a/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/SerializeAttrMatchesTest.java +++ b/extensions/indexes/lucene/src/test/java/org/exist/indexing/lucene/SerializeAttrMatchesTest.java @@ -70,12 +70,13 @@ public class SerializeAttrMatchesTest { ""; private static final String XML = - "нас\n" + - "свакога\n" + - "Божића\n" + - "новом\n" + - "књигом\n" + - "пешкешите. –"; + """ + нас + свакога + Божића + новом + књигом + пешкешите. –"""; private Collection test = null; diff --git a/extensions/indexes/lucene/src/test/java/xquery/lucene/VectorSearchEmbeddingTest.java b/extensions/indexes/lucene/src/test/java/xquery/lucene/VectorSearchEmbeddingTest.java index 3a854090cfd..c89bef2cfd8 100644 --- a/extensions/indexes/lucene/src/test/java/xquery/lucene/VectorSearchEmbeddingTest.java +++ b/extensions/indexes/lucene/src/test/java/xquery/lucene/VectorSearchEmbeddingTest.java @@ -38,7 +38,6 @@ import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import static org.junit.Assert.assertEquals; import static org.junit.Assume.assumeTrue; @@ -99,7 +98,7 @@ private Sequence executeQuery(final String query) throws EXistException, Permiss private boolean hasEmbeddingModel() { final Path base = ConfigurationHelper.getExistHome() - .orElse(Paths.get(System.getProperty("user.dir", "."))); + .orElse(Path.of(System.getProperty("user.dir", "."))); final Path modelDir = base.resolve("target/onnx-models/all-MiniLM-L6-v2"); return Files.isRegularFile(modelDir.resolve("model.onnx")) && Files.isRegularFile(modelDir.resolve("tokenizer.json")); diff --git a/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/HighlightMatches.java b/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/HighlightMatches.java index a7dba848f52..cd2a451c8bc 100644 --- a/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/HighlightMatches.java +++ b/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/HighlightMatches.java @@ -56,15 +56,22 @@ public class HighlightMatches extends BasicFunction { public final static FunctionSignature signature = new FunctionSignature( new QName("filter-matches", NGramModule.NAMESPACE_URI, NGramModule.PREFIX), - "Highlight matching strings within text nodes that resulted from a ngram search. " + - "The function takes a sequence of nodes as first argument $nodes and a callback function (defined with " + - "util:function) as second parameter $function-reference. Each node in $nodes will be copied into a new document fragment. " + - "For each ngram match found while copying a node, the callback function in $function-reference will be called once. The " + - "callback function should take 2 arguments:\n\n1) the matching text string as xs:string,\n2) the node to which this " + - "text string belongs.\n\nThe callback function should return zero or more nodes, which will be inserted into the " + - "resulting node set at the place where the matching text sequence occurred.\n\n" + - "Note: a ngram match on mixed content may span multiple nodes. In this case, the callback function is called " + - "once for every text node which is part of the matching text sequence.", + """ + Highlight matching strings within text nodes that resulted from a ngram search. \ + The function takes a sequence of nodes as first argument $nodes and a callback function (defined with \ + util:function) as second parameter $function-reference. Each node in $nodes will be copied into a new document fragment. \ + For each ngram match found while copying a node, the callback function in $function-reference will be called once. The \ + callback function should take 2 arguments: + + 1) the matching text string as xs:string, + 2) the node to which this \ + text string belongs. + + The callback function should return zero or more nodes, which will be inserted into the \ + resulting node set at the place where the matching text sequence occurred. + + Note: a ngram match on mixed content may span multiple nodes. In this case, the callback function is called \ + once for every text node which is part of the matching text sequence.""", new SequenceType[] { new FunctionParameterSequenceType("nodes", Type.NODE, Cardinality.ZERO_OR_MORE, "The sequence of nodes"), new FunctionParameterSequenceType("function-reference", Type.FUNCTION, Cardinality.EXACTLY_ONE, "The callback function") diff --git a/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/NGramSearch.java b/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/NGramSearch.java index 10a230baaea..9fe9189d1f5 100644 --- a/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/NGramSearch.java +++ b/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/NGramSearch.java @@ -134,7 +134,7 @@ public NGramSearch(XQueryContext context, FunctionSignature signature) { @Override public void setArguments(List arguments) throws XPathException { steps.clear(); - Expression path = arguments.get(0); + Expression path = arguments.getFirst(); steps.add(path); Expression arg = arguments.get(1); diff --git a/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/query/WildcardedExpressionSequence.java b/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/query/WildcardedExpressionSequence.java index 64499177b01..cf72827e3cd 100644 --- a/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/query/WildcardedExpressionSequence.java +++ b/extensions/indexes/ngram/src/main/java/org/exist/xquery/modules/ngram/query/WildcardedExpressionSequence.java @@ -51,9 +51,9 @@ public WildcardedExpressionSequence(final List expressions WildcardedExpression currentExpression = expressions.removeFirst(); for (WildcardedExpression expression : expressions) { - if (currentExpression instanceof MergeableExpression - && ((MergeableExpression) currentExpression).mergeableWith(expression)) { - currentExpression = ((MergeableExpression) currentExpression).mergeWith(expression); + if (currentExpression instanceof MergeableExpression mergeableExpression + && mergeableExpression.mergeableWith(expression)) { + currentExpression = mergeableExpression.mergeWith(expression); } else { this.expressions.add(currentExpression); currentExpression = expression; @@ -143,14 +143,14 @@ private NodeSet expandMatchesBackward(final Wildcard leadingWildcard, final Node * */ private void formEvaluatableTriples(final int expressionId) { - WildcardedExpression first = expressions.get(0); + WildcardedExpression first = expressions.getFirst(); WildcardedExpression second = expressions.get(1); WildcardedExpression third = expressions.get(2); - if (first instanceof EvaluatableExpression && second instanceof Wildcard - && third instanceof EvaluatableExpression) { - WildcardedExpressionTriple triple = new WildcardedExpressionTriple((EvaluatableExpression) first, - (Wildcard) second, (EvaluatableExpression) third); + if (first instanceof EvaluatableExpression expression && second instanceof Wildcard wildcard + && third instanceof EvaluatableExpression expression1) { + WildcardedExpressionTriple triple = new WildcardedExpressionTriple(expression, + wildcard, expression1); expressions.subList(0, 3).clear(); expressions.addFirst(triple); } else { diff --git a/extensions/indexes/ngram/src/test/java/org/exist/indexing/ngram/CustomIndexTest.java b/extensions/indexes/ngram/src/test/java/org/exist/indexing/ngram/CustomIndexTest.java index 123f35dd528..1653743d134 100644 --- a/extensions/indexes/ngram/src/test/java/org/exist/indexing/ngram/CustomIndexTest.java +++ b/extensions/indexes/ngram/src/test/java/org/exist/indexing/ngram/CustomIndexTest.java @@ -599,14 +599,16 @@ public void indexKeys() throws SAXException, PermissionDeniedException, XPathExc assertEquals(1, seq.getItemCount()); String queryBody = - "declare function local:callback($key as item(), $data as xs:int+)\n" + - "as element()+ {\n" + - " \n" + - " {$key}\n" + - " {$data[1]}\n" + - " \n" + - "};\n" + - "\n"; + """ + declare function local:callback($key as item(), $data as xs:int+) + as element()+ { + + {$key} + {$data[1]} + + }; + + """; String query = queryBody + "util:index-keys(/test/item, \'\', util:function(xs:QName(\'local:callback\'), 2), 1000, 'ngram-index')"; //String query = queryBody + "util:index-keys(/test/item, \'\', util:function(xs:QName(\'local:callback\'), 2), 1000, 'org.exist.indexing.impl.NGramIndex')"; diff --git a/extensions/indexes/ngram/src/test/java/org/exist/indexing/ngram/MatchListenerTest.java b/extensions/indexes/ngram/src/test/java/org/exist/indexing/ngram/MatchListenerTest.java index 79fdafc5e98..1af382fdc8b 100644 --- a/extensions/indexes/ngram/src/test/java/org/exist/indexing/ngram/MatchListenerTest.java +++ b/extensions/indexes/ngram/src/test/java/org/exist/indexing/ngram/MatchListenerTest.java @@ -81,14 +81,15 @@ public class MatchListenerTest { + ""; private static String XML2 = - "\n" + - "

爾時會中。有一尊者。名曰龍護。手執寶拂。 \n" + - " 侍立佛側。時尊者龍護白佛言。世尊。我見 \n" + - " 諸邪外道尼乾子等。於佛世尊。先不起信。 \n" + - " 唯於邪道。競說勝能。是故我今建立表剎 \n" + - " 宣示於世。咸使聞知佛勝功德。於佛世尊。是 \n" + - " 大丈夫。最尊最上。無有等者。\n" + - "

"; + """ + +

爾時會中。有一尊者。名曰龍護。手執寶拂。\s + 侍立佛側。時尊者龍護白佛言。世尊。我見\s + 諸邪外道尼乾子等。於佛世尊。先不起信。\s + 唯於邪道。競說勝能。是故我今建立表剎\s + 宣示於世。咸使聞知佛勝功德。於佛世尊。是\s + 大丈夫。最尊最上。無有等者。 +

"""; private static String CONF1 = "" + @@ -121,7 +122,7 @@ public void nestedContent() throws PermissionDeniedException, IOException, LockE configureAndStore(CONF1, XML); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final XQuery xquery = pool.getXQueryService(); assertNotNull(xquery); Sequence seq = xquery.execute(broker, "//para[ngram:contains(., 'mixed')]", null); @@ -159,7 +160,7 @@ public void matchInParent() throws PermissionDeniedException, IOException, LockE configureAndStore(CONF1, XML); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final XQuery xquery = pool.getXQueryService(); assertNotNull(xquery); @@ -176,7 +177,7 @@ public void matchInAncestor() throws PermissionDeniedException, IOException, Loc configureAndStore(CONF1, XML); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final XQuery xquery = pool.getXQueryService(); assertNotNull(xquery); @@ -199,7 +200,7 @@ public void nestedIndex() throws PermissionDeniedException, IOException, LockExc configureAndStore(CONF1, XML); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final XQuery xquery = pool.getXQueryService(); assertNotNull(xquery); @@ -228,7 +229,7 @@ public void mixedContentQueries() throws PermissionDeniedException, XPathExcepti configureAndStore(CONF1, XML); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final XQuery xquery = pool.getXQueryService(); assertNotNull(xquery); @@ -269,7 +270,7 @@ public void indexOnInnerElement() throws PermissionDeniedException, IOException, configureAndStore(CONF2, XML); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final XQuery xquery = pool.getXQueryService(); assertNotNull(xquery); Sequence seq = xquery.execute(broker, "//para[ngram:contains(note, 'nested inner')]", null); @@ -293,7 +294,7 @@ public void doubleMatch() throws PermissionDeniedException, XPathException, SAXE configureAndStore(CONF1, XML); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final XQuery xquery = pool.getXQueryService(); assertNotNull(xquery); @@ -324,7 +325,7 @@ public void wildcardMatch() throws PermissionDeniedException, IOException, LockE configureAndStore(CONF1, XML); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final XQuery xquery = pool.getXQueryService(); assertNotNull(xquery); @@ -463,7 +464,7 @@ public void smallStrings() throws PermissionDeniedException, IOException, LockEx configureAndStore(CONF3, XML2); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final XQuery xquery = pool.getXQueryService(); assertNotNull(xquery); @@ -488,7 +489,7 @@ public void constructedNodes() throws PermissionDeniedException, XPathException, configureAndStore(CONF3, XML2); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); - try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()));) { + try(final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject()))) { final XQuery xquery = pool.getXQueryService(); assertNotNull(xquery); diff --git a/extensions/indexes/range/src/main/java/org/exist/indexing/range/RangeIndexConfigCondition.java b/extensions/indexes/range/src/main/java/org/exist/indexing/range/RangeIndexConfigCondition.java index 1e7222da21a..d6141e1a3ab 100644 --- a/extensions/indexes/range/src/main/java/org/exist/indexing/range/RangeIndexConfigCondition.java +++ b/extensions/indexes/range/src/main/java/org/exist/indexing/range/RangeIndexConfigCondition.java @@ -60,14 +60,14 @@ public boolean find(Predicate predicate) { */ protected Expression getInnerExpression(Predicate predicate) { Expression inner = predicate.getExpression(0); - if (inner instanceof InternalFunctionCall) { - Function function = ((InternalFunctionCall)inner).getFunction(); - if (function instanceof Lookup) { - return ((Lookup)function).getFallback(); + if (inner instanceof InternalFunctionCall call) { + Function function = call.getFunction(); + if (function instanceof Lookup lookup) { + return lookup.getFallback(); } } return inner; } -} \ No newline at end of file +} diff --git a/extensions/indexes/range/src/main/java/org/exist/indexing/range/RangeIndexWorker.java b/extensions/indexes/range/src/main/java/org/exist/indexing/range/RangeIndexWorker.java index bdff00fe70c..95c2a23480f 100644 --- a/extensions/indexes/range/src/main/java/org/exist/indexing/range/RangeIndexWorker.java +++ b/extensions/indexes/range/src/main/java/org/exist/indexing/range/RangeIndexWorker.java @@ -204,37 +204,22 @@ public Query toQuery(String field, QName qname, AtomicValue content, RangeIndex. }; } if (operator == RangeIndex.Operator.NE) { - Query eqQuery; - switch (type) { + Query eqQuery = switch (type) { case Type.INTEGER: case Type.LONG: - case Type.UNSIGNED_LONG: - eqQuery = LongField.newExactQuery(field, ((NumericValue) content).getLong()); - break; + case Type.UNSIGNED_LONG: yield LongField.newExactQuery(field, ((NumericValue) content).getLong()); case Type.INT: case Type.UNSIGNED_INT: case Type.SHORT: - case Type.UNSIGNED_SHORT: - eqQuery = IntField.newExactQuery(field, ((NumericValue) content).getInt()); - break; + case Type.UNSIGNED_SHORT: yield IntField.newExactQuery(field, ((NumericValue) content).getInt()); case Type.DECIMAL: - case Type.DOUBLE: - eqQuery = DoubleField.newExactQuery(field, ((NumericValue) content).getDouble()); - break; - case Type.FLOAT: - eqQuery = FloatField.newExactQuery(field, (float) ((NumericValue) content).getDouble()); - break; - case Type.DATE: - eqQuery = LongField.newExactQuery(field, RangeIndexConfigElement.dateToLong((DateValue) content)); - break; - case Type.TIME: - eqQuery = LongField.newExactQuery(field, RangeIndexConfigElement.timeToLong((TimeValue) content)); - break; + case Type.DOUBLE: yield DoubleField.newExactQuery(field, ((NumericValue) content).getDouble()); + case Type.FLOAT: yield FloatField.newExactQuery(field, (float) ((NumericValue) content).getDouble()); + case Type.DATE: yield LongField.newExactQuery(field, RangeIndexConfigElement.dateToLong((DateValue) content)); + case Type.TIME: yield LongField.newExactQuery(field, RangeIndexConfigElement.timeToLong((TimeValue) content)); case Type.DATE_TIME: - default: - eqQuery = new TermQuery(new Term(field, RangeIndexConfigElement.convertToBytes(content))); - break; - } + default: yield new TermQuery(new Term(field, RangeIndexConfigElement.convertToBytes(content))); + }; final BooleanQuery.Builder nqb = new BooleanQuery.Builder(); nqb.add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST); nqb.add(eqQuery, BooleanClause.Occur.MUST_NOT); @@ -678,7 +663,7 @@ public NodeSet queryField(int contextId, DocumentSet docs, NodeSet contextSet, S BooleanQuery query = queryBuilder.build(); Query qu = query; if (query.clauses().size() == 1) { - qu = query.clauses().get(0).query(); + qu = query.clauses().getFirst().query(); } final NodeSet resultSet = new NewArrayNodeSet(); resultSet.addAll(doQuery(contextId, docs, contextSet, axis, searcher.searcher(), Node.ELEMENT_NODE, qu)); @@ -720,18 +705,23 @@ private NodeSet doQuery(final int contextId, final DocumentSet docs, final NodeS private void diagnoseQuery(IndexSearcher searcher, Query query) { String field = null; String searchTerm = null; - if (query instanceof TermQuery tq) { - Term t = tq.getTerm(); - field = t.field(); - searchTerm = t.text(); - } else if (query instanceof PrefixQuery pq) { - Term t = pq.getPrefix(); - field = t.field(); - searchTerm = t.text(); - } else if (query instanceof WildcardQuery wq) { - Term t = wq.getTerm(); - field = t.field(); - searchTerm = t.text(); + switch (query) { + case TermQuery tq -> { + Term t = tq.getTerm(); + field = t.field(); + searchTerm = t.text(); + } + case PrefixQuery pq -> { + Term t = pq.getPrefix(); + field = t.field(); + searchTerm = t.text(); + } + case WildcardQuery wq -> { + Term t = wq.getTerm(); + field = t.field(); + searchTerm = t.text(); + } + default -> {} } if (field == null || FIELD_DOC_ID.equals(field) || FIELD_NODE_ID.equals(field) || FIELD_ID.equals(field) || FIELD_ADDRESS.equals(field)) { return; @@ -1079,8 +1069,8 @@ public void endElement(Txn transaction, ElementImpl element, NodePath path) { boolean match = configuration.match(path); if (match) { final TextCollector collector = contentStack.pop(); - match = collector instanceof ComplexTextCollector - ? match && ((ComplexTextCollector)collector).getConfig().matchConditions(element) + match = collector instanceof ComplexTextCollector ctc + ? match && ctc.getConfig().matchConditions(element) : match; if (match) indexText(element, element.getQName(), path, configuration, collector); } diff --git a/extensions/indexes/range/src/main/java/org/exist/indexing/range/conversion/DateConverter.java b/extensions/indexes/range/src/main/java/org/exist/indexing/range/conversion/DateConverter.java index dd4430ddeed..059100ebd2c 100644 --- a/extensions/indexes/range/src/main/java/org/exist/indexing/range/conversion/DateConverter.java +++ b/extensions/indexes/range/src/main/java/org/exist/indexing/range/conversion/DateConverter.java @@ -61,7 +61,7 @@ public Field toField(String fieldName, String content) { if (matcher.matches()) { try { int year = Integer.parseInt(matcher.group(1)); - content = (year < 0 ? "-" : "") + String.format("%04d-%02d-%02d", Math.abs(year), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3))); + content = (year < 0 ? "-" : "") + "%04d-%02d-%02d".formatted(Math.abs(year), Integer.parseInt(matcher.group(2)), Integer.parseInt(matcher.group(3))); } catch (NumberFormatException e) { // invalid content: ignore } diff --git a/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/Lookup.java b/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/Lookup.java index 425153fbd98..629a3710116 100644 --- a/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/Lookup.java +++ b/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/Lookup.java @@ -219,7 +219,7 @@ public void setFallback(@Nullable Expression expression, final int optimizeAxis) public void setArguments(List arguments) throws XPathException { steps.clear(); - Expression path = arguments.get(0); + Expression path = arguments.getFirst(); steps.add(path); Expression arg = arguments.get(1).simplify(); diff --git a/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/OptimizeFieldPragma.java b/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/OptimizeFieldPragma.java index bd43e76e088..9b5ec788a81 100644 --- a/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/OptimizeFieldPragma.java +++ b/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/OptimizeFieldPragma.java @@ -259,7 +259,7 @@ private static boolean isInsideFtQuery(final Expression expr) { final SequenceConstructor arg1 = new SequenceConstructor(context); mergedArgs.add(arg1); for (final List args : predicateArgs.values()) { - arg0.add(args.get(0)); + arg0.add(args.getFirst()); arg1.add(args.get(1)); mergedArgs.addAll(args.subList(2, args.size())); } @@ -283,8 +283,8 @@ private static boolean isInsideFtQuery(final Expression expr) { } private @Nullable Expression getKeyArg(final Expression expression) { - if (expression instanceof GeneralComparison) { - return ((GeneralComparison) expression).getRight(); + if (expression instanceof GeneralComparison comparison) { + return comparison.getRight(); } else if (expression instanceof InternalFunctionCall fcall) { final Function function = fcall.getFunction(); if (function instanceof Lookup) { diff --git a/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/RangeQueryRewriter.java b/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/RangeQueryRewriter.java index 2f3c052e885..2555af0f352 100644 --- a/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/RangeQueryRewriter.java +++ b/extensions/indexes/range/src/main/java/org/exist/xquery/modules/range/RangeQueryRewriter.java @@ -163,8 +163,8 @@ public Pragma rewriteLocationStep(final LocationStep locationStep) throws XPathE } if (argCount == 3) { final Expression flagsExpr = funMatches.getArgument(2); - if (flagsExpr instanceof LiteralValue) { - final String flags = ((LiteralValue) flagsExpr).getValue().getStringValue(); + if (flagsExpr instanceof LiteralValue value) { + final String flags = value.getValue().getStringValue(); for (int i = 0; i < flags.length(); i++) { if (flags.charAt(i) != 'i') { return null; @@ -206,11 +206,11 @@ protected static List getStepsToOptimize(Expression expr) { if (function instanceof org.exist.xquery.functions.fn.FunMatches funMatches) { return BasicExpressionVisitor.findLocationSteps(funMatches.getArgument(0)); } - if (function instanceof Lookup) { + if (function instanceof Lookup lookup) { if (function.isCalledAs("matches")) { return BasicExpressionVisitor.findLocationSteps(function.getArgument(0)); } else { - Expression original = ((Lookup)function).getFallback(); + Expression original = lookup.getFallback(); return getStepsToOptimize(original); } } diff --git a/extensions/indexes/range/src/test/java/org/exist/xquery/modules/range/Issue4074IndexKeysServletContextTest.java b/extensions/indexes/range/src/test/java/org/exist/xquery/modules/range/Issue4074IndexKeysServletContextTest.java index 2e41a7f2390..dc9ef63a5e8 100644 --- a/extensions/indexes/range/src/test/java/org/exist/xquery/modules/range/Issue4074IndexKeysServletContextTest.java +++ b/extensions/indexes/range/src/test/java/org/exist/xquery/modules/range/Issue4074IndexKeysServletContextTest.java @@ -88,9 +88,10 @@ public class Issue4074IndexKeysServletContextTest { + ""; private static final String INDEX_KEYS_QUERY = - "import module namespace range = \"http://exist-db.org/xquery/range\" " - + "at \"java:org.exist.xquery.modules.range.RangeIndexModule\";\n" - + "range:index-keys-for-field(\"elem-field\", function($key, $nums) { $key }, 100)"; + """ + import module namespace range = "http://exist-db.org/xquery/range" \ + at "java:org.exist.xquery.modules.range.RangeIndexModule"; + range:index-keys-for-field("elem-field", function($key, $nums) { $key }, 100)"""; @ClassRule public static final ExistEmbeddedServer existEmbeddedServer = new ExistEmbeddedServer(true, true); diff --git a/extensions/indexes/spatial/src/main/java/org/exist/indexing/spatial/SpatialIndexException.java b/extensions/indexes/spatial/src/main/java/org/exist/indexing/spatial/SpatialIndexException.java index 1fcaac84d56..54d23032fd3 100644 --- a/extensions/indexes/spatial/src/main/java/org/exist/indexing/spatial/SpatialIndexException.java +++ b/extensions/indexes/spatial/src/main/java/org/exist/indexing/spatial/SpatialIndexException.java @@ -21,11 +21,14 @@ */ package org.exist.indexing.spatial; +import java.io.Serial; + /** * @author
Pierrick Brihaye */ public class SpatialIndexException extends Exception { + @Serial private static final long serialVersionUID = 7991787594779565819L; SpatialIndexException(final String message) { diff --git a/extensions/indexes/spatial/src/test/java/org/exist/indexing/spatial/GMLIndexTest.java b/extensions/indexes/spatial/src/test/java/org/exist/indexing/spatial/GMLIndexTest.java index bedd0c0f03b..82931fc5d34 100644 --- a/extensions/indexes/spatial/src/test/java/org/exist/indexing/spatial/GMLIndexTest.java +++ b/extensions/indexes/spatial/src/test/java/org/exist/indexing/spatial/GMLIndexTest.java @@ -25,7 +25,7 @@ import java.io.StringReader; import java.net.URISyntaxException; import java.net.URL; -import java.nio.file.Paths; +import java.nio.file.Path; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @@ -121,7 +121,7 @@ public static void setup() throws EXistException, PermissionDeniedException, IOE for (final String file : FILES) { final URL url = GMLIndexTest.class.getResource("/" + file); - broker.storeDocument(transaction, XmldbURI.create(file), new FileInputSource(Paths.get(url.toURI())), MimeType.XML_TYPE, testCollection); + broker.storeDocument(transaction, XmldbURI.create(file), new FileInputSource(Path.of(url.toURI())), MimeType.XML_TYPE, testCollection); } transaction.commit(); diff --git a/extensions/indexes/vector-it/src/test/java/xquery/lucene/VectorSearchEmbeddingIT.java b/extensions/indexes/vector-it/src/test/java/xquery/lucene/VectorSearchEmbeddingIT.java index c3247a058b9..0abe27f2369 100644 --- a/extensions/indexes/vector-it/src/test/java/xquery/lucene/VectorSearchEmbeddingIT.java +++ b/extensions/indexes/vector-it/src/test/java/xquery/lucene/VectorSearchEmbeddingIT.java @@ -37,7 +37,6 @@ import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Optional; import static org.junit.Assert.assertEquals; @@ -133,9 +132,10 @@ public void embedBatchReturnsTwoArrays() throws XPathException, PermissionDenied public void diagnosticsReportsModel() throws XPathException, PermissionDeniedException, EXistException { setupDefaultCollection(); final Sequence result = executeQuery( - "xquery version \"3.1\";\n" - + "import module namespace vector=\"http://exist-db.org/xquery/vector\";\n" - + "count(vector:diagnostics())"); + """ + xquery version "3.1"; + import module namespace vector="http://exist-db.org/xquery/vector"; + count(vector:diagnostics())"""); assertTrue("diagnostics should return at least one entry", result.itemAt(0).toJavaObject(Integer.class).intValue() >= 1); } @@ -311,7 +311,7 @@ private Sequence executeQuery(final String query) throws EXistException, Permiss private boolean hasEmbeddingModel() { final Path base = ConfigurationHelper.getExistHome() - .orElse(Paths.get(System.getProperty("user.dir", "."))); + .orElse(Path.of(System.getProperty("user.dir", "."))); final Path modelDir = base.resolve("target/onnx-models/all-MiniLM-L6-v2"); return Files.isRegularFile(modelDir.resolve("model.onnx")) && Files.isRegularFile(modelDir.resolve("tokenizer.json")); diff --git a/extensions/modules/cache/src/main/java/org/exist/xquery/modules/cache/CacheFunctions.java b/extensions/modules/cache/src/main/java/org/exist/xquery/modules/cache/CacheFunctions.java index c1679622896..08c6876f504 100644 --- a/extensions/modules/cache/src/main/java/org/exist/xquery/modules/cache/CacheFunctions.java +++ b/extensions/modules/cache/src/main/java/org/exist/xquery/modules/cache/CacheFunctions.java @@ -305,7 +305,7 @@ private void lazilyCreateCache(final String cacheName) throws XPathException { final CacheModule cacheModule = (CacheModule) getParentModule(); final Optional maybeLazyCacheConfig = cacheModule.getLazyCacheConfig(); - if (!maybeLazyCacheConfig.isPresent()) { + if (maybeLazyCacheConfig.isEmpty()) { throw new XPathException(this, LAZY_CREATION_DISABLED, "There is no such named cache: " + cacheName + ", and lazy creation of the cache has been disabled."); } diff --git a/extensions/modules/cache/src/test/java/org/exist/xquery/modules/cache/LazyCacheTest.java b/extensions/modules/cache/src/test/java/org/exist/xquery/modules/cache/LazyCacheTest.java index c712bfb261a..d18d541b48a 100644 --- a/extensions/modules/cache/src/test/java/org/exist/xquery/modules/cache/LazyCacheTest.java +++ b/extensions/modules/cache/src/test/java/org/exist/xquery/modules/cache/LazyCacheTest.java @@ -34,7 +34,6 @@ import java.net.URISyntaxException; import java.nio.file.Path; -import java.nio.file.Paths; import static org.junit.Assert.*; @@ -42,7 +41,7 @@ public class LazyCacheTest { private static Path getLazyConfig() { try { - return Paths.get(LazyCacheTest.class.getResource("/lazy-cache-conf.xml").toURI()); + return Path.of(LazyCacheTest.class.getResource("/lazy-cache-conf.xml").toURI()); } catch (final URISyntaxException e) { throw new IllegalStateException("Unable to find: lazy-cache-conf.xml"); } diff --git a/extensions/modules/cache/src/test/java/org/exist/xquery/modules/cache/NonLazyCacheTest.java b/extensions/modules/cache/src/test/java/org/exist/xquery/modules/cache/NonLazyCacheTest.java index f2e33d1dd29..474616a07ca 100644 --- a/extensions/modules/cache/src/test/java/org/exist/xquery/modules/cache/NonLazyCacheTest.java +++ b/extensions/modules/cache/src/test/java/org/exist/xquery/modules/cache/NonLazyCacheTest.java @@ -35,7 +35,6 @@ import java.net.URISyntaxException; import java.nio.file.Path; -import java.nio.file.Paths; import static org.junit.Assert.*; @@ -43,7 +42,7 @@ public class NonLazyCacheTest { private static Path getLazyConfig() { try { - return Paths.get(NonLazyCacheTest.class.getResource("/non-lazy-cache-conf.xml").toURI()); + return Path.of(NonLazyCacheTest.class.getResource("/non-lazy-cache-conf.xml").toURI()); } catch (final URISyntaxException e) { throw new IllegalStateException("Unable to find: non-lazy-cache-conf.xml"); } diff --git a/extensions/modules/compression/src/main/java/org/exist/xquery/modules/compression/AbstractCompressFunction.java b/extensions/modules/compression/src/main/java/org/exist/xquery/modules/compression/AbstractCompressFunction.java index 0a675acb204..178f8e76292 100644 --- a/extensions/modules/compression/src/main/java/org/exist/xquery/modules/compression/AbstractCompressFunction.java +++ b/extensions/modules/compression/src/main/java/org/exist/xquery/modules/compression/AbstractCompressFunction.java @@ -70,7 +70,6 @@ import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Iterator; import java.util.zip.CRC32; import java.util.zip.DeflaterOutputStream; @@ -175,7 +174,7 @@ private void compressFromUri(final OutputStream os, final URI uri, final boolean } // got a file - final Path file = Paths.get(uri.getPath()); + final Path file = Path.of(uri.getPath()); compressFile(os, file, useHierarchy, stripOffset, method, resourceName); } else { diff --git a/extensions/modules/compression/src/main/java/org/exist/xquery/modules/compression/EntryFunctions.java b/extensions/modules/compression/src/main/java/org/exist/xquery/modules/compression/EntryFunctions.java index 646ccce57a7..45b04e621e5 100644 --- a/extensions/modules/compression/src/main/java/org/exist/xquery/modules/compression/EntryFunctions.java +++ b/extensions/modules/compression/src/main/java/org/exist/xquery/modules/compression/EntryFunctions.java @@ -58,7 +58,6 @@ import java.net.URI; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Optional; diff --git a/extensions/modules/expathrepo/expathrepo-trigger-test/src/test/java/org/exist/repo/ExampleModuleTest.java b/extensions/modules/expathrepo/expathrepo-trigger-test/src/test/java/org/exist/repo/ExampleModuleTest.java index 56c7b17a843..22da336bab1 100644 --- a/extensions/modules/expathrepo/expathrepo-trigger-test/src/test/java/org/exist/repo/ExampleModuleTest.java +++ b/extensions/modules/expathrepo/expathrepo-trigger-test/src/test/java/org/exist/repo/ExampleModuleTest.java @@ -53,8 +53,9 @@ public class ExampleModuleTest { @Test public void helloWorld() throws XPathException, PermissionDeniedException, EXistException { final String query = - "declare namespace myjmod = \"https://my-organisation.com/exist-db/ns/app/my-java-module\";\n" + - "myjmod:hello-world()"; + """ + declare namespace myjmod = "https://my-organisation.com/exist-db/ns/app/my-java-module"; + myjmod:hello-world()"""; final Sequence result = executeQuery(query); assertTrue(result.hasOne()); @@ -73,8 +74,9 @@ public void helloWorld() throws XPathException, PermissionDeniedException, EXist @Test public void sayHello() throws XPathException, PermissionDeniedException, EXistException { final String query = - "declare namespace myjmod = \"https://my-organisation.com/exist-db/ns/app/my-java-module\";\n" + - "myjmod:say-hello('Adam')"; + """ + declare namespace myjmod = "https://my-organisation.com/exist-db/ns/app/my-java-module"; + myjmod:say-hello('Adam')"""; final Sequence result = executeQuery(query); assertTrue(result.hasOne()); @@ -93,8 +95,9 @@ public void sayHello() throws XPathException, PermissionDeniedException, EXistEx @Test public void sayHello_noName() throws XPathException, PermissionDeniedException, EXistException { final String query = - "declare namespace myjmod = \"https://my-organisation.com/exist-db/ns/app/my-java-module\";\n" + - "myjmod:say-hello(())"; + """ + declare namespace myjmod = "https://my-organisation.com/exist-db/ns/app/my-java-module"; + myjmod:say-hello(())"""; final Sequence result = executeQuery(query); assertTrue(result.hasOne()); @@ -113,8 +116,9 @@ public void sayHello_noName() throws XPathException, PermissionDeniedException, @Test public void add() throws XPathException, PermissionDeniedException, EXistException { final String query = - "declare namespace myjmod = \"https://my-organisation.com/exist-db/ns/app/my-java-module\";\n" + - "myjmod:add(xs:int(123), xs:int(456))"; + """ + declare namespace myjmod = "https://my-organisation.com/exist-db/ns/app/my-java-module"; + myjmod:add(xs:int(123), xs:int(456))"""; final Sequence result = executeQuery(query); assertTrue(result.hasOne()); diff --git a/extensions/modules/expathrepo/src/test/java/org/exist/repo/PackageTriggerIT.java b/extensions/modules/expathrepo/src/test/java/org/exist/repo/PackageTriggerIT.java index 8ba03ac002c..d8e42d5b6a9 100644 --- a/extensions/modules/expathrepo/src/test/java/org/exist/repo/PackageTriggerIT.java +++ b/extensions/modules/expathrepo/src/test/java/org/exist/repo/PackageTriggerIT.java @@ -48,7 +48,6 @@ import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.io.IOException; import java.util.Optional; @@ -70,7 +69,7 @@ private static java.util.function.Supplier resolveXarSupplier() { return () -> PackageTriggerIT.class.getResourceAsStream("/" + xarFile); } // 2) Try from sibling module build output - final Path relPath = Paths.get("extensions/modules/expathrepo/expathrepo-trigger-test/target", xarFile); + final Path relPath = Path.of("extensions/modules/expathrepo/expathrepo-trigger-test/target", xarFile); if (Files.exists(relPath)) { return () -> { try { @@ -81,7 +80,7 @@ private static java.util.function.Supplier resolveXarSupplier() { }; } // 3) Try from current module generated-test-resources (in case direct run already copied it) - final Path generated = Paths.get("extensions/modules/expathrepo/target/generated-test-resources", xarFile); + final Path generated = Path.of("extensions/modules/expathrepo/target/generated-test-resources", xarFile); if (Files.exists(generated)) { return () -> { try { diff --git a/extensions/modules/file/src/main/java/org/exist/xquery/modules/file/DirectoryList.java b/extensions/modules/file/src/main/java/org/exist/xquery/modules/file/DirectoryList.java index 10893583c83..090cf934fc1 100644 --- a/extensions/modules/file/src/main/java/org/exist/xquery/modules/file/DirectoryList.java +++ b/extensions/modules/file/src/main/java/org/exist/xquery/modules/file/DirectoryList.java @@ -64,12 +64,15 @@ public class DirectoryList extends BasicFunction { public static final FunctionSignature[] signatures = { new FunctionSignature( new QName("directory-list", NAMESPACE_URI, PREFIX), - "List all files, including their file size and modification time, " - + "found in or below a directory, $directory. Files are located in the server's " - + "file system, using filename patterns, $pattern. File pattern matching is based " - + "on code from Apache's Ant, thus following the same conventions. For example:\n\n" - + "'*.xml' matches any file ending with .xml in the current directory,\n- '**/*.xml' matches files " - + "in any directory below the specified directory. This method is only available to the DBA role.", + """ + List all files, including their file size and modification time, \ + found in or below a directory, $directory. Files are located in the server's \ + file system, using filename patterns, $pattern. File pattern matching is based \ + on code from Apache's Ant, thus following the same conventions. For example: + + '*.xml' matches any file ending with .xml in the current directory, + - '**/*.xml' matches files \ + in any directory below the specified directory. This method is only available to the DBA role.""", new SequenceType[]{ new FunctionParameterSequenceType("path", Type.ITEM, Cardinality.EXACTLY_ONE, "The base directory path or URI in the file system where the files are located."), diff --git a/extensions/modules/file/src/main/java/org/exist/xquery/modules/file/FileModuleHelper.java b/extensions/modules/file/src/main/java/org/exist/xquery/modules/file/FileModuleHelper.java index df5f37c82f2..902a609d67d 100644 --- a/extensions/modules/file/src/main/java/org/exist/xquery/modules/file/FileModuleHelper.java +++ b/extensions/modules/file/src/main/java/org/exist/xquery/modules/file/FileModuleHelper.java @@ -23,7 +23,6 @@ import java.net.URI; import java.nio.file.Path; -import java.nio.file.Paths; import org.exist.xquery.Expression; import org.exist.xquery.XPathException; @@ -51,12 +50,12 @@ private FileModuleHelper() { public static Path getFile(String path, final Expression expression) throws XPathException { if(path.startsWith("file:")){ try { - return Paths.get(new URI(path)); + return Path.of(new URI(path)); } catch (Exception ex) { // catch all (URISyntaxException) throw new XPathException(expression, path + " is not a valid URI: '"+ ex.getMessage() +"'"); } } else { - return Paths.get(path); + return Path.of(path); } } diff --git a/extensions/modules/image/src/main/java/org/exist/xquery/modules/image/CropFunction.java b/extensions/modules/image/src/main/java/org/exist/xquery/modules/image/CropFunction.java index 6f3a1a1cba0..b2c2b9f151f 100644 --- a/extensions/modules/image/src/main/java/org/exist/xquery/modules/image/CropFunction.java +++ b/extensions/modules/image/src/main/java/org/exist/xquery/modules/image/CropFunction.java @@ -156,9 +156,9 @@ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathExce //crop the image Image cropImage = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), new CropImageFilter(x1, y1, width, height))); - if(cropImage instanceof BufferedImage) { + if(cropImage instanceof BufferedImage bufferedImage) { // just in case cropImage is allready an BufferedImage - bImage = (BufferedImage)cropImage; + bImage = bufferedImage; } else { bImage = new BufferedImage(cropImage.getWidth(null), diff --git a/extensions/modules/image/src/main/java/org/exist/xquery/modules/image/GetThumbnailsFunction.java b/extensions/modules/image/src/main/java/org/exist/xquery/modules/image/GetThumbnailsFunction.java index 4cb91f1480e..80878c27be6 100644 --- a/extensions/modules/image/src/main/java/org/exist/xquery/modules/image/GetThumbnailsFunction.java +++ b/extensions/modules/image/src/main/java/org/exist/xquery/modules/image/GetThumbnailsFunction.java @@ -31,7 +31,6 @@ import java.net.URISyntaxException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Iterator; import java.util.List; import java.util.Optional; @@ -198,7 +197,7 @@ public Sequence eval(Sequence[] args, Sequence contextSequence) throw new XPathException(this, e.getMessage()); } } else { - thumbDir = Paths.get(thumbPath.toString()); + thumbDir = Path.of(thumbPath.toString()); if (!Files.isDirectory(thumbDir)) try { Files.createDirectories(thumbDir); @@ -293,7 +292,7 @@ public Sequence eval(Sequence[] args, Sequence contextSequence) .write( bImage, "jpg", - Paths.get(thumbPath + Path.of(thumbPath + "/" + prefix + docImage.getFileURI()).toFile()); } catch (Exception e) { @@ -349,4 +348,4 @@ private boolean fileExist(List cols, DocumentImpl file, String prefix) { return false; } -} \ No newline at end of file +} diff --git a/extensions/modules/mail/src/main/java/org/exist/xquery/modules/mail/MessageFunctions.java b/extensions/modules/mail/src/main/java/org/exist/xquery/modules/mail/MessageFunctions.java index 581fafc0e17..b8fea546443 100644 --- a/extensions/modules/mail/src/main/java/org/exist/xquery/modules/mail/MessageFunctions.java +++ b/extensions/modules/mail/src/main/java/org/exist/xquery/modules/mail/MessageFunctions.java @@ -202,8 +202,8 @@ private Sequence getMessages(Sequence[] args, Sequence contextSequence) throws X // Handle the content Object content = message.getContent(); - if (content instanceof Multipart) { - handleMultipart((Multipart) content, builder); + if (content instanceof Multipart multipart) { + handleMultipart(multipart, builder); } else { handlePart(message, builder); } @@ -314,8 +314,8 @@ private void mimeParamsToAttributes(MemTreeBuilder builder, String contentType) private void handlePart(Part part, MemTreeBuilder builder) throws MessagingException, IOException, XPathException, SAXException { Object content = part.getContent(); - if (content instanceof Multipart) { - handleMultipart((Multipart)content, builder); + if (content instanceof Multipart multipart) { + handleMultipart(multipart, builder); return; } String disposition = part.getDisposition(); diff --git a/extensions/modules/mail/src/main/java/org/exist/xquery/modules/mail/SendEmailFunction.java b/extensions/modules/mail/src/main/java/org/exist/xquery/modules/mail/SendEmailFunction.java index ee7b15e4095..fd7ac27b2d7 100644 --- a/extensions/modules/mail/src/main/java/org/exist/xquery/modules/mail/SendEmailFunction.java +++ b/extensions/modules/mail/src/main/java/org/exist/xquery/modules/mail/SendEmailFunction.java @@ -242,7 +242,7 @@ private boolean sendBySendmail(final Mail mail, final String charset) { try { //Create a sendmail Process - final Process p = Runtime.getRuntime().exec("/usr/sbin/sendmail" + recipients); + final Process p = Runtime.getRuntime().exec(("/usr/sbin/sendmail" + recipients).split(" ")); //Get a Buffered Print Writer to the Processes stdOut try (final PrintWriter out = new PrintWriter(new OutputStreamWriter(p.getOutputStream(), charset))) { diff --git a/extensions/modules/process/src/main/java/org/exist/xquery/modules/process/Execute.java b/extensions/modules/process/src/main/java/org/exist/xquery/modules/process/Execute.java index 4df7edf385d..b2493693fec 100644 --- a/extensions/modules/process/src/main/java/org/exist/xquery/modules/process/Execute.java +++ b/extensions/modules/process/src/main/java/org/exist/xquery/modules/process/Execute.java @@ -37,7 +37,6 @@ import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; public class Execute extends BasicFunction { @@ -148,7 +147,7 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence) thro } private Path getWorkingDir(String arg) { - final Path file = Paths.get(arg); + final Path file = Path.of(arg); if (file.isAbsolute()) { return file; } diff --git a/extensions/modules/sql/src/main/java/org/exist/xquery/modules/sql/ExecuteFunction.java b/extensions/modules/sql/src/main/java/org/exist/xquery/modules/sql/ExecuteFunction.java index fde66a86276..a5ee8281c85 100644 --- a/extensions/modules/sql/src/main/java/org/exist/xquery/modules/sql/ExecuteFunction.java +++ b/extensions/modules/sql/src/main/java/org/exist/xquery/modules/sql/ExecuteFunction.java @@ -293,8 +293,8 @@ private void setParametersOnPreparedStatement(final Statement stmt, final Elemen final String value; if (child != null) { - if (child instanceof ReferenceNode) { - child = ((ReferenceNode) child).getReference().getNode(); + if (child instanceof ReferenceNode node) { + child = node.getReference().getNode(); } if (child instanceof Element elem) { diff --git a/extensions/modules/sql/src/main/java/org/exist/xquery/modules/sql/SQLModule.java b/extensions/modules/sql/src/main/java/org/exist/xquery/modules/sql/SQLModule.java index 38ca38e4c8a..0cfa49e2dae 100644 --- a/extensions/modules/sql/src/main/java/org/exist/xquery/modules/sql/SQLModule.java +++ b/extensions/modules/sql/src/main/java/org/exist/xquery/modules/sql/SQLModule.java @@ -104,7 +104,7 @@ public SQLModule(final Map> parameters) { if (poolName != null && !poolName.isEmpty()) { if (!CONNECTION_POOLS.containsKey(poolName)) { - final Properties poolProperties = new Properties();; + final Properties poolProperties = new Properties(); poolProperties.setProperty("poolName", poolName); final String poolPropertiesPrefix = poolId + ".properties."; diff --git a/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ConnectionIT.java b/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ConnectionIT.java index 5c34203313c..5b75e1521f5 100644 --- a/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ConnectionIT.java +++ b/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ConnectionIT.java @@ -125,8 +125,9 @@ public void getConnectionFromModuleIsAutomaticallyClosed() throws EXistException "};\n"; final String mainQuery = - "import module namespace mymodule = \"http://mymodule.com\" at \"xmldb:exist:///db/mymodule.xqm\";\n" + - "mymodule:get-handle()"; + """ + import module namespace mymodule = "http://mymodule.com" at "xmldb:exist:///db/mymodule.xqm"; + mymodule:get-handle()"""; final Source mainQuerySource = new StringSource(mainQuery); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); diff --git a/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ConnectionPoolIT.java b/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ConnectionPoolIT.java index 0a6930d71c3..a8b9a05f30b 100644 --- a/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ConnectionPoolIT.java +++ b/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ConnectionPoolIT.java @@ -67,8 +67,9 @@ public class ConnectionPoolIT { public void getConnectionFromPoolIsAutomaticallyClosed() throws EXistException, XPathException, PermissionDeniedException, IOException { // NOTE: pool-1 is configured in src/test/resources-filtered/conf.xml final String mainQuery = - "import module namespace sql = \"http://exist-db.org/xquery/sql\";\n" + - "sql:get-connection-from-pool(\"pool-1\")"; + """ + import module namespace sql = "http://exist-db.org/xquery/sql"; + sql:get-connection-from-pool("pool-1")"""; final Source mainQuerySource = new StringSource(mainQuery); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); diff --git a/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ImplicitConnectionCloseIT.java b/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ImplicitConnectionCloseIT.java index 32ea3098fdd..3eecbd8de4e 100644 --- a/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ImplicitConnectionCloseIT.java +++ b/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/ImplicitConnectionCloseIT.java @@ -179,8 +179,9 @@ public void getJndiConnectionFromModuleIsAutomaticallyClosed() throws EXistExcep "};\n"; final String mainQuery = - "import module namespace mymodule = \"http://mymodule.com\" at \"xmldb:exist:///db/mymodule.xqm\";\n" + - "mymodule:get-handle()"; + """ + import module namespace mymodule = "http://mymodule.com" at "xmldb:exist:///db/mymodule.xqm"; + mymodule:get-handle()"""; final Source mainQuerySource = new StringSource(mainQuery); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); diff --git a/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/JndiConnectionIT.java b/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/JndiConnectionIT.java index dbe2d49eb58..5fdb34caf6d 100644 --- a/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/JndiConnectionIT.java +++ b/extensions/modules/sql/src/test/java/org/exist/xquery/modules/sql/JndiConnectionIT.java @@ -159,8 +159,9 @@ public void getJndiConnectionFromModuleIsAutomaticallyClosed() throws EXistExcep "};\n"; final String mainQuery = - "import module namespace mymodule = \"http://mymodule.com\" at \"xmldb:exist:///db/mymodule.xqm\";\n" + - "mymodule:get-handle()"; + """ + import module namespace mymodule = "http://mymodule.com" at "xmldb:exist:///db/mymodule.xqm"; + mymodule:get-handle()"""; final Source mainQuerySource = new StringSource(mainQuery); final BrokerPool pool = existEmbeddedServer.getBrokerPool(); diff --git a/extensions/modules/xmldiff/src/main/java/org/exist/xquery/modules/xmldiff/Compare.java b/extensions/modules/xmldiff/src/main/java/org/exist/xquery/modules/xmldiff/Compare.java index 7f35fa2889a..8c8f045f498 100644 --- a/extensions/modules/xmldiff/src/main/java/org/exist/xquery/modules/xmldiff/Compare.java +++ b/extensions/modules/xmldiff/src/main/java/org/exist/xquery/modules/xmldiff/Compare.java @@ -165,12 +165,12 @@ private MapType falseMapResult(final int sequencePosition, final String message) } private static @Nullable Node toNode(final Item item) { - if (item instanceof Node) { - return (Node) item; + if (item instanceof Node node) { + return node; } - if (item instanceof NodeProxy) { - return ((NodeProxy) item).getNode(); + if (item instanceof NodeProxy proxy) { + return proxy.getNode(); } return null; diff --git a/extensions/modules/xslfo/src/test/java/org/exist/xquery/modules/xslfo/ApacheFopTest.java b/extensions/modules/xslfo/src/test/java/org/exist/xquery/modules/xslfo/ApacheFopTest.java index 1d6564911d5..236d5853177 100644 --- a/extensions/modules/xslfo/src/test/java/org/exist/xquery/modules/xslfo/ApacheFopTest.java +++ b/extensions/modules/xslfo/src/test/java/org/exist/xquery/modules/xslfo/ApacheFopTest.java @@ -45,45 +45,47 @@ public class ApacheFopTest { @Test public void simplePdf() throws EXistException, PermissionDeniedException, XPathException { final String fopConfig = - "\n" + - " true\n" + - " false\n" + - " ./\n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + true + false + ./ + + + + """; final String fo = - "\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - " Hello World!\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " \n" + - ""; + """ + + + + + + + + + + + + + + + + + + + + + + + Hello World! + + + + + + """; final String xquery = "xquery version \"3.1\";\n" + diff --git a/extensions/security/iprange/src/main/java/org/exist/security/realm/iprange/IPRangeServlet.java b/extensions/security/iprange/src/main/java/org/exist/security/realm/iprange/IPRangeServlet.java index 16e73a243e0..fbcd41ad95b 100644 --- a/extensions/security/iprange/src/main/java/org/exist/security/realm/iprange/IPRangeServlet.java +++ b/extensions/security/iprange/src/main/java/org/exist/security/realm/iprange/IPRangeServlet.java @@ -37,6 +37,7 @@ import jakarta.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; +import java.io.Serial; /** * IPRange authenticator servlet. @@ -46,6 +47,7 @@ public class IPRangeServlet extends HttpServlet implements ExistExtensionServlet { protected final static Logger LOG = LogManager.getLogger(IPRangeServlet.class); + @Serial private static final long serialVersionUID = -568037449837549034L; @Override diff --git a/extensions/vector/src/main/java/org/exist/vector/HttpVectorProvider.java b/extensions/vector/src/main/java/org/exist/vector/HttpVectorProvider.java index 34193e65228..6fb065239fc 100644 --- a/extensions/vector/src/main/java/org/exist/vector/HttpVectorProvider.java +++ b/extensions/vector/src/main/java/org/exist/vector/HttpVectorProvider.java @@ -96,14 +96,11 @@ public float[] embed(final String text, final boolean forQuery) { return null; } try { - switch (apiType) { - case OPENAI: - return embedOpenAI(text); - case COHERE: - return embedCohere(text, forQuery); - default: - return null; - } + return switch (apiType) { + case OPENAI -> embedOpenAI(text); + case COHERE -> embedCohere(text, forQuery); + default -> null; + }; } catch (final Exception e) { LOG.warn("HTTP embedding failed for {}: {}", modelId, e.getMessage()); return null; diff --git a/extensions/vector/src/main/java/org/exist/vector/ModelPathResolver.java b/extensions/vector/src/main/java/org/exist/vector/ModelPathResolver.java index ca0a34ee26b..809bb4f606a 100644 --- a/extensions/vector/src/main/java/org/exist/vector/ModelPathResolver.java +++ b/extensions/vector/src/main/java/org/exist/vector/ModelPathResolver.java @@ -33,7 +33,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Optional; @@ -61,7 +60,7 @@ private ModelPathResolver() { @Nonnull static Path getVectorBase() { final Optional home = ConfigurationHelper.getExistHome(); - return home.orElse(Paths.get(System.getProperty("user.dir", "."))).normalize().toAbsolutePath(); + return home.orElse(Path.of(System.getProperty("user.dir", "."))).normalize().toAbsolutePath(); } /** diff --git a/extensions/vector/src/main/java/org/exist/vector/ModelRegistry.java b/extensions/vector/src/main/java/org/exist/vector/ModelRegistry.java index bb7561f9dc7..68a7f01c831 100644 --- a/extensions/vector/src/main/java/org/exist/vector/ModelRegistry.java +++ b/extensions/vector/src/main/java/org/exist/vector/ModelRegistry.java @@ -29,7 +29,6 @@ import javax.annotation.Nullable; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -81,7 +80,7 @@ private void load() { try { final Optional home = ConfigurationHelper.getExistHome(); final Path confFile = home.map(h -> h.resolve(CONF_XML).normalize().toAbsolutePath()) - .orElseGet(() -> Paths.get(System.getProperty("user.dir", ".")).resolve(CONF_XML).normalize().toAbsolutePath()); + .orElseGet(() -> Path.of(System.getProperty("user.dir", ".")).resolve(CONF_XML).normalize().toAbsolutePath()); if (!Files.isRegularFile(confFile) || !Files.isReadable(confFile)) { LOG.debug("conf.xml not found or not readable at {} (vector-models registry empty)", confFile); return; diff --git a/extensions/webdav/src/main/java/org/exist/webdav/ExistDocument.java b/extensions/webdav/src/main/java/org/exist/webdav/ExistDocument.java index fe30d15a591..b5736e187a9 100644 --- a/extensions/webdav/src/main/java/org/exist/webdav/ExistDocument.java +++ b/extensions/webdav/src/main/java/org/exist/webdav/ExistDocument.java @@ -178,7 +178,7 @@ public void stream(OutputStream os) throws IOException, PermissionDeniedExceptio os.flush(); } catch (SAXException e) { LOG.error(e); - throw new IOException(String.format("Error while serializing XML document: %s", e.getMessage()), e); + throw new IOException("Error while serializing XML document: %s".formatted(e.getMessage()), e); } } else { @@ -465,7 +465,7 @@ void unlock() throws PermissionDeniedException, DocumentNotLockedException, EXis final DocumentImpl document = lockedDocument.getDocument(); if (document == null) { - final String msg = String.format("No resource found for path: %s", xmldbUri); + final String msg = "No resource found for path: %s".formatted(xmldbUri); LOG.debug(msg); throw new EXistException(msg); } @@ -650,7 +650,7 @@ public LockToken refreshLock(String token) throws PermissionDeniedException, if (LOG.isDebugEnabled()) { LOG.debug("Token does not match"); } - throw new PermissionDeniedException(String.format("Token %s does not match %s", token, lockToken.getOpaqueLockToken())); + throw new PermissionDeniedException("Token %s does not match %s".formatted(token, lockToken.getOpaqueLockToken())); } lockToken.setTimeOut(LockToken.LOCK_TIMEOUT_INFINITE); diff --git a/extensions/webdav/src/main/java/org/exist/webdav/exceptions/CollectionDoesNotExistException.java b/extensions/webdav/src/main/java/org/exist/webdav/exceptions/CollectionDoesNotExistException.java index c7bc60ebd00..f8572495392 100644 --- a/extensions/webdav/src/main/java/org/exist/webdav/exceptions/CollectionDoesNotExistException.java +++ b/extensions/webdav/src/main/java/org/exist/webdav/exceptions/CollectionDoesNotExistException.java @@ -21,6 +21,8 @@ */ package org.exist.webdav.exceptions; +import java.io.Serial; + /** * Class that represents a situation that a file cannot be created because the collection * does not exist. @@ -29,6 +31,7 @@ */ public class CollectionDoesNotExistException extends EXistWebdavException { + @Serial private static final long serialVersionUID = 5754679193191561751L; public CollectionDoesNotExistException() { diff --git a/extensions/webdav/src/main/java/org/exist/webdav/exceptions/CollectionExistsException.java b/extensions/webdav/src/main/java/org/exist/webdav/exceptions/CollectionExistsException.java index 0faa3b37b0d..d0dc5291f39 100644 --- a/extensions/webdav/src/main/java/org/exist/webdav/exceptions/CollectionExistsException.java +++ b/extensions/webdav/src/main/java/org/exist/webdav/exceptions/CollectionExistsException.java @@ -21,6 +21,8 @@ */ package org.exist.webdav.exceptions; +import java.io.Serial; + /** * Class that represents a situation that a collection cannot be created because the * collection already exists. @@ -29,6 +31,7 @@ */ public class CollectionExistsException extends EXistWebdavException { + @Serial private static final long serialVersionUID = 9147649778466124318L; public CollectionExistsException() { diff --git a/extensions/webdav/src/main/java/org/exist/webdav/exceptions/DocumentAlreadyLockedException.java b/extensions/webdav/src/main/java/org/exist/webdav/exceptions/DocumentAlreadyLockedException.java index 05458a22e9e..2bfe39d917f 100644 --- a/extensions/webdav/src/main/java/org/exist/webdav/exceptions/DocumentAlreadyLockedException.java +++ b/extensions/webdav/src/main/java/org/exist/webdav/exceptions/DocumentAlreadyLockedException.java @@ -21,6 +21,8 @@ */ package org.exist.webdav.exceptions; +import java.io.Serial; + /** * Class that represents a situation that a file cannot be created because the collection * does not exist. @@ -29,6 +31,7 @@ */ public class DocumentAlreadyLockedException extends Exception { + @Serial private static final long serialVersionUID = 7229034225491130620L; public DocumentAlreadyLockedException() { diff --git a/extensions/webdav/src/main/java/org/exist/webdav/exceptions/DocumentNotLockedException.java b/extensions/webdav/src/main/java/org/exist/webdav/exceptions/DocumentNotLockedException.java index 884fa1d1e19..3ff88605862 100644 --- a/extensions/webdav/src/main/java/org/exist/webdav/exceptions/DocumentNotLockedException.java +++ b/extensions/webdav/src/main/java/org/exist/webdav/exceptions/DocumentNotLockedException.java @@ -21,6 +21,8 @@ */ package org.exist.webdav.exceptions; +import java.io.Serial; + /** * Class that represents a situation that a file cannot be created because the collection * does not exist. @@ -29,6 +31,7 @@ */ public class DocumentNotLockedException extends Exception { + @Serial private static final long serialVersionUID = -4907184035845864493L; public DocumentNotLockedException() { diff --git a/extensions/webdav/src/main/java/org/exist/webdav/exceptions/EXistWebdavException.java b/extensions/webdav/src/main/java/org/exist/webdav/exceptions/EXistWebdavException.java index 16b92230411..27ecab58d4f 100644 --- a/extensions/webdav/src/main/java/org/exist/webdav/exceptions/EXistWebdavException.java +++ b/extensions/webdav/src/main/java/org/exist/webdav/exceptions/EXistWebdavException.java @@ -21,6 +21,8 @@ */ package org.exist.webdav.exceptions; +import java.io.Serial; + /** * Class that represents a situation that a file cannot be created because the collection * does not exist. @@ -29,6 +31,7 @@ */ public class EXistWebdavException extends Exception { + @Serial private static final long serialVersionUID = 6789177932722513095L; public EXistWebdavException() { diff --git a/extensions/webdav/src/test/java/org/exist/webdav/SerializationTest.java b/extensions/webdav/src/test/java/org/exist/webdav/SerializationTest.java index 3cba7907f70..c28f55e937c 100644 --- a/extensions/webdav/src/test/java/org/exist/webdav/SerializationTest.java +++ b/extensions/webdav/src/test/java/org/exist/webdav/SerializationTest.java @@ -46,12 +46,14 @@ public class SerializationTest { private static final String XML_WITH_DOCTYPE = - "\n" + - ""; + """ + + """; private static final String XML_WITH_XMLDECL = - "\n" + - ""; + """ + + """; private static String PREV_PROPFIND_METHOD_XML_SIZE = null; diff --git a/extensions/xqdoc/src/main/java/org/exist/xqdoc/ant/XQDocTask.java b/extensions/xqdoc/src/main/java/org/exist/xqdoc/ant/XQDocTask.java index f5fab9143ad..6a630a35cd6 100644 --- a/extensions/xqdoc/src/main/java/org/exist/xqdoc/ant/XQDocTask.java +++ b/extensions/xqdoc/src/main/java/org/exist/xqdoc/ant/XQDocTask.java @@ -45,22 +45,24 @@ public class XQDocTask extends AbstractXMLDBTask { private final static String XQUERY = - "import module namespace xqdm=\"http://exist-db.org/xquery/xqdoc\";\n" + - "import module namespace xdb=\"http://exist-db.org/xquery/xmldb\";\n" + - "declare namespace xqdoc=\"http://www.xqdoc.org/1.0\"\n;" + - "declare variable $uri external;\n" + - "declare variable $name external;\n" + - "declare variable $collection external;\n" + - "declare variable $data external;\n" + - "let $xml :=\n" + - "if ($uri) then\n" + - " xqdm:scan(xs:anyURI($uri))\n" + - "else\n" + - " xqdm:scan($data, $name)\n" + - "let $moduleURI := $xml//xqdoc:module/xqdoc:uri\n" + - "let $docName := concat(util:hash($moduleURI, 'MD5'), '.xml')\n" + - "return\n" + - " xdb:store($collection, $docName, $xml, 'application/xml')"; + """ + import module namespace xqdm="http://exist-db.org/xquery/xqdoc"; + import module namespace xdb="http://exist-db.org/xquery/xmldb"; + declare namespace xqdoc="http://www.xqdoc.org/1.0" + ;\ + declare variable $uri external; + declare variable $name external; + declare variable $collection external; + declare variable $data external; + let $xml := + if ($uri) then + xqdm:scan(xs:anyURI($uri)) + else + xqdm:scan($data, $name) + let $moduleURI := $xml//xqdoc:module/xqdoc:uri + let $docName := concat(util:hash($moduleURI, 'MD5'), '.xml') + return + xdb:store($collection, $docName, $xml, 'application/xml')"""; private String moduleURI = null; private boolean createCollection = false; @@ -153,4 +155,4 @@ private byte[] read(Path file) throws BuildException { ": " + e.getMessage(), e); } } -} \ No newline at end of file +} From 5d24af59a9cb9838100418d678d222cf2636290c Mon Sep 17 00:00:00 2001 From: duncdrum Date: Tue, 31 Mar 2026 12:11:40 +0200 Subject: [PATCH 3/9] [refactor] common static analysis error mostly unsorted imports, low hanging fruit to combat linter noise --- .../java/org/exist/ant/AbstractXMLDBTask.java | 12 +- .../main/java/org/exist/ant/BackupTask.java | 4 +- .../main/java/org/exist/ant/ChmodTask.java | 4 +- .../main/java/org/exist/ant/ChownTask.java | 6 +- .../java/org/exist/ant/ListGroupsTask.java | 2 +- .../java/org/exist/ant/ListUsersTask.java | 2 +- .../java/org/exist/ant/LockResourceTask.java | 4 +- .../java/org/exist/ant/RemoveGroupTask.java | 2 +- .../java/org/exist/ant/RemoveUserTask.java | 2 +- .../main/java/org/exist/ant/RestoreTask.java | 2 +- .../src/main/java/org/exist/ant/UserTask.java | 4 +- .../java/org/exist/ant/XMLDBCopyTask.java | 8 +- .../java/org/exist/ant/XMLDBCreateTask.java | 4 +- .../java/org/exist/ant/XMLDBExistTask.java | 4 +- .../java/org/exist/ant/XMLDBExtractTask.java | 16 +- .../java/org/exist/ant/XMLDBListTask.java | 4 +- .../java/org/exist/ant/XMLDBMoveTask.java | 8 +- .../java/org/exist/ant/XMLDBRemoveTask.java | 4 +- .../java/org/exist/ant/XMLDBStoreTask.java | 37 ++- .../java/org/exist/ant/XMLDBXPathTask.java | 12 +- .../java/org/exist/ant/XMLDBXQueryTask.java | 16 +- .../java/org/exist/ant/XMLDBXUpdateTask.java | 4 +- .../exist/util/WeakLazyStripesStressTest.java | 4 +- .../storage/lock/LockTableBenchmark.java | 14 +- .../xquery/utils/StringJoinBenchmark.java | 2 +- .../exist/xquery/utils/URIUtilsBenchmark.java | 2 +- .../src/main/java/org/exist/BTreeTest.java | 8 +- .../src/main/java/org/exist/Database.java | 10 +- .../src/main/java/org/exist/Indexer.java | 90 +++--- .../main/java/org/exist/SystemProperties.java | 14 +- .../backup/AbstractBackupDescriptor.java | 6 +- .../main/java/org/exist/backup/Backup.java | 14 +- .../org/exist/backup/BackupDirectory.java | 12 +- .../java/org/exist/backup/BackupFile.java | 12 +- .../org/exist/backup/ConsistencyCheck.java | 10 +- .../backup/DescriptorResourceCounter.java | 4 +- .../java/org/exist/backup/ErrorReport.java | 50 ++-- .../main/java/org/exist/backup/ExportGUI.java | 20 +- .../java/org/exist/backup/ExportMain.java | 6 +- .../backup/FileSystemBackupDescriptor.java | 10 +- .../org/exist/backup/FileSystemWriter.java | 6 +- .../backup/GuiRestoreServiceTaskListener.java | 2 +- .../src/main/java/org/exist/backup/Main.java | 2 +- .../java/org/exist/backup/RestoreDialog.java | 12 +- .../java/org/exist/backup/SystemExport.java | 66 ++--- .../java/org/exist/backup/SystemImport.java | 4 +- .../backup/ZipArchiveBackupDescriptor.java | 2 +- .../main/java/org/exist/backup/ZipWriter.java | 10 +- .../restore/AbstractDeferredPermission.java | 14 +- .../restore/AbstractRestoreHandler.java | 18 +- .../exist/backup/restore/AppRestoreUtils.java | 6 +- .../restore/CollectionDeferredPermission.java | 2 +- .../restore/ResourceDeferredPermission.java | 2 +- .../restore/listener/LogRestoreListener.java | 4 +- .../org/exist/backup/xquery/BackupModule.java | 12 +- .../org/exist/backup/xquery/ListBackups.java | 10 +- .../exist/backup/xquery/RetrieveBackup.java | 6 +- .../exist/client/BackupContentsFilter.java | 2 +- .../exist/client/CheckboxTableCellEditor.java | 8 +- .../client/CheckboxTableCellRenderer.java | 4 +- .../java/org/exist/client/ClientFrame.java | 30 +- .../org/exist/client/CollectionXConf.java | 53 ++-- .../org/exist/client/CommandlineOptions.java | 10 +- .../org/exist/client/ConnectionDialog.java | 14 +- .../java/org/exist/client/DocumentView.java | 57 ++-- .../org/exist/client/EnterKeyAdapter.java | 6 +- .../exist/client/FavouriteConnections.java | 7 +- .../client/HighlightedTableCellRenderer.java | 19 +- .../java/org/exist/client/IndexDialog.java | 4 +- .../org/exist/client/InteractiveClient.java | 102 ++++--- .../main/java/org/exist/client/Messages.java | 2 +- .../org/exist/client/MimeTypeFileFilter.java | 13 +- .../org/exist/client/NewResourceDialog.java | 35 +-- .../java/org/exist/client/PrettyXmldbURI.java | 2 +- .../java/org/exist/client/QueryDialog.java | 70 ++--- .../org/exist/client/ResourceDescriptor.java | 10 +- .../java/org/exist/client/TriggersDialog.java | 33 +-- .../java/org/exist/client/UploadDialog.java | 18 +- .../main/java/org/exist/client/ZipFilter.java | 2 +- .../security/AccessControlEntryDialog.java | 30 +- .../exist/client/security/AclTableModel.java | 5 +- .../exist/client/security/AutoCompletion.java | 24 +- .../security/BasicPermissionsTableModel.java | 3 +- .../client/security/EditGroupDialog.java | 15 +- .../client/security/EditPropertiesDialog.java | 28 +- .../exist/client/security/EditUserDialog.java | 11 +- .../exist/client/security/FindGroupForm.java | 6 +- .../exist/client/security/FindUserForm.java | 11 +- .../exist/client/security/GroupDialog.java | 13 +- .../MemberOfGroupsListCellRenderer.java | 8 +- .../security/ReadOnlyDefaultTableModel.java | 1 - .../client/security/RegExpInputVerifier.java | 4 +- .../client/security/SortedListModel.java | 10 +- .../client/security/UmaskDocumentFilter.java | 6 +- .../exist/client/security/UmaskEditor.java | 1 - .../client/security/UmaskEditorFormatter.java | 4 +- .../client/security/UmaskSpinnerModel.java | 26 +- .../org/exist/client/security/UserDialog.java | 21 +- .../client/security/UserManagerDialog.java | 41 +-- .../tristatecheckbox/TristateCheckBox.java | 5 +- .../exist/collections/CollectionCache.java | 9 +- .../collections/CollectionConfiguration.java | 32 +- .../CollectionConfigurationManager.java | 2 +- .../org/exist/collections/CollectionURI.java | 6 +- .../java/org/exist/collections/IndexInfo.java | 10 +- .../org/exist/collections/ManagedLocks.java | 2 +- .../exist/collections/MutableCollection.java | 37 +-- .../triggers/AbstractTriggerProxy.java | 10 +- .../triggers/AbstractTriggersVisitor.java | 10 +- .../triggers/CSVExtractingTrigger.java | 17 +- .../triggers/CollectionTriggers.java | 8 +- .../triggers/DeferrableFilteringTrigger.java | 74 ++--- .../triggers/DocumentTriggers.java | 25 +- .../exist/collections/triggers/Dumper.java | 6 +- .../collections/triggers/HistoryTrigger.java | 12 +- .../collections/triggers/SAXTrigger.java | 85 +++--- .../triggers/STXTemplatesCache.java | 16 +- .../triggers/STXTransformerTrigger.java | 23 +- .../exist/collections/triggers/Trigger.java | 6 +- .../collections/triggers/TriggerProxy.java | 6 +- .../triggers/TriggerStatePerThread.java | 2 +- .../triggers/XQueryStartupTrigger.java | 18 +- .../collections/triggers/XQueryTrigger.java | 24 +- .../java/org/exist/config/Configuration.java | 10 +- .../config/ConfigurationDocumentTrigger.java | 47 ++- .../org/exist/config/ConfigurationImpl.java | 47 +-- .../java/org/exist/config/Configurator.java | 93 +++--- .../java/org/exist/config/ReferenceImpl.java | 4 +- .../org/exist/config/mapper/CallMethod.java | 20 +- .../org/exist/config/mapper/Constructor.java | 63 ++-- .../org/exist/debuggee/DebuggeeFactory.java | 5 +- .../org/exist/debuggee/DebuggeeJoint.java | 6 +- .../java/org/exist/debugger/Debugger.java | 6 +- .../org/exist/debugger/DebuggingSource.java | 6 +- .../src/main/java/org/exist/dom/QName.java | 19 +- .../dom/memtree/AbstractCharacterData.java | 12 +- .../java/org/exist/dom/memtree/AttrImpl.java | 2 +- .../org/exist/dom/memtree/DOMIndexer.java | 41 ++- .../dom/memtree/DocumentBuilderReceiver.java | 8 +- .../org/exist/dom/memtree/DocumentImpl.java | 49 ++-- .../org/exist/dom/memtree/ElementImpl.java | 19 +- .../dom/memtree/InMemoryXMLStreamReader.java | 2 +- .../org/exist/dom/memtree/MemTreeBuilder.java | 26 +- .../org/exist/dom/memtree/NamespaceNode.java | 2 +- .../java/org/exist/dom/memtree/NodeImpl.java | 15 +- .../memtree/ProcessingInstructionImpl.java | 4 +- .../org/exist/dom/memtree/SAXAdapter.java | 6 +- .../exist/dom/persistent/AVLTreeNodeSet.java | 27 +- .../dom/persistent/AbstractArrayNodeSet.java | 13 +- .../dom/persistent/AbstractCharacterData.java | 4 +- .../exist/dom/persistent/AbstractNodeSet.java | 6 +- .../org/exist/dom/persistent/AttrImpl.java | 2 +- .../exist/dom/persistent/BinaryDocument.java | 2 +- .../org/exist/dom/persistent/ContextItem.java | 2 +- .../dom/persistent/DefaultDocumentSet.java | 2 +- .../exist/dom/persistent/DocumentImpl.java | 48 +-- .../org/exist/dom/persistent/ElementImpl.java | 38 ++- .../exist/dom/persistent/ExtArrayNodeSet.java | 118 ++++---- .../org/exist/dom/persistent/LockToken.java | 2 +- .../java/org/exist/dom/persistent/Match.java | 4 +- .../org/exist/dom/persistent/NamedNode.java | 2 +- .../exist/dom/persistent/NewArrayNodeSet.java | 109 ++++--- .../org/exist/dom/persistent/NodeImpl.java | 2 +- .../org/exist/dom/persistent/NodeProxy.java | 14 +- .../exist/dom/persistent/NodeSetHelper.java | 4 +- .../persistent/ProcessingInstructionImpl.java | 4 +- .../exist/dom/persistent/SortedNodeSet.java | 4 +- .../org/exist/dom/persistent/StoredNode.java | 8 +- .../org/exist/dom/persistent/SymbolTable.java | 8 +- .../exist/dom/persistent/VirtualNodeSet.java | 27 +- .../org/exist/dom/persistent/XMLUtil.java | 18 +- .../exist/http/AuditTrailSessionListener.java | 8 +- .../main/java/org/exist/http/Descriptor.java | 28 +- .../main/java/org/exist/http/RESTServer.java | 50 ++-- .../main/java/org/exist/http/Response.java | 10 +- .../org/exist/http/SessionCountListener.java | 3 +- .../java/org/exist/http/SessionManager.java | 2 +- .../org/exist/http/filter/DumpFilter.java | 18 +- .../org/exist/http/filter/GuestFilter.java | 12 +- .../org/exist/http/filter/PathFilter.java | 12 +- .../servlets/AbstractExistHttpServlet.java | 18 +- .../exist/http/servlets/Authenticator.java | 6 +- .../http/servlets/BasicAuthenticator.java | 10 +- .../http/servlets/DigestAuthenticator.java | 20 +- .../org/exist/http/servlets/EXistServlet.java | 16 +- .../http/servlets/HttpRequestWrapper.java | 34 +-- .../http/servlets/HttpResponseWrapper.java | 4 +- .../servlets/HttpServletRequestWrapper.java | 14 +- .../http/servlets/HttpSessionWrapper.java | 1 + .../http/servlets/RedirectorServlet.java | 29 +- .../exist/http/servlets/RequestWrapper.java | 1 + .../exist/http/servlets/SessionWrapper.java | 3 +- .../exist/http/servlets/XQueryServlet.java | 53 ++-- .../org/exist/http/servlets/XSLTServlet.java | 24 +- .../http/urlrewrite/ControllerForward.java | 7 +- .../org/exist/http/urlrewrite/Forward.java | 6 +- .../org/exist/http/urlrewrite/ModuleCall.java | 8 +- .../exist/http/urlrewrite/PassThrough.java | 5 +- .../exist/http/urlrewrite/PathForward.java | 5 +- .../org/exist/http/urlrewrite/Redirect.java | 6 +- .../exist/http/urlrewrite/RewriteConfig.java | 6 +- .../org/exist/http/urlrewrite/URLRewrite.java | 22 +- .../http/urlrewrite/XQueryURLRewrite.java | 56 ++-- .../org/exist/indexing/AbstractIndex.java | 4 +- .../exist/indexing/AbstractMatchListener.java | 7 +- .../indexing/AbstractStreamListener.java | 6 +- .../org/exist/indexing/IndexController.java | 14 +- .../java/org/exist/indexing/IndexManager.java | 6 +- .../java/org/exist/indexing/IndexWorker.java | 8 +- .../org/exist/indexing/StreamListener.java | 2 +- .../org/exist/indexing/StructuralIndex.java | 6 +- .../main/java/org/exist/jetty/JettyStart.java | 22 +- .../java/org/exist/jetty/ServerShutdown.java | 3 +- .../exist/launcher/ConfigurationDialog.java | 40 +-- .../exist/launcher/ConfigurationUtility.java | 3 +- .../java/org/exist/launcher/Launcher.java | 16 +- .../org/exist/launcher/LauncherWrapper.java | 4 +- .../java/org/exist/launcher/SplashScreen.java | 9 +- .../java/org/exist/launcher/UtilityPanel.java | 8 +- .../org/exist/management/AgentFactory.java | 4 +- .../java/org/exist/management/TaskStatus.java | 15 +- .../exist/management/client/JMXClient.java | 39 +-- .../exist/management/client/JMXServlet.java | 34 +-- .../org/exist/management/client/JMXtoXML.java | 53 ++-- .../exist/management/impl/BinaryValues.java | 2 +- .../org/exist/management/impl/Database.java | 10 +- .../org/exist/management/impl/DiskUsage.java | 17 +- .../org/exist/management/impl/JMXAgent.java | 9 +- .../org/exist/management/impl/LockTable.java | 4 +- .../exist/management/impl/ProcessReport.java | 14 +- .../management/impl/ProcessReportMXBean.java | 3 +- .../exist/management/impl/SanityReport.java | 35 ++- .../org/exist/management/impl/SystemInfo.java | 5 +- .../main/java/org/exist/numbering/DLN.java | 10 +- .../java/org/exist/numbering/DLNBase.java | 19 +- .../java/org/exist/numbering/DLNFactory.java | 4 +- .../org/exist/numbering/NodeIdFactory.java | 6 +- .../URLStreamHandlerStartupTrigger.java | 8 +- .../eXistURLStreamHandlerFactory.java | 8 +- .../embedded/EmbeddedInputStream.java | 12 +- .../embedded/EmbeddedOutputStream.java | 11 +- .../embedded/InMemoryInputStream.java | 16 +- .../embedded/InMemoryOutputStream.java | 14 +- .../xmldb/EmbeddedURLConnection.java | 12 +- .../protocols/xmldb/Handler.java | 8 +- .../xmldb/InMemoryURLConnection.java | 11 +- .../exist/protocolhandler/xmldb/XmldbURL.java | 12 +- .../xmlrpc/XmlrpcDownload.java | 18 +- .../xmlrpc/XmlrpcDownloadRunnable.java | 4 +- .../xmlrpc/XmlrpcInputStream.java | 6 +- .../xmlrpc/XmlrpcOutputStream.java | 8 +- .../protocolhandler/xmlrpc/XmlrpcUpload.java | 15 +- .../xmlrpc/XmlrpcUploadRunnable.java | 6 +- .../org/exist/repo/AutoDeploymentTrigger.java | 12 +- .../java/org/exist/repo/ClasspathHelper.java | 2 +- .../main/java/org/exist/repo/Deployment.java | 20 +- .../org/exist/repo/ExistPkgExtension.java | 2 +- .../java/org/exist/repo/ExistPkgInfo.java | 6 +- .../java/org/exist/repo/ExistRepository.java | 27 +- .../java/org/exist/repo/PackageLoader.java | 8 +- .../main/java/org/exist/repo/RepoBackup.java | 2 +- .../java/org/exist/scheduler/JobConfig.java | 7 +- .../org/exist/scheduler/ScheduledJobInfo.java | 3 +- .../java/org/exist/scheduler/UserJavaJob.java | 3 +- .../org/exist/scheduler/UserXQueryJob.java | 15 +- .../scheduler/impl/QuartzSchedulerImpl.java | 42 ++- .../scheduler/impl/SystemTaskJobImpl.java | 4 +- .../org/exist/security/ACLPermission.java | 8 +- .../org/exist/security/AbstractAccount.java | 19 +- .../org/exist/security/AbstractGroup.java | 20 +- .../org/exist/security/AbstractPrincipal.java | 10 +- .../org/exist/security/AbstractRealm.java | 32 +- .../org/exist/security/AbstractSubject.java | 8 +- .../security/AbstractUnixStylePermission.java | 40 +-- ...BouncyCastleJceProviderStartupTrigger.java | 2 +- .../org/exist/security/EffectiveSubject.java | 8 +- .../org/exist/security/MessageDigester.java | 8 +- .../java/org/exist/security/Permission.java | 33 ++- .../org/exist/security/PermissionFactory.java | 34 +-- .../java/org/exist/security/Principal.java | 1 + .../org/exist/security/SecurityManager.java | 3 +- .../main/java/org/exist/security/Session.java | 14 +- .../exist/security/SimpleACLPermission.java | 14 +- .../exist/security/UnixStylePermission.java | 20 +- .../exist/security/internal/AccountImpl.java | 29 +- .../security/internal/EXistDBLoginModule.java | 28 +- .../internal/EventAuthentication.java | 4 +- .../exist/security/internal/GroupImpl.java | 3 +- .../org/exist/security/internal/Password.java | 11 +- .../exist/security/internal/RealmImpl.java | 27 +- .../org/exist/security/internal/SMEvents.java | 18 +- .../internal/SecurityManagerImpl.java | 43 ++- .../internal/SubjectAccreditedImpl.java | 10 +- .../exist/security/internal/SubjectImpl.java | 2 +- .../security/internal/aider/GroupAider.java | 9 +- .../aider/PermissionAiderFactory.java | 4 +- .../aider/SimpleACLPermissionAider.java | 6 +- .../aider/UnixStylePermissionAider.java | 31 +- .../security/internal/aider/UserAider.java | 8 +- .../security/internal/web/HttpAccount.java | 4 +- .../management/AccountsManagement.java | 4 +- .../java/org/exist/security/realm/Realm.java | 5 +- .../java/org/exist/security/utils/Utils.java | 3 +- .../java/org/exist/source/AbstractSource.java | 15 +- .../main/java/org/exist/source/DBSource.java | 8 +- .../java/org/exist/source/FileSource.java | 10 +- .../main/java/org/exist/source/Source.java | 9 +- .../java/org/exist/source/SourceFactory.java | 33 +-- .../java/org/exist/source/StringSource.java | 4 +- .../main/java/org/exist/source/URLSource.java | 4 +- .../exist/stax/EmbeddedXMLStreamReader.java | 23 +- .../exist/stax/ExtendedXMLStreamReader.java | 2 +- .../java/org/exist/storage/BrokerFactory.java | 12 +- .../java/org/exist/storage/BrokerPool.java | 45 +-- .../storage/BrokerPoolServicesManager.java | 11 +- .../java/org/exist/storage/BrokerPools.java | 2 +- .../org/exist/storage/BrokerWatchdog.java | 4 +- .../java/org/exist/storage/BufferStats.java | 4 +- .../exist/storage/ConsistencyCheckTask.java | 56 ++-- .../java/org/exist/storage/DataBackup.java | 6 +- .../exist/storage/DefaultCacheManager.java | 44 ++- .../java/org/exist/storage/ElementIndex.java | 14 +- .../org/exist/storage/FluentBrokerAPI.java | 30 +- .../exist/storage/GeneralRangeIndexSpec.java | 8 +- .../java/org/exist/storage/IndexSpec.java | 17 +- .../java/org/exist/storage/IndexStats.java | 4 +- .../java/org/exist/storage/NativeBroker.java | 81 +++--- .../org/exist/storage/NativeValueIndex.java | 51 ++-- .../main/java/org/exist/storage/NodePath.java | 7 +- .../java/org/exist/storage/NodePath2.java | 6 +- .../exist/storage/NotificationService.java | 3 +- .../org/exist/storage/OccurrenceList.java | 13 +- .../org/exist/storage/ProcessMonitor.java | 18 +- .../exist/storage/QNameRangeIndexSpec.java | 4 +- .../org/exist/storage/RangeIndexSpec.java | 16 +- .../java/org/exist/storage/RegexMatcher.java | 6 +- .../java/org/exist/storage/Signatures.java | 34 +-- .../exist/storage/StartupTriggersManager.java | 2 +- .../org/exist/storage/StorageAddress.java | 34 +-- .../java/org/exist/storage/SystemTask.java | 4 +- .../org/exist/storage/SystemTaskManager.java | 4 +- .../org/exist/storage/UpdateListener.java | 8 +- .../org/exist/storage/ValueIndexFactory.java | 21 +- .../java/org/exist/storage/XQueryPool.java | 10 +- .../storage/blob/AbstractBlobLoggable.java | 4 +- .../exist/storage/blob/BlobStoreDumpTool.java | 10 +- .../org/exist/storage/blob/BlobStoreImpl.java | 10 +- .../storage/btree/BTAbstractLoggable.java | 8 +- .../java/org/exist/storage/btree/BTree.java | 70 +++-- .../storage/btree/CreateBTNodeLoggable.java | 4 +- .../storage/btree/InsertValueLoggable.java | 4 +- .../java/org/exist/storage/btree/Paged.java | 38 +-- .../storage/btree/RemoveValueLoggable.java | 4 +- .../java/org/exist/storage/btree/Repair.java | 4 +- .../storage/btree/SetPageLinkLoggable.java | 4 +- .../storage/btree/SetParentLoggable.java | 4 +- .../org/exist/storage/btree/TreeMetrics.java | 8 +- .../storage/btree/UpdatePageLoggable.java | 15 +- .../storage/btree/UpdateValueLoggable.java | 4 +- .../java/org/exist/storage/btree/Value.java | 6 +- .../org/exist/storage/cache/Accounting.java | 22 +- .../org/exist/storage/cache/GClockCache.java | 10 +- .../org/exist/storage/cache/LRDCache.java | 4 +- .../org/exist/storage/cache/LRUCache.java | 4 +- .../exist/storage/dom/AddLinkLoggable.java | 6 +- .../storage/dom/AddMovedValueLoggable.java | 4 +- .../exist/storage/dom/AddValueLoggable.java | 6 +- .../exist/storage/dom/CreatePageLoggable.java | 6 +- .../java/org/exist/storage/dom/DOMFile.java | 101 +++---- .../org/exist/storage/dom/DOMTransaction.java | 4 +- .../org/exist/storage/dom/INodeIterator.java | 1 + .../storage/dom/InsertValueLoggable.java | 6 +- .../java/org/exist/storage/dom/ItemId.java | 18 +- .../org/exist/storage/dom/NodeIterator.java | 21 +- .../exist/storage/dom/RawNodeIterator.java | 6 +- .../java/org/exist/storage/dom/RecordPos.java | 4 +- .../storage/dom/RemoveEmptyPageLoggable.java | 4 +- .../storage/dom/RemoveOverflowLoggable.java | 4 +- .../exist/storage/dom/RemovePageLoggable.java | 4 +- .../storage/dom/RemoveValueLoggable.java | 4 +- .../exist/storage/dom/SplitPageLoggable.java | 6 +- .../storage/dom/UpdateHeaderLoggable.java | 6 +- .../exist/storage/dom/UpdateLinkLoggable.java | 6 +- .../storage/dom/UpdateValueLoggable.java | 4 +- .../dom/WriteOverflowPageLoggable.java | 8 +- .../storage/index/AbstractBFileLoggable.java | 8 +- .../java/org/exist/storage/index/BFile.java | 109 +++---- .../exist/storage/index/CollectionStore.java | 12 +- .../storage/index/CreatePageLoggable.java | 4 +- .../org/exist/storage/index/FreeList.java | 12 +- .../org/exist/storage/index/FreeSpace.java | 18 +- .../storage/index/OverflowAppendLoggable.java | 6 +- .../storage/index/OverflowCreateLoggable.java | 4 +- .../index/OverflowCreatePageLoggable.java | 4 +- .../index/OverflowModifiedLoggable.java | 4 +- .../storage/index/OverflowRemoveLoggable.java | 4 +- .../storage/index/OverflowStoreLoggable.java | 4 +- .../index/RemoveEmptyPageLoggable.java | 4 +- .../storage/index/RemoveValueLoggable.java | 6 +- .../storage/index/StoreValueLoggable.java | 4 +- .../storage/io/AbstractVariableByteInput.java | 31 +- .../exist/storage/io/BlockingInputStream.java | 38 ++- .../storage/io/BlockingOutputStream.java | 4 +- .../storage/io/VariableByteArrayInput.java | 19 +- .../exist/storage/io/VariableByteInput.java | 4 +- .../storage/io/VariableByteInputStream.java | 2 +- .../storage/io/VariableByteOutputStream.java | 20 +- .../storage/journal/AbstractLoggable.java | 2 +- .../org/exist/storage/journal/Journal.java | 30 +- .../exist/storage/journal/JournalManager.java | 4 +- .../exist/storage/journal/JournalReader.java | 4 +- .../exist/storage/journal/LogEntryTypes.java | 18 +- .../java/org/exist/storage/journal/Lsn.java | 17 +- .../org/exist/storage/lock/EnsureLocked.java | 6 +- .../storage/lock/EnsureLockingAspect.java | 16 +- .../java/org/exist/storage/lock/FileLock.java | 15 +- .../exist/storage/lock/FileLockService.java | 4 +- .../storage/lock/LockEventJsonListener.java | 8 +- .../storage/lock/LockEventXmlListener.java | 8 +- .../java/org/exist/storage/lock/LockInfo.java | 20 +- .../org/exist/storage/lock/LockManager.java | 14 +- .../org/exist/storage/lock/LockTable.java | 19 +- .../exist/storage/lock/LockTableUtils.java | 8 +- .../exist/storage/lock/LockedDocumentMap.java | 4 +- .../storage/lock/ManagedDocumentLock.java | 2 +- .../org/exist/storage/lock/ManagedLock.java | 2 +- .../storage/recovery/RecoveryManager.java | 23 +- .../exist/storage/report/XMLStatistics.java | 10 +- .../serializers/AbstractChainOfReceivers.java | 2 +- .../serializers/ChainOfReceiversFactory.java | 6 +- .../CustomMatchListenerFactory.java | 12 +- .../storage/serializers/NativeSerializer.java | 46 ++- .../exist/storage/serializers/Serializer.java | 93 +++--- .../exist/storage/serializers/WSDLFilter.java | 6 +- .../storage/serializers/XIncludeFilter.java | 32 +- .../exist/storage/statistics/DataGuide.java | 6 +- .../storage/statistics/IndexStatistics.java | 4 +- .../statistics/IndexStatisticsWorker.java | 19 +- .../exist/storage/statistics/NodeStats.java | 10 +- .../structural/NativeStructuralIndex.java | 14 +- .../NativeStructuralIndexWorker.java | 36 +-- .../java/org/exist/storage/sync/SyncTask.java | 12 +- .../org/exist/storage/txn/Checkpoint.java | 8 +- .../exist/storage/txn/TransactionManager.java | 2 +- .../main/java/org/exist/storage/txn/Txn.java | 12 +- .../java/org/exist/storage/txn/TxnAbort.java | 4 +- .../java/org/exist/storage/txn/TxnCommit.java | 4 +- .../java/org/exist/storage/txn/TxnStart.java | 4 +- .../main/java/org/exist/test/DiffMatcher.java | 2 +- .../org/exist/test/ExistEmbeddedServer.java | 4 +- .../java/org/exist/test/ExistWebServer.java | 4 +- .../exist/test/ExistXmldbEmbeddedServer.java | 6 +- .../org/exist/test/TransactionTestDSL.java | 8 +- .../java/org/exist/test/XQueryAssertions.java | 5 +- .../org/exist/test/XmlStringDiffMatcher.java | 2 +- .../ExtTestAssumptionFailedFunction.java | 4 +- .../test/runner/ExtTestErrorFunction.java | 4 +- .../test/runner/ExtTestFailureFunction.java | 6 +- .../test/runner/JUnitIntegrationFunction.java | 2 +- .../exist/test/runner/XQueryTestRunner.java | 12 +- .../java/org/exist/test/runner/XSuite.java | 2 +- .../exist/util/BinaryValueInputSource.java | 2 +- .../java/org/exist/util/ByteArrayPool.java | 2 +- .../java/org/exist/util/ByteConversion.java | 34 +-- .../CachingFilterInputStreamInputSource.java | 2 +- .../java/org/exist/util/CharArrayPool.java | 2 +- .../main/java/org/exist/util/Collations.java | 39 ++- .../exist/util/CollectionOfArrayIterator.java | 2 +- .../org/exist/util/CollectionScanner.java | 10 +- .../org/exist/util/CompressedWhitespace.java | 18 +- .../main/java/org/exist/util/Compressor.java | 6 +- .../java/org/exist/util/Configuration.java | 199 +++---------- .../org/exist/util/ConfigurationHelper.java | 15 +- .../java/org/exist/util/EXistInputSource.java | 2 +- .../org/exist/util/ExistSAXParserFactory.java | 12 +- .../main/java/org/exist/util/FastQSort.java | 212 +++++++------- .../java/org/exist/util/FileInputSource.java | 2 +- .../main/java/org/exist/util/FileUtils.java | 21 +- .../java/org/exist/util/GZIPInputSource.java | 4 +- .../src/main/java/org/exist/util/HSort.java | 50 ++-- .../main/java/org/exist/util/HeapSort.java | 46 +-- .../main/java/org/exist/util/HexEncoder.java | 2 +- .../java/org/exist/util/HtmlToXmlParser.java | 8 +- .../src/main/java/org/exist/util/IPUtil.java | 2 +- .../java/org/exist/util/IncludeXMLFilter.java | 2 +- .../java/org/exist/util/InsertionSort.java | 38 +-- .../java/org/exist/util/LongLinkedList.java | 14 +- .../main/java/org/exist/util/MimeTable.java | 41 ++- .../main/java/org/exist/util/MimeType.java | 32 +- .../main/java/org/exist/util/Occurrences.java | 2 +- .../org/exist/util/OrderedLinkedList.java | 20 +- .../org/exist/util/ParametersExtractor.java | 21 +- .../java/org/exist/util/PatternFactory.java | 2 +- .../main/java/org/exist/util/ProgressBar.java | 12 +- .../org/exist/util/PropertiesBuilder.java | 2 +- .../src/main/java/org/exist/util/Range.java | 4 +- .../main/java/org/exist/util/SSLHelper.java | 21 +- .../org/exist/util/SaxonConfiguration.java | 6 +- .../util/SingleInstanceConfiguration.java | 8 +- .../main/java/org/exist/util/Stacktrace.java | 2 +- .../main/java/org/exist/util/SwapVals.java | 8 +- .../java/org/exist/util/SystemExitCodes.java | 14 +- .../org/exist/util/TraceableStateChange.java | 2 +- .../src/main/java/org/exist/util/UTF8.java | 38 +-- .../java/org/exist/util/UUIDGenerator.java | 14 +- .../java/org/exist/util/ValueOccurrences.java | 6 +- .../java/org/exist/util/WeakLazyStripes.java | 2 +- .../exist/util/XMLReaderObjectFactory.java | 9 +- .../main/java/org/exist/util/XMLString.java | 24 +- .../org/exist/util/XQueryFilenameFilter.java | 4 +- .../org/exist/util/ZipEntryInputSource.java | 2 +- .../util/crypto/digest/MessageDigest.java | 11 +- .../exist/util/hashtable/AbstractHashSet.java | 8 +- .../org/exist/util/hashtable/NamePool.java | 6 +- .../io/AbstractFilterInputStreamCache.java | 8 +- .../exist/util/io/ByteBufferInputStream.java | 6 +- .../util/io/CachingFilterInputStream.java | 11 +- .../util/io/FileFilterInputStreamCache.java | 4 +- .../io/FilterInputStreamCacheFactory.java | 8 +- .../io/FilterInputStreamCacheMonitor.java | 2 +- .../org/exist/util/io/MemoryContentsImpl.java | 12 +- .../util/io/MemoryContentsInputStream.java | 6 +- ...emoryMappedFileFilterInputStreamCache.java | 6 +- .../exist/util/io/OverflowToDiskStream.java | 10 +- .../exist/util/io/TemporaryFileManager.java | 14 +- .../org/exist/util/io/VirtualTempPath.java | 12 +- .../java/org/exist/util/pool/NodePool.java | 14 +- .../org/exist/util/sax/event/TextEvent.java | 2 +- .../sax/event/contenthandler/Element.java | 2 +- .../sax/event/contenthandler/EndDocument.java | 4 +- .../event/contenthandler/PrefixMapping.java | 2 +- .../event/contenthandler/StartDocument.java | 4 +- .../sax/event/lexicalhandler/EndCDATA.java | 4 +- .../util/sax/event/lexicalhandler/EndDTD.java | 4 +- .../sax/event/lexicalhandler/StartCDATA.java | 4 +- .../util/serializer/AbstractSerializer.java | 4 +- .../util/serializer/AdaptiveSerializer.java | 2 +- .../exist/util/serializer/AdaptiveWriter.java | 13 +- .../org/exist/util/serializer/AttrList.java | 4 +- .../serializer/CharacterMappingWriter.java | 2 +- .../exist/util/serializer/DOMSerializer.java | 15 +- .../exist/util/serializer/DOMStreamer.java | 13 +- .../exist/util/serializer/EXISerializer.java | 20 +- .../serializer/ExtendedDOMSerializer.java | 11 +- .../util/serializer/IndentingXMLWriter.java | 31 +- .../exist/util/serializer/MicroXmlWriter.java | 11 +- .../exist/util/serializer/ReceiverToSAX.java | 2 +- .../exist/util/serializer/SAXSerializer.java | 6 +- .../exist/util/serializer/SAXToReceiver.java | 12 +- .../org/exist/util/serializer/TEXTWriter.java | 13 +- .../exist/util/serializer/XHTML5Writer.java | 6 +- .../exist/util/serializer/XHTMLWriter.java | 16 +- .../org/exist/util/serializer/XMLWriter.java | 41 +-- .../serializer/encodings/ASCIICharSet.java | 2 +- .../serializer/encodings/KOI8RCharSet.java | 2 +- .../serializer/encodings/Latin1CharSet.java | 2 +- .../serializer/encodings/Latin2CharSet.java | 6 +- .../serializer/encodings/UnicodeCharSet.java | 2 +- .../exist/util/serializer/json/JSONNode.java | 16 +- .../util/serializer/json/JSONObject.java | 11 +- .../util/serializer/json/JSONSerializer.java | 11 +- .../exist/util/serializer/json/JSONValue.java | 4 +- .../util/serializer/json/JSONWriter.java | 47 +-- .../org/exist/validation/GrammarPool.java | 18 +- .../validation/ValidationContentHandler.java | 4 +- .../exist/validation/ValidationReport.java | 6 +- .../validation/ValidationReportItem.java | 8 +- .../exist/validation/XmlLibraryChecker.java | 8 +- .../internal/DatabaseResources.java | 18 +- .../internal/node/NodeSerializer.java | 2 +- .../resolver/unstable/ExistResolver.java | 8 +- .../resolver/unstable/eXistLSInput.java | 2 +- .../java/org/exist/webstart/JnlpJarFiles.java | 14 +- .../java/org/exist/webstart/JnlpServlet.java | 16 +- .../java/org/exist/webstart/JnlpWriter.java | 22 +- .../exist/xmldb/AbstractEXistResource.java | 16 +- .../java/org/exist/xmldb/AbstractLocal.java | 15 +- .../java/org/exist/xmldb/AbstractRemote.java | 11 +- .../exist/xmldb/AbstractRemoteResource.java | 37 ++- .../java/org/exist/xmldb/DatabaseImpl.java | 47 ++- .../java/org/exist/xmldb/DatabaseStatus.java | 10 +- .../java/org/exist/xmldb/EXistCollection.java | 4 +- .../EXistCollectionManagementService.java | 3 +- .../java/org/exist/xmldb/EXistResource.java | 5 +- .../org/exist/xmldb/EXistXQueryService.java | 4 +- .../org/exist/xmldb/ExtendedResource.java | 4 +- .../org/exist/xmldb/LocalBinaryResource.java | 32 +- .../java/org/exist/xmldb/LocalCollection.java | 39 ++- .../LocalCollectionManagementService.java | 7 +- .../xmldb/LocalDatabaseInstanceManager.java | 4 +- .../exist/xmldb/LocalIndexQueryService.java | 2 +- .../org/exist/xmldb/LocalResourceSet.java | 16 +- .../org/exist/xmldb/LocalRestoreService.java | 1 - .../xmldb/LocalUserManagementService.java | 15 +- .../org/exist/xmldb/LocalXMLResource.java | 58 ++-- .../exist/xmldb/LocalXPathQueryService.java | 33 +-- .../exist/xmldb/LocalXUpdateQueryService.java | 7 +- .../java/org/exist/xmldb/MapResourceSet.java | 12 +- .../org/exist/xmldb/RemoteBinaryResource.java | 28 +- .../org/exist/xmldb/RemoteCollection.java | 53 ++-- .../RemoteCollectionManagementService.java | 9 +- .../xmldb/RemoteDatabaseInstanceManager.java | 11 +- .../exist/xmldb/RemoteIndexQueryService.java | 12 +- .../exist/xmldb/RemoteResourceIterator.java | 14 +- .../org/exist/xmldb/RemoteResourceSet.java | 35 +-- .../org/exist/xmldb/RemoteRestoreService.java | 1 + .../xmldb/RemoteUserManagementService.java | 30 +- .../org/exist/xmldb/RemoteXMLResource.java | 50 ++-- .../exist/xmldb/RemoteXPathQueryService.java | 15 +- .../xmldb/RemoteXUpdateQueryService.java | 8 +- .../exist/xmldb/UserManagementService.java | 8 +- .../main/java/org/exist/xmldb/XmldbURI.java | 51 ++-- .../LocalXmldbCollectionFunction.java | 2 +- .../function/LocalXmldbDocumentFunction.java | 2 +- .../xmldb/function/LocalXmldbFunction.java | 2 +- .../txn/bridge/InTxnLocalCollection.java | 4 +- .../java/org/exist/xmlrpc/ACEAiderParser.java | 2 +- .../exist/xmlrpc/AbstractCachedResult.java | 10 +- .../java/org/exist/xmlrpc/QueryResult.java | 16 +- .../org/exist/xmlrpc/QueryResultCache.java | 6 +- .../main/java/org/exist/xmlrpc/RpcAPI.java | 11 +- .../java/org/exist/xmlrpc/RpcConnection.java | 75 +++-- .../java/org/exist/xmlrpc/RpcServlet.java | 18 +- .../java/org/exist/xmlrpc/TupleParser.java | 2 +- .../xmlrpc/XmldbRequestProcessorFactory.java | 6 +- .../function/XmlRpcCollectionFunction.java | 2 +- .../XmlRpcCompiledXQueryFunction.java | 2 +- .../function/XmlRpcDocumentFunction.java | 2 +- .../exist/xmlrpc/function/XmlRpcFunction.java | 2 +- .../main/java/org/exist/xqj/Marshaller.java | 25 +- .../org/exist/xquery/AbstractExpression.java | 8 +- .../org/exist/xquery/AbstractFLWORClause.java | 6 +- .../exist/xquery/AbstractInternalModule.java | 9 +- .../java/org/exist/xquery/AbstractPragma.java | 2 +- .../org/exist/xquery/AnalyzeContextInfo.java | 8 +- .../org/exist/xquery/AncestorSelector.java | 8 +- .../java/org/exist/xquery/Annotation.java | 4 +- .../java/org/exist/xquery/Annotations.java | 2 +- .../java/org/exist/xquery/AnyNodeTest.java | 4 +- .../java/org/exist/xquery/ArrowOperator.java | 10 +- .../main/java/org/exist/xquery/Atomize.java | 6 +- .../exist/xquery/AttributeConstructor.java | 13 +- .../exist/xquery/BasicExpressionVisitor.java | 4 +- .../java/org/exist/xquery/BasicFunction.java | 4 +- .../main/java/org/exist/xquery/BinaryOp.java | 4 +- .../org/exist/xquery/BindingExpression.java | 10 +- .../java/org/exist/xquery/CachedResult.java | 8 +- .../java/org/exist/xquery/ChildSelector.java | 4 +- .../org/exist/xquery/CombiningExpression.java | 6 +- .../org/exist/xquery/CommentConstructor.java | 3 +- .../java/org/exist/xquery/CompiledXQuery.java | 6 +- .../main/java/org/exist/xquery/Context.java | 19 +- .../exist/xquery/ContextItemExpression.java | 1 + .../java/org/exist/xquery/CountClause.java | 9 +- .../exist/xquery/DebuggableExpression.java | 8 +- .../exist/xquery/DeferredFunctionCall.java | 15 +- .../java/org/exist/xquery/Dependency.java | 32 +- .../xquery/DynamicAttributeConstructor.java | 16 +- .../exist/xquery/DynamicCardinalityCheck.java | 6 +- .../xquery/DynamicCommentConstructor.java | 2 +- .../org/exist/xquery/DynamicFunctionCall.java | 4 +- .../org/exist/xquery/DynamicNameCheck.java | 6 +- .../exist/xquery/DynamicPIConstructor.java | 3 +- .../exist/xquery/DynamicTextConstructor.java | 2 +- .../org/exist/xquery/DynamicTypeCheck.java | 8 +- .../org/exist/xquery/ElementConstructor.java | 24 +- .../java/org/exist/xquery/EnclosedExpr.java | 2 +- .../java/org/exist/xquery/ErrorCodes.java | 4 +- .../main/java/org/exist/xquery/Except.java | 9 +- .../java/org/exist/xquery/Expression.java | 30 +- .../org/exist/xquery/ExtensionExpression.java | 2 +- .../org/exist/xquery/ExternalModuleImpl.java | 19 +- .../main/java/org/exist/xquery/FailTest.java | 2 +- .../org/exist/xquery/FilteredExpression.java | 9 +- .../main/java/org/exist/xquery/ForExpr.java | 4 +- .../main/java/org/exist/xquery/Function.java | 7 +- .../java/org/exist/xquery/FunctionCall.java | 103 +++---- .../org/exist/xquery/FunctionFactory.java | 9 +- .../java/org/exist/xquery/FunctionId.java | 3 +- .../org/exist/xquery/FunctionSignature.java | 19 +- .../org/exist/xquery/GeneralComparison.java | 116 ++++---- .../java/org/exist/xquery/GroupByClause.java | 9 +- .../java/org/exist/xquery/InlineFunction.java | 14 +- .../exist/xquery/InternalFunctionCall.java | 10 +- .../java/org/exist/xquery/InternalModule.java | 6 +- .../main/java/org/exist/xquery/JavaCall.java | 34 +-- .../java/org/exist/xquery/LocalVariable.java | 6 +- .../java/org/exist/xquery/LocationStep.java | 32 +- .../main/java/org/exist/xquery/LogicalOp.java | 10 +- .../main/java/org/exist/xquery/Lookup.java | 4 +- .../main/java/org/exist/xquery/Module.java | 3 +- .../java/org/exist/xquery/ModuleContext.java | 14 +- .../main/java/org/exist/xquery/NameTest.java | 36 +-- .../exist/xquery/NamedFunctionReference.java | 12 +- .../exist/xquery/NamespaceConstructor.java | 10 +- .../java/org/exist/xquery/NodeComparison.java | 6 +- .../org/exist/xquery/NodeConstructor.java | 8 +- .../main/java/org/exist/xquery/NodeTest.java | 2 +- .../src/main/java/org/exist/xquery/OpAnd.java | 4 +- .../main/java/org/exist/xquery/OpNumeric.java | 18 +- .../java/org/exist/xquery/OpSimpleMap.java | 4 +- .../main/java/org/exist/xquery/Optimizer.java | 10 +- .../main/java/org/exist/xquery/Option.java | 30 +- .../main/java/org/exist/xquery/OrderSpec.java | 4 +- .../java/org/exist/xquery/PIConstructor.java | 7 +- .../java/org/exist/xquery/ParentSelector.java | 2 +- .../xquery/PartialFunctionApplication.java | 16 +- .../main/java/org/exist/xquery/PathExpr.java | 8 +- .../exist/xquery/PerformanceStatsImpl.java | 17 +- .../exist/xquery/PerformanceStatsService.java | 6 +- .../main/java/org/exist/xquery/Predicate.java | 31 +- .../main/java/org/exist/xquery/Profiler.java | 29 +- .../exist/xquery/QuantifiedExpression.java | 14 +- .../org/exist/xquery/RangeExpression.java | 10 +- .../java/org/exist/xquery/RangeSequence.java | 14 +- .../main/java/org/exist/xquery/RootNode.java | 13 +- .../java/org/exist/xquery/SelfSelector.java | 4 +- .../java/org/exist/xquery/SimpleStep.java | 2 +- .../src/main/java/org/exist/xquery/Step.java | 17 +- .../org/exist/xquery/SwitchExpression.java | 14 +- .../org/exist/xquery/TerminatedException.java | 4 +- .../org/exist/xquery/TextConstructor.java | 5 +- .../org/exist/xquery/TreatAsExpression.java | 4 +- .../org/exist/xquery/TryCatchExpression.java | 29 +- .../main/java/org/exist/xquery/TypeTest.java | 6 +- .../exist/xquery/TypeswitchExpression.java | 10 +- .../org/exist/xquery/UserDefinedFunction.java | 17 +- .../xquery/UserSwitchingBasicFunction.java | 4 +- .../org/exist/xquery/ValueComparison.java | 6 +- .../main/java/org/exist/xquery/Variable.java | 2 +- .../org/exist/xquery/VariableDeclaration.java | 4 +- .../java/org/exist/xquery/VariableImpl.java | 10 +- .../org/exist/xquery/VariableReference.java | 9 +- .../java/org/exist/xquery/WhereClause.java | 4 +- .../java/org/exist/xquery/WindowExpr.java | 2 +- .../java/org/exist/xquery/XPathException.java | 28 +- .../main/java/org/exist/xquery/XPathUtil.java | 32 +- .../main/java/org/exist/xquery/XQuery.java | 14 +- .../java/org/exist/xquery/XQueryContext.java | 146 +++++----- .../java/org/exist/xquery/XQueryWatchDog.java | 13 +- .../functions/array/ArrayConstructor.java | 27 +- .../functions/fn/CollatingFunction.java | 4 +- .../xquery/functions/fn/ExtCollection.java | 6 +- .../xquery/functions/fn/FnFormatDates.java | 37 +-- .../xquery/functions/fn/FnFormatNumbers.java | 12 +- .../xquery/functions/fn/FnHasChildren.java | 6 +- .../xquery/functions/fn/FnInnerMost.java | 6 +- .../exist/xquery/functions/fn/FnModule.java | 20 +- .../xquery/functions/fn/FnOuterMost.java | 6 +- .../functions/fn/FnRandomNumberGenerator.java | 16 +- .../org/exist/xquery/functions/fn/FunAbs.java | 10 +- .../functions/fn/FunAdjustTimezone.java | 28 +- .../xquery/functions/fn/FunAnalyzeString.java | 17 +- .../org/exist/xquery/functions/fn/FunAvg.java | 22 +- .../exist/xquery/functions/fn/FunBoolean.java | 10 +- .../exist/xquery/functions/fn/FunCeiling.java | 10 +- .../functions/fn/FunCodepointEqual.java | 10 +- .../functions/fn/FunCodepointsToString.java | 12 +- .../xquery/functions/fn/FunCollationKey.java | 9 +- .../exist/xquery/functions/fn/FunCompare.java | 10 +- .../exist/xquery/functions/fn/FunConcat.java | 15 +- .../xquery/functions/fn/FunContains.java | 10 +- .../xquery/functions/fn/FunContainsToken.java | 8 +- .../exist/xquery/functions/fn/FunCount.java | 10 +- .../functions/fn/FunCurrentDateTime.java | 13 +- .../exist/xquery/functions/fn/FunData.java | 10 +- .../xquery/functions/fn/FunDateTime.java | 13 +- .../xquery/functions/fn/FunDeepEqual.java | 17 +- .../functions/fn/FunDefaultCollation.java | 2 +- .../functions/fn/FunDistinctValues.java | 21 +- .../org/exist/xquery/functions/fn/FunDoc.java | 14 +- .../xquery/functions/fn/FunDocAvailable.java | 9 +- .../xquery/functions/fn/FunDocumentURI.java | 6 +- .../exist/xquery/functions/fn/FunEmpty.java | 10 +- .../xquery/functions/fn/FunEncodeForURI.java | 10 +- .../xquery/functions/fn/FunEndsWith.java | 10 +- .../xquery/functions/fn/FunEnvironment.java | 13 +- .../exist/xquery/functions/fn/FunEquals.java | 10 +- .../exist/xquery/functions/fn/FunError.java | 13 +- .../xquery/functions/fn/FunEscapeHTMLURI.java | 10 +- .../xquery/functions/fn/FunEscapeURI.java | 13 +- .../xquery/functions/fn/FunExactlyOne.java | 10 +- .../exist/xquery/functions/fn/FunExists.java | 10 +- .../exist/xquery/functions/fn/FunFloor.java | 10 +- .../functions/fn/FunGetDateComponent.java | 47 ++- .../functions/fn/FunGetDurationComponent.java | 35 +-- .../xquery/functions/fn/FunHeadTail.java | 8 +- .../functions/fn/FunHigherOrderFun.java | 5 +- .../xquery/functions/fn/FunIRIToURI.java | 10 +- .../org/exist/xquery/functions/fn/FunId.java | 2 +- .../exist/xquery/functions/fn/FunIdRef.java | 23 +- .../functions/fn/FunImplicitTimezone.java | 8 +- .../functions/fn/FunInScopePrefixes.java | 18 +- .../exist/xquery/functions/fn/FunIndexOf.java | 12 +- .../xquery/functions/fn/FunInsertBefore.java | 11 +- .../exist/xquery/functions/fn/FunLang.java | 12 +- .../exist/xquery/functions/fn/FunLast.java | 8 +- .../xquery/functions/fn/FunLocalName.java | 9 +- .../exist/xquery/functions/fn/FunMatches.java | 27 +- .../org/exist/xquery/functions/fn/FunMax.java | 17 +- .../org/exist/xquery/functions/fn/FunMin.java | 17 +- .../exist/xquery/functions/fn/FunName.java | 11 +- .../xquery/functions/fn/FunNamespaceURI.java | 11 +- .../fn/FunNamespaceURIForPrefix.java | 14 +- .../xquery/functions/fn/FunNodeName.java | 11 +- .../functions/fn/FunNormalizeSpace.java | 14 +- .../functions/fn/FunNormalizeUnicode.java | 11 +- .../org/exist/xquery/functions/fn/FunNot.java | 15 +- .../exist/xquery/functions/fn/FunNumber.java | 10 +- .../xquery/functions/fn/FunOnFunctions.java | 11 +- .../xquery/functions/fn/FunOneOrMore.java | 9 +- .../xquery/functions/fn/FunParseIetfDate.java | 29 +- .../exist/xquery/functions/fn/FunPath.java | 6 +- .../xquery/functions/fn/FunPosition.java | 8 +- .../exist/xquery/functions/fn/FunQName.java | 36 ++- .../exist/xquery/functions/fn/FunRemove.java | 13 +- .../exist/xquery/functions/fn/FunReplace.java | 6 +- .../xquery/functions/fn/FunResolveQName.java | 19 +- .../xquery/functions/fn/FunResolveURI.java | 16 +- .../exist/xquery/functions/fn/FunReverse.java | 11 +- .../exist/xquery/functions/fn/FunRoot.java | 15 +- .../xquery/functions/fn/FunRoundBase.java | 4 +- .../xquery/functions/fn/FunSerialize.java | 4 +- .../exist/xquery/functions/fn/FunSort.java | 15 +- .../xquery/functions/fn/FunStartsWith.java | 10 +- .../xquery/functions/fn/FunStrLength.java | 10 +- .../exist/xquery/functions/fn/FunString.java | 10 +- .../xquery/functions/fn/FunStringJoin.java | 11 +- .../functions/fn/FunStringToCodepoints.java | 10 +- .../xquery/functions/fn/FunSubSequence.java | 2 +- .../xquery/functions/fn/FunSubstring.java | 13 +- .../functions/fn/FunSubstringAfter.java | 10 +- .../functions/fn/FunSubstringBefore.java | 10 +- .../org/exist/xquery/functions/fn/FunSum.java | 26 +- .../xquery/functions/fn/FunTokenize.java | 18 +- .../exist/xquery/functions/fn/FunTrace.java | 2 +- .../xquery/functions/fn/FunTranslate.java | 12 +- .../xquery/functions/fn/FunTrueOrFalse.java | 4 +- .../xquery/functions/fn/FunUnordered.java | 9 +- .../xquery/functions/fn/FunUnparsedText.java | 4 +- .../functions/fn/FunUpperOrLowerCase.java | 12 +- .../xquery/functions/fn/FunUriCollection.java | 20 +- .../xquery/functions/fn/FunXmlToJson.java | 11 +- .../xquery/functions/fn/FunZeroOrOne.java | 9 +- .../org/exist/xquery/functions/fn/JSON.java | 37 ++- .../xquery/functions/fn/LoadXQueryModule.java | 18 +- .../xquery/functions/fn/ParsingFunctions.java | 8 +- .../xquery/functions/fn/QNameFunctions.java | 15 +- .../functions/fn/transform/Convert.java | 13 +- .../functions/fn/transform/Options.java | 2 +- .../fn/transform/SerializationParameters.java | 4 +- .../functions/fn/transform/Transform.java | 4 +- .../functions/fn/transform/TreeUtils.java | 2 +- .../inspect/FunctionCallVisitor.java | 2 +- .../functions/inspect/InspectionModule.java | 8 +- .../functions/inspect/ModuleFunctions.java | 7 +- .../integer/DigitsIntegerPicture.java | 24 +- .../functions/integer/FormatModifier.java | 16 +- .../functions/integer/IntegerPicture.java | 3 +- .../functions/integer/NumberingPicture.java | 2 +- .../functions/integer/RomanNumberHelper.java | 2 +- .../xquery/functions/integer/WordPicture.java | 11 +- .../xquery/functions/map/AbstractMapType.java | 4 +- .../xquery/functions/math/MathModule.java | 15 +- .../functions/math/NoParamFunctions.java | 2 +- .../functions/math/OneParamFunctions.java | 22 +- .../functions/math/TwoParamFunctions.java | 4 +- .../functions/request/GetContextPath.java | 2 +- .../functions/request/GetCookieNames.java | 9 +- .../functions/request/GetCookieValue.java | 10 +- .../xquery/functions/request/GetData.java | 13 +- .../xquery/functions/request/GetExists.java | 2 +- .../xquery/functions/request/GetHeader.java | 10 +- .../functions/request/GetHeaderNames.java | 11 +- .../xquery/functions/request/GetHostname.java | 2 +- .../xquery/functions/request/GetMethod.java | 2 +- .../functions/request/GetParameter.java | 8 +- .../functions/request/GetParameterNames.java | 11 +- .../xquery/functions/request/GetPathInfo.java | 2 +- .../functions/request/GetQueryString.java | 2 +- .../functions/request/GetRemoteAddr.java | 2 +- .../functions/request/GetRemoteHost.java | 2 +- .../functions/request/GetRemotePort.java | 2 +- .../request/GetRequestAttribute.java | 2 +- .../xquery/functions/request/GetScheme.java | 2 +- .../functions/request/GetServerName.java | 2 +- .../functions/request/GetServerPort.java | 2 +- .../xquery/functions/request/GetURI.java | 2 +- .../xquery/functions/request/GetURL.java | 2 +- .../functions/request/GetUploadedFile.java | 17 +- .../request/GetUploadedFileName.java | 13 +- .../request/GetUploadedFileSize.java | 15 +- .../functions/request/IsMultiPartContent.java | 4 +- .../functions/request/RequestFunction.java | 2 +- .../functions/request/RequestModule.java | 14 +- .../functions/request/SetAttribute.java | 2 +- .../request/StrictRequestFunction.java | 2 +- .../xquery/functions/response/GetExists.java | 3 +- .../xquery/functions/response/RedirectTo.java | 3 +- .../functions/response/ResponseFunction.java | 2 +- .../functions/response/ResponseModule.java | 20 +- .../xquery/functions/response/SetCookie.java | 17 +- .../functions/response/SetDateHeader.java | 9 +- .../xquery/functions/response/SetHeader.java | 3 +- .../functions/response/SetStatusCode.java | 9 +- .../xquery/functions/response/Stream.java | 13 +- .../functions/response/StreamBinary.java | 14 +- .../response/StrictResponseFunction.java | 2 +- .../AccountManagementFunction.java | 22 +- .../AccountStatusFunction.java | 17 +- .../securitymanager/FindGroupFunction.java | 35 +-- .../securitymanager/FindUserFunction.java | 40 ++- .../GetPrincipalMetadataFunction.java | 34 +-- .../GroupManagementFunction.java | 14 +- .../GroupMembershipFunction.java | 40 +-- .../functions/securitymanager/IdFunction.java | 2 +- .../IsAuthenticatedFunction.java | 4 +- .../securitymanager/PermissionsFunction.java | 73 +++-- .../SecurityManagerModule.java | 17 +- .../SetPrincipalMetadataFunction.java | 10 +- .../securitymanager/UMaskFunction.java | 17 +- .../exist/xquery/functions/session/Clear.java | 7 +- .../xquery/functions/session/Create.java | 2 +- .../xquery/functions/session/EncodeURL.java | 9 +- .../functions/session/GetAttribute.java | 8 +- .../functions/session/GetAttributeNames.java | 13 +- .../functions/session/GetCreationTime.java | 8 +- .../xquery/functions/session/GetExists.java | 2 +- .../exist/xquery/functions/session/GetID.java | 2 +- .../session/GetLastAccessedTime.java | 8 +- .../session/GetMaxInactiveInterval.java | 2 +- .../xquery/functions/session/Invalidate.java | 2 +- .../functions/session/RemoveAttribute.java | 2 +- .../functions/session/SessionFunction.java | 2 +- .../functions/session/SessionModule.java | 16 +- .../functions/session/SetAttribute.java | 2 +- .../functions/session/SetCurrentUser.java | 10 +- .../session/SetMaxInactiveInterval.java | 8 +- .../session/StrictSessionFunction.java | 2 +- .../exist/xquery/functions/system/AsUser.java | 10 +- .../functions/system/ClearXQueryCache.java | 2 +- .../functions/system/CountInstances.java | 10 +- .../xquery/functions/system/FnExport.java | 36 +-- .../xquery/functions/system/FnImport.java | 45 ++- .../functions/system/FunctionAvailable.java | 13 +- .../functions/system/FunctionTrace.java | 8 +- .../xquery/functions/system/GetBuild.java | 2 +- .../xquery/functions/system/GetExistHome.java | 10 +- .../functions/system/GetIndexStatistics.java | 4 +- .../system/GetMainModuleLoadPath.java | 4 +- .../xquery/functions/system/GetMemory.java | 8 +- .../functions/system/GetModuleLoadPath.java | 4 +- .../functions/system/GetProductName.java | 2 +- .../xquery/functions/system/GetRevision.java | 2 +- .../functions/system/GetRunningJobs.java | 18 +- .../functions/system/GetRunningXQueries.java | 25 +- .../functions/system/GetScheduledJobs.java | 23 +- .../xquery/functions/system/GetUptime.java | 10 +- .../xquery/functions/system/GetVersion.java | 2 +- .../functions/system/KillRunningXQuery.java | 16 +- .../xquery/functions/system/Restore.java | 23 +- .../xquery/functions/system/Shutdown.java | 16 +- .../xquery/functions/system/SystemModule.java | 10 +- .../functions/system/TriggerSystemTask.java | 14 +- .../functions/system/UpdateStatistics.java | 4 +- .../xquery/functions/transform/Transform.java | 4 +- .../functions/transform/TransformModule.java | 15 +- .../functions/util/Base64Functions.java | 9 +- .../util/BaseConversionFunctions.java | 15 +- .../xquery/functions/util/BaseConverter.java | 13 +- .../xquery/functions/util/BinaryDoc.java | 12 +- .../xquery/functions/util/BinaryToString.java | 22 +- .../functions/util/BuiltinFunctions.java | 4 +- .../xquery/functions/util/CallFunction.java | 16 +- .../xquery/functions/util/Collations.java | 12 +- .../xquery/functions/util/CollectionName.java | 18 +- .../exist/xquery/functions/util/Compile.java | 20 +- .../functions/util/DeepCopyFunction.java | 15 +- .../functions/util/DescribeFunction.java | 16 +- .../functions/util/DocumentNameOrId.java | 20 +- .../org/exist/xquery/functions/util/Eval.java | 45 ++- .../functions/util/ExclusiveLockFunction.java | 2 +- .../exist/xquery/functions/util/Expand.java | 10 +- .../xquery/functions/util/FunDoctype.java | 13 +- .../xquery/functions/util/FunUnEscapeURI.java | 12 +- .../functions/util/FunctionFunction.java | 4 +- .../functions/util/GetFragmentBetween.java | 40 +-- .../xquery/functions/util/GetNodeById.java | 13 +- .../functions/util/GetSequenceType.java | 12 +- .../org/exist/xquery/functions/util/Hash.java | 11 +- .../functions/util/IndexKeyDocuments.java | 17 +- .../functions/util/IndexKeyOccurrences.java | 17 +- .../xquery/functions/util/IndexKeys.java | 8 +- .../xquery/functions/util/IndexType.java | 11 +- .../xquery/functions/util/LineNumber.java | 2 +- .../xquery/functions/util/LogFunction.java | 14 +- .../xquery/functions/util/ModuleInfo.java | 34 +-- .../exist/xquery/functions/util/NodeId.java | 12 +- .../xquery/functions/util/NodeXPath.java | 2 +- .../exist/xquery/functions/util/Parse.java | 10 +- .../exist/xquery/functions/util/Profile.java | 8 +- .../functions/util/PrologFunctions.java | 2 +- .../functions/util/QNameIndexLookup.java | 24 +- .../xquery/functions/util/RandomFunction.java | 16 +- .../functions/util/SharedLockFunction.java | 2 +- .../xquery/functions/util/SystemProperty.java | 11 +- .../xquery/functions/util/SystemTime.java | 17 +- .../org/exist/xquery/functions/util/UUID.java | 11 +- .../xquery/functions/util/UtilModule.java | 26 +- .../org/exist/xquery/functions/util/Wait.java | 11 +- .../functions/validation/GrammarTooling.java | 33 +-- .../xquery/functions/validation/Jaxp.java | 50 ++-- .../xquery/functions/validation/Jaxv.java | 28 +- .../xquery/functions/validation/Jing.java | 22 +- .../xquery/functions/validation/Shared.java | 42 +-- .../validation/ValidationModule.java | 19 +- .../functions/xmldb/FindLastModified.java | 11 +- .../XMLDBAbstractCollectionManipulator.java | 20 +- .../functions/xmldb/XMLDBAuthenticate.java | 15 +- .../xmldb/XMLDBCollectionAvailable.java | 11 +- .../xquery/functions/xmldb/XMLDBCopy.java | 5 +- .../xmldb/XMLDBCreateCollection.java | 10 +- .../xquery/functions/xmldb/XMLDBCreated.java | 16 +- .../functions/xmldb/XMLDBDefragment.java | 10 +- .../xmldb/XMLDBGetChildCollections.java | 11 +- .../xmldb/XMLDBGetChildResources.java | 12 +- .../functions/xmldb/XMLDBGetMimeType.java | 11 +- .../xquery/functions/xmldb/XMLDBHasLock.java | 11 +- .../functions/xmldb/XMLDBLoadFromPattern.java | 29 +- .../functions/xmldb/XMLDBMatchCollection.java | 17 +- .../xquery/functions/xmldb/XMLDBModule.java | 30 +- .../xquery/functions/xmldb/XMLDBMove.java | 12 +- .../xmldb/XMLDBRegisterDatabase.java | 10 +- .../xquery/functions/xmldb/XMLDBReindex.java | 13 +- .../xquery/functions/xmldb/XMLDBRemove.java | 8 +- .../xquery/functions/xmldb/XMLDBRename.java | 12 +- .../functions/xmldb/XMLDBSetMimeType.java | 13 +- .../xquery/functions/xmldb/XMLDBSize.java | 11 +- .../xquery/functions/xmldb/XMLDBStore.java | 35 +-- .../xquery/functions/xmldb/XMLDBTouch.java | 12 +- .../functions/xmldb/XMLDBURIFunctions.java | 18 +- .../xquery/functions/xmldb/XMLDBXUpdate.java | 11 +- .../org/exist/xquery/modules/ModuleUtils.java | 44 ++- .../org/exist/xquery/parser/XQueryAST.java | 4 +- .../xquery/parser/XQueryFunctionAST.java | 2 +- .../exist/xquery/pragmas/ForceIndexUse.java | 2 +- .../exist/xquery/pragmas/NoIndexPragma.java | 2 +- .../org/exist/xquery/pragmas/Optimize.java | 10 +- .../exist/xquery/pragmas/ProfilePragma.java | 2 +- .../org/exist/xquery/pragmas/TimePragma.java | 10 +- .../java/org/exist/xquery/update/Delete.java | 6 +- .../java/org/exist/xquery/update/Insert.java | 19 +- .../org/exist/xquery/update/Modification.java | 22 +- .../java/org/exist/xquery/update/Rename.java | 9 +- .../java/org/exist/xquery/update/Replace.java | 15 +- .../java/org/exist/xquery/update/Update.java | 18 +- .../java/org/exist/xquery/util/DocUtils.java | 27 +- .../java/org/exist/xquery/util/Error.java | 30 +- .../exist/xquery/util/ExpressionDumper.java | 14 +- .../java/org/exist/xquery/util/HTTPUtils.java | 8 +- .../exist/xquery/util/NumberFormatter.java | 6 +- .../exist/xquery/util/SerializerUtils.java | 14 +- .../java/org/exist/xquery/util/URIUtils.java | 12 +- .../xquery/value/AbstractDateTimeValue.java | 40 +-- .../exist/xquery/value/AbstractSequence.java | 2 +- .../org/exist/xquery/value/AnyURIValue.java | 2 +- .../xquery/value/ArrayListValueSequence.java | 6 +- .../org/exist/xquery/value/AtomicValue.java | 2 +- .../xquery/value/Base64BinaryDocument.java | 4 +- .../xquery/value/Base64BinaryValueType.java | 4 +- .../org/exist/xquery/value/BinaryValue.java | 12 +- .../value/BinaryValueFromBinaryString.java | 12 +- .../xquery/value/BinaryValueFromFile.java | 6 +- .../value/BinaryValueFromInputStream.java | 4 +- .../exist/xquery/value/BinaryValueType.java | 4 +- .../org/exist/xquery/value/BooleanValue.java | 6 +- .../exist/xquery/value/ComputableValue.java | 3 +- .../xquery/value/DateTimeStampValue.java | 1 - .../org/exist/xquery/value/DecimalValue.java | 40 ++- .../org/exist/xquery/value/DoubleValue.java | 4 +- .../org/exist/xquery/value/DurationValue.java | 36 +-- .../org/exist/xquery/value/FloatValue.java | 14 +- .../exist/xquery/value/FunctionReference.java | 2 +- .../value/FunctionReturnSequenceType.java | 2 +- .../org/exist/xquery/value/GMonthValue.java | 2 +- .../xquery/value/HexBinaryValueType.java | 4 +- .../org/exist/xquery/value/IntegerValue.java | 4 +- .../exist/xquery/value/ItemComparator.java | 2 +- .../org/exist/xquery/value/NumericValue.java | 5 +- .../xquery/value/OrderedDurationValue.java | 8 +- .../xquery/value/OrderedValueSequence.java | 23 +- .../xquery/value/PreorderedValueSequence.java | 4 +- .../xquery/value/SequenceComparator.java | 2 +- .../org/exist/xquery/value/SequenceType.java | 2 +- .../org/exist/xquery/value/StringValue.java | 6 +- .../org/exist/xquery/value/SubSequence.java | 5 +- .../org/exist/xquery/value/TimeUtils.java | 2 +- .../java/org/exist/xquery/value/Type.java | 152 +++++----- .../org/exist/xquery/value/ValueSequence.java | 32 +- .../xquery/value/YearMonthDurationValue.java | 8 +- .../org/exist/xquery/xqdoc/XQDocHelper.java | 14 +- .../org/exist/xslt/EXistDbInputSource.java | 6 +- .../java/org/exist/xslt/EXistDbSource.java | 12 +- .../java/org/exist/xslt/EXistDbXMLReader.java | 13 +- .../java/org/exist/xslt/EXistURIResolver.java | 19 +- .../main/java/org/exist/xslt/Stylesheet.java | 9 +- .../xslt/StylesheetResolverAndCompiler.java | 31 +- .../java/org/exist/xslt/TemplatesFactory.java | 27 +- .../xslt/TransformerFactoryAllocator.java | 29 +- .../org/exist/xslt/XSLTErrorsListener.java | 7 +- .../main/java/org/exist/xupdate/Append.java | 6 +- .../java/org/exist/xupdate/Conditional.java | 25 +- .../main/java/org/exist/xupdate/Insert.java | 21 +- .../java/org/exist/xupdate/Modification.java | 43 ++- .../main/java/org/exist/xupdate/Rename.java | 8 +- .../main/java/org/exist/xupdate/Replace.java | 13 +- .../main/java/org/exist/xupdate/Update.java | 15 +- .../org/exist/xupdate/XUpdateProcessor.java | 82 +++--- .../src/test/java/org/exist/Indexer2Test.java | 24 +- .../src/test/java/org/exist/Indexer3Test.java | 87 +++--- .../src/test/java/org/exist/IndexerTest.java | 29 +- .../java/org/exist/TestDataGenerator.java | 10 +- .../backup/DeepEmbeddedBackupRestoreTest.java | 4 +- .../exist/backup/SystemExportFiltersTest.java | 4 +- .../exist/backup/SystemExportImportTest.java | 34 +-- .../org/exist/backup/XMLDBRestoreTest.java | 17 +- .../exist/client/InteractiveClientTest.java | 6 +- .../BasicPermissionsTableModelTest.java | 43 +-- .../collections/CollectionOrderTest.java | 2 +- .../collections/CollectionRemovalTest.java | 17 +- .../collections/CollectionStoreTest.java | 2 +- .../exist/collections/CollectionURITest.java | 4 +- .../exist/collections/ConcurrencyTest.java | 9 +- .../InitCollectionConfigurationTest.java | 3 - .../exist/collections/OpenCollectionTest.java | 2 +- .../collections/triggers/AnotherTrigger.java | 4 +- .../triggers/CollectionTriggerTest.java | 6 +- .../triggers/CountingCollectionTrigger.java | 26 +- .../triggers/HistoryTriggerTest.java | 6 +- .../collections/triggers/SAXTriggerTest.java | 16 +- .../collections/triggers/TestTrigger.java | 8 +- .../triggers/TriggerConfigTest.java | 22 +- .../triggers/XQueryTrigger2Test.java | 64 ++-- .../triggers/XQueryTriggerChainTest.java | 26 +- .../triggers/XQueryTriggerSetGidTest.java | 22 +- .../triggers/XQueryTriggerSetUidTest.java | 26 +- .../triggers/XQueryTriggerTest.java | 79 +++-- .../org/exist/config/ConfigurableObject.java | 10 +- .../org/exist/config/ConfigurableObject2.java | 8 +- .../org/exist/config/ConfigurableTest.java | 14 +- .../src/test/java/org/exist/config/Sp.java | 2 +- .../src/test/java/org/exist/config/Spice.java | 4 +- .../org/exist/config/TwoDatabasesTest.java | 16 +- .../config/mapping/ConfigurableObject.java | 4 +- .../config/mapping/ConfigurableTest.java | 9 +- .../org/exist/config/mapping/MappedClass.java | 8 +- .../org/exist/config/mapping/SubConfig.java | 4 +- .../GetReleaseBrokerDeadlocksTest.java | 25 +- .../org/exist/dom/memtree/DOMIndexerTest.java | 19 +- .../java/org/exist/dom/memtree/DOMTest.java | 21 +- ...ocumentBuilderReceiverIntegrationTest.java | 5 +- .../memtree/DocumentBuilderReceiverTest.java | 8 +- .../exist/dom/memtree/DocumentImplTest.java | 4 +- .../org/exist/dom/memtree/MemtreeTest.java | 2 +- .../dom/persistent/BasicNodeSetTest.java | 31 +- .../dom/persistent/CDataIntergationTest.java | 6 +- .../persistent/DefaultDocumentSetTest.java | 7 +- .../org/exist/dom/persistent/DocTypeTest.java | 29 +- .../dom/persistent/DocumentImplTest.java | 13 +- .../dom/persistent/NewArrayNodeSetTest.java | 2 +- .../org/exist/dom/persistent/NodeTest.java | 6 +- .../dom/persistent/PersistentDomTest.java | 6 +- .../exist/dom/persistent/SymbolTableTest.java | 11 +- .../exist/dom/persistent/TextImplTest.java | 8 +- .../org/exist/dom/persistent/XMLUtilTest.java | 4 +- .../http/AuditTrailSessionListenerTest.java | 5 +- .../java/org/exist/http/RESTServiceTest.java | 37 +-- .../exist/http/urlrewrite/ControllerTest.java | 3 +- .../exist/http/urlrewrite/URLRewriteTest.java | 22 +- .../http/urlrewrite/URLRewritingTest.java | 2 +- .../http/urlrewrite/XQueryURLRewriteTest.java | 22 +- .../org/exist/numbering/DLNStorageTest.java | 2 +- .../java/org/exist/numbering/DLNTest.java | 19 +- .../exist/security/AbstractAccountTest.java | 15 +- .../security/AbstractApiSecurityTest.java | 32 +- .../org/exist/security/AbstractGroupTest.java | 14 +- .../org/exist/security/AbstractRealmTest.java | 15 +- .../AbstractSecurityManagerRoundtripTest.java | 23 +- .../java/org/exist/security/AccountTest.java | 7 +- .../security/FnCollectionSecurityTest.java | 6 +- .../org/exist/security/FnDocSecurityTest.java | 6 +- .../exist/security/RestApiSecurityTest.java | 12 +- .../exist/security/SecurityManagerTest.java | 4 +- .../security/SimpleACLPermissionTest.java | 44 ++- .../security/UnixStylePermissionTest.java | 274 +++++++++--------- .../org/exist/security/XMLDBSecurityTest.java | 67 ++--- .../exist/security/XmldbApiSecurityTest.java | 8 +- .../BackupRestoreSecurityPrincipalsTest.java | 10 +- .../aider/UnixStylePermissionAiderTest.java | 66 ++--- .../stax/EmbeddedXMLStreamReaderTest.java | 2 +- .../exist/storage/AbstractRecoverTest.java | 4 +- .../org/exist/storage/AbstractUpdateTest.java | 2 +- .../java/org/exist/storage/AppendTest.java | 5 +- .../org/exist/storage/BFileRecoverTest.java | 10 +- .../org/exist/storage/BTreeRecoverTest.java | 8 +- .../org/exist/storage/BinaryDocumentTest.java | 4 +- .../storage/BrokerPoolNoRecoveryTest.java | 6 +- .../exist/storage/BrokerPoolServiceTest.java | 7 +- .../org/exist/storage/BrokerPoolTest.java | 2 +- .../org/exist/storage/CollectionTest.java | 17 +- .../storage/ConcurrentBrokerPoolTest.java | 4 +- .../exist/storage/ConcurrentStoreTest.java | 17 +- .../storage/CopyCollectionRecoveryTest.java | 19 +- .../org/exist/storage/CopyCollectionTest.java | 6 +- .../storage/CopyResourceRecoveryTest.java | 15 +- .../org/exist/storage/CopyResourceTest.java | 32 +- .../org/exist/storage/DOMFileRecoverTest.java | 20 +- .../org/exist/storage/DataBackupTest.java | 10 +- .../org/exist/storage/DirtyShutdownTest.java | 18 +- .../org/exist/storage/IndexManagerTest.java | 15 +- .../org/exist/storage/LargeValuesTest.java | 5 +- .../exist/storage/ModificationTimeTest.java | 9 +- .../storage/MoveCollectionRecoveryTest.java | 12 +- .../org/exist/storage/MoveCollectionTest.java | 6 +- .../storage/MoveOverwriteCollectionTest.java | 21 +- .../storage/MoveOverwriteResourceTest.java | 15 +- .../storage/MoveResourceRecoveryTest.java | 21 +- .../storage/NativeBrokerLockingTest.java | 60 ++-- .../exist/storage/RangeIndexUpdateTest.java | 7 +- .../org/exist/storage/RecoverBinary2Test.java | 20 +- .../org/exist/storage/RecoverBinaryTest.java | 14 +- .../org/exist/storage/RecoverXmlTest.java | 6 +- .../java/org/exist/storage/Recovery2Test.java | 20 +- .../java/org/exist/storage/Recovery3Test.java | 19 +- .../java/org/exist/storage/RecoveryTest.java | 19 +- .../exist/storage/ReindexRecoveryTest.java | 11 +- .../java/org/exist/storage/ReindexTest.java | 2 +- .../org/exist/storage/RemoveCollectionIT.java | 13 +- .../storage/RemoveRootCollectionTest.java | 10 +- .../java/org/exist/storage/RemoveTest.java | 9 +- .../java/org/exist/storage/RenameTest.java | 9 +- .../java/org/exist/storage/ReplaceTest.java | 9 +- .../java/org/exist/storage/ResourceTest.java | 16 +- .../java/org/exist/storage/ShutdownTest.java | 11 +- .../org/exist/storage/StartupLockingTest.java | 17 +- .../org/exist/storage/StartupTriggerTest.java | 6 +- .../org/exist/storage/StoreBinaryTest.java | 20 +- .../org/exist/storage/StoreResourceTest.java | 6 +- .../exist/storage/UpdateAttributeTest.java | 7 +- .../org/exist/storage/UpdateRecoverTest.java | 21 +- .../java/org/exist/storage/UpdateTest.java | 7 +- .../exist/storage/ValueIndexFactoryTest.java | 9 +- .../exist/storage/XIncludeSerializerTest.java | 33 ++- .../exist/storage/blob/BlobStoreImplTest.java | 13 +- .../storage/blob/BlobStoreRecoveryTest.java | 4 +- .../org/exist/storage/btree/BTreeTest.java | 14 +- .../storage/io/VariableByteStreamTest.java | 20 +- .../storage/journal/AbstractJournalTest.java | 92 ++++-- .../storage/journal/JournalBinaryTest.java | 26 +- .../exist/storage/journal/JournalTest.java | 12 +- .../exist/storage/journal/JournalXmlTest.java | 4 +- .../org/exist/storage/journal/LsnTest.java | 4 +- .../storage/lock/CollectionLocksTest.java | 4 +- .../org/exist/storage/lock/DeadlockIT.java | 37 +-- .../exist/storage/lock/DocumentLocksTest.java | 4 +- .../lock/GetXMLResourceNoLockTest.java | 28 +- .../exist/storage/lock/LockManagerTest.java | 12 +- .../exist/storage/lock/ProtectedModeTest.java | 9 +- .../statistics/StatisticsIndexTest.java | 8 +- .../txn/ConcurrentTransactionsTest.java | 8 +- .../storage/txn/CountingTxnListener.java | 4 +- .../txn/TransactionManagerTestHelper.java | 4 +- .../org/exist/storage/util/PauseFunction.java | 14 +- .../exist/storage/util/TestUtilModule.java | 15 +- .../test/runner/InspectLineSourceTest.java | 7 +- .../exist/test/runner/XMLTestRunnerTest.java | 5 +- .../test/runner/XQueryTestRunnerTest.java | 5 +- .../test/runner/XSuiteDebuggabilityTest.java | 4 +- .../org/exist/util/CodePointStringTest.java | 6 +- .../org/exist/util/DOMSerializerTest.java | 21 +- .../java/org/exist/util/MimeTableTest.java | 8 +- .../java/org/exist/util/XMLStringTest.java | 10 +- .../hashtable/SequencedLongHashMapTest.java | 9 +- .../util/io/ByteBufferInputStreamTest.java | 64 ++-- ...amNonMarkableByteArrayInputStreamTest.java | 117 ++++---- .../util/io/CachingFilterInputStreamTest.java | 104 ++++--- .../exist/util/io/ContentFilePoolTest.java | 6 +- .../io/FilterInputStreamCacheMonitorTest.java | 4 +- .../io/MemoryContentsInputStreamTest.java | 8 +- .../io/MemoryContentsOutputStreamTest.java | 7 +- .../util/io/OverflowToDiskStreamTest.java | 7 +- .../exist/util/io/VirtualTempPathTest.java | 5 +- .../org/exist/util/pool/NodePoolTest.java | 7 +- .../util/serializer/EXISerializerTest.java | 22 +- .../util/serializer/HTML5WriterTest.java | 4 +- .../util/serializer/json/JSONObjectTest.java | 4 +- .../util/serializer/json/JSONWriterTest.java | 3 +- .../exist/util/sorters/FastQSortTester.java | 8 +- .../org/exist/util/sorters/HSortTester.java | 8 +- .../exist/util/sorters/HeapSortTester.java | 8 +- .../util/sorters/InsertionSortTester.java | 8 +- .../org/exist/util/sorters/ListChecker.java | 10 +- .../util/sorters/NodeProxyByIdChecker.java | 6 +- .../exist/util/sorters/NodeProxyChecker.java | 6 +- .../exist/util/sorters/PlainArrayChecker.java | 11 +- .../util/sorters/SortComparatorTest.java | 8 +- .../java/org/exist/util/sorters/SortTest.java | 14 +- .../exist/util/sorters/SortTestNodeId.java | 13 +- .../exist/util/sorters/SortTestNodeProxy.java | 14 +- .../util/sorters/SortingAlgorithmTester.java | 8 +- .../CollectionConfigSchema6000Test.java | 2 +- .../validation/DatabaseCollectionTest.java | 4 +- ...tabaseInsertResourcesNoValidationTest.java | 4 +- ...baseInsertResourcesWithValidationTest.java | 4 +- .../org/exist/validation/GrammarPoolTest.java | 4 +- .../java/org/exist/validation/TestTools.java | 8 +- .../java/org/exist/w3c/tests/TestCase.java | 150 +++++----- .../exist/xmldb/BinaryResourceUpdateTest.java | 8 +- .../xmldb/CollectionConfigurationTest.java | 91 +++--- .../java/org/exist/xmldb/CollectionTest.java | 3 +- .../org/exist/xmldb/ContentAsDOMTest.java | 27 +- .../java/org/exist/xmldb/CopyMoveTest.java | 14 +- .../exist/xmldb/CreateCollectionsTest.java | 31 +- .../java/org/exist/xmldb/DOMJUnitTest.java | 2 +- .../test/java/org/exist/xmldb/DOMTest.java | 25 +- .../java/org/exist/xmldb/IndexingTest.java | 58 ++-- .../exist/xmldb/LocalXMLResourceDOMTest.java | 4 +- .../java/org/exist/xmldb/MultiDBTest.java | 4 +- .../org/exist/xmldb/RemoteCollectionTest.java | 4 +- .../java/org/exist/xmldb/RemoteDBTest.java | 6 +- .../exist/xmldb/RemoteDatabaseImplTest.java | 2 +- .../java/org/exist/xmldb/RemoteQueryTest.java | 17 +- .../org/exist/xmldb/RenameCollectionTest.java | 2 +- .../java/org/exist/xmldb/ResourceSetTest.java | 4 +- .../java/org/exist/xmldb/ResourceTest.java | 38 +-- .../org/exist/xmldb/SerializationTest.java | 5 +- .../test/java/org/exist/xmldb/ShutdownIT.java | 6 +- .../exist/xmldb/TestEXistXMLSerialize.java | 50 ++-- .../org/exist/xmldb/TreeLevelOrderTest.java | 2 +- .../java/org/exist/xmldb/XmldbURITest.java | 41 ++- .../concurrent/ConcurrentAttrUpdateTest.java | 8 +- .../xmldb/concurrent/ConcurrentQueryTest.java | 8 +- .../concurrent/ConcurrentQueryUpdateTest.java | 6 +- .../xmldb/concurrent/ConcurrentTestBase.java | 12 +- .../concurrent/ConcurrentXUpdateTest.java | 8 +- .../org/exist/xmldb/concurrent/DBUtils.java | 10 +- .../exist/xmldb/concurrent/DeadlockTest.java | 2 +- .../exist/xmldb/concurrent/FragmentsTest.java | 2 +- .../exist/xmldb/concurrent/XMLGenerator.java | 8 +- .../exist/xmldb/concurrent/action/Action.java | 4 +- .../action/AttributeUpdateAction.java | 4 +- .../action/CreateCollectionAction.java | 8 +- .../action/MultiResourcesAction.java | 10 +- .../concurrent/action/RemoveAppendAction.java | 7 +- .../action/ReplaceResourceAction.java | 8 +- .../concurrent/action/TextUpdateAction.java | 6 +- .../xmldb/concurrent/action/XQueryAction.java | 6 +- .../exist/xmlrpc/CachedContentFileTest.java | 4 +- .../java/org/exist/xmlrpc/MimeTypeTest.java | 12 +- .../org/exist/xmlrpc/MoveResourceTest.java | 5 +- .../org/exist/xmlrpc/QuerySessionTest.java | 14 +- .../java/org/exist/xmlrpc/XmlRpcTest.java | 63 ++-- .../java/org/exist/xqj/MarshallerTest.java | 19 +- .../org/exist/xquery/AbsolutePathTests.java | 5 +- .../exist/xquery/AbstractBinariesTest.java | 6 +- .../AbstractDescendantOrSelfNodeKindTest.java | 4 +- .../org/exist/xquery/AnnotationsTest.java | 9 +- .../java/org/exist/xquery/CleanupTest.java | 16 +- .../xquery/ConstructedNodesRecoveryTest.java | 18 +- .../exist/xquery/ConstructedNodesTest.java | 12 +- .../org/exist/xquery/CountExpressionTest.java | 4 +- .../xquery/DeferredFunctionCallTest.java | 10 +- .../exist/xquery/DuplicateAttributesTest.java | 13 +- .../exist/xquery/EmbeddedBinariesTest.java | 2 +- .../java/org/exist/xquery/EntitiesTest.java | 7 +- .../exist/xquery/ForwardReferenceTest.java | 20 +- .../org/exist/xquery/ImportModuleTest.java | 2 +- .../org/exist/xquery/JavaFunctionsTest.java | 4 +- .../org/exist/xquery/JavaMethodsTest.java | 2 +- .../test/java/org/exist/xquery/LexerTest.java | 11 +- .../org/exist/xquery/ModuleImportTest.java | 2 - .../org/exist/xquery/NamespaceUpdateTest.java | 2 +- .../java/org/exist/xquery/OpNumericTest.java | 4 +- .../java/org/exist/xquery/OptimizerTest.java | 12 +- .../xquery/ReservedNamesConflictTest.java | 6 +- .../org/exist/xquery/RestBinariesTest.java | 13 +- .../test/java/org/exist/xquery/SeqOpTest.java | 12 +- .../org/exist/xquery/SpecialNamesTest.java | 7 +- .../org/exist/xquery/StoredModuleTest.java | 24 +- .../java/org/exist/xquery/TestModule.java | 10 +- .../xquery/TestXPathOpOrSpecialCase.java | 1 - .../test/java/org/exist/xquery/UnionTest.java | 27 +- .../exist/xquery/ValueIndexByQNameTest.java | 2 +- .../java/org/exist/xquery/ValueIndexTest.java | 28 +- .../java/org/exist/xquery/VariablesTest.java | 2 +- .../org/exist/xquery/WindowClauseTest.java | 4 +- .../java/org/exist/xquery/XPathQueryTest.java | 76 +++-- .../xquery/XQueryContextAttributesTest.java | 6 +- .../org/exist/xquery/XQueryContextTest.java | 6 +- .../org/exist/xquery/XQueryFunctionsTest.java | 14 +- .../XQueryProcessingInstructionTest.java | 6 +- .../java/org/exist/xquery/XQueryTest.java | 78 +++-- .../org/exist/xquery/XQueryUpdateTest.java | 8 +- .../org/exist/xquery/XmldbBinariesTest.java | 2 +- .../xquery/functions/fn/CollectionTest.java | 6 +- .../exist/xquery/functions/fn/DocTest.java | 21 +- .../exist/xquery/functions/fn/ExtDocTest.java | 5 +- .../xquery/functions/fn/FunLangTest.java | 4 +- .../xquery/functions/fn/FunNumberTest.java | 3 +- .../functions/fn/FunSubSequenceTest.java | 2 +- .../functions/fn/FunUnparsedTextTest.java | 4 +- .../functions/integer/IntegerPictureTest.java | 8 +- .../xquery/functions/request/GetDataTest.java | 30 +- .../functions/request/GetHeaderTest.java | 22 +- .../functions/request/GetParameterTest.java | 33 +-- .../xquery/functions/request/PatchTest.java | 25 +- .../functions/response/StreamBinaryTest.java | 17 +- ...ntManagementFunctionRemoveAccountTest.java | 5 +- ...roupManagementFunctionRemoveGroupTest.java | 5 +- ...mbershipFunctionRemoveGroupMemberTest.java | 8 +- .../securitymanager/IdFunctionTest.java | 8 +- .../PermissionsFunctionChmodTest.java | 6 +- .../PermissionsFunctionChownTest.java | 8 +- ...PermissionsFunctionModeConversionTest.java | 9 +- .../functions/transform/TransformTest.java | 7 +- .../functions/util/Base64FunctionsTest.java | 6 +- .../util/BaseConversionFunctionsTest.java | 5 +- .../functions/util/BaseConverterTest.java | 7 +- .../functions/util/BinaryToStringTest.java | 1 + .../exist/xquery/functions/util/EvalTest.java | 14 +- .../xquery/functions/util/ExpandTest.java | 8 +- .../validate/AdditionalJingXsdRngTest.java | 7 +- .../validate/JaxpDtdCatalogTest.java | 17 +- .../functions/validate/JaxpParseTest.java | 18 +- .../validate/JaxpXsdCatalogTest.java | 17 +- .../xquery/functions/validate/JaxvTest.java | 18 +- .../functions/validate/JingOnvdlTest.java | 24 +- .../functions/validate/JingRelaxNgTest.java | 17 +- .../validate/JingSchematronTest.java | 17 +- .../functions/validate/JingXsdTest.java | 18 +- .../functions/validate/ParseDtdNokTest.java | 17 +- .../functions/validate/ParseXsdNokTest.java | 17 +- .../xquery/functions/xmldb/DbStore2Test.java | 14 +- .../xquery/functions/xmldb/DbStoreTest.java | 2 +- .../xquery3/DeclareVariableTest.java | 4 +- .../xquery/functions/xquery3/SwitchTest.java | 3 +- .../functions/xquery3/TryCatchTest.java | 9 +- .../xquery/update/AbstractTestUpdate.java | 4 +- .../xquery/update/IndexIntegrationTest.java | 2 +- .../value/AbstractDateTimeValueTest.java | 1 - .../value/AbstractTimeRelatedTestCase.java | 8 +- .../org/exist/xquery/value/AnyURITest.java | 4 +- .../exist/xquery/value/Base64BinaryTest.java | 3 +- .../value/Base64BinaryValueTypeTest.java | 13 +- .../BinaryValueFromBinaryStringTest.java | 8 +- .../value/BinaryValueFromInputStreamTest.java | 12 +- .../exist/xquery/value/BinaryValueTest.java | 7 +- .../xquery/value/BinaryValueTypeTest.java | 9 +- .../java/org/exist/xquery/value/DateTest.java | 31 +- .../org/exist/xquery/value/DateTimeTest.java | 4 +- .../xquery/value/DayTimeDurationTest.java | 4 +- .../exist/xquery/value/DoubleValueTest.java | 2 +- .../xquery/value/HexBinaryValueTypeTest.java | 1 + .../xquery/value/MockBinaryValueManager.java | 4 +- .../xquery/value/NumericOpPromotionTest.java | 9 +- .../value/OrderedValueSequenceTest.java | 4 +- .../java/org/exist/xquery/value/TimeTest.java | 4 +- .../exist/xquery/value/ValueSequenceTest.java | 2 +- .../xquery/value/YearMonthDurationTest.java | 4 +- .../xslt/TransformerFactoryAllocatorTest.java | 25 +- .../org/exist/xupdate/RemoveAppendTest.java | 20 +- .../java/org/exist/xupdate/StressTest.java | 18 +- .../java/org/exist/xupdate/XUpdateTest.java | 43 ++- exist-samples/pom.xml | 7 +- .../main/java/org/exist/samples/Samples.java | 2 +- .../java/org/exist/service/ExistDbDaemon.java | 6 +- .../start/CompatibleJavaVersionCheck.java | 2 +- .../start/classloader/ReflectionUtils.java | 2 +- .../contentextraction/ContentExtraction.java | 8 +- .../contentextraction/ContentReceiver.java | 14 +- .../xquery/ContentExtractionModule.java | 23 +- .../xquery/ContentFunctions.java | 28 +- .../exist/exiftool/xquery/ExiftoolModule.java | 25 +- .../exiftool/xquery/MetadataFunctions.java | 28 +- .../org/expath/exist/HttpClientModule.java | 18 +- .../org/expath/exist/SendRequestFunction.java | 21 +- .../org/expath/exist/ZipEntryFunctions.java | 38 +-- .../org/expath/exist/ZipFileFunctions.java | 38 +-- .../main/java/org/expath/exist/ZipModule.java | 15 +- .../httpclient/model/exist/EXistResult.java | 20 +- .../tools/model/exist/EXistElement.java | 23 +- .../tools/model/exist/EXistSequence.java | 22 +- .../java/org/expath/exist/HttpClientTest.java | 2 +- .../AbstractRequestModuleFunction.java | 2 +- .../modules/request/ConnectionFunctions.java | 22 +- .../modules/request/CookieFunctions.java | 13 +- .../modules/request/GeneralFunctions.java | 4 +- .../modules/request/HeaderFunctions.java | 18 +- .../modules/request/ParameterFunctions.java | 24 +- .../modules/request/RequestModule.java | 9 +- .../exquery/modules/request/URIFunctions.java | 30 +- .../RestXqServiceCompiledXQueryCache.java | 5 +- .../restxq/impl/ExistXqueryRegistry.java | 31 +- .../impl/ResourceFunctionExecutorImpl.java | 22 +- .../RestXqServiceCompiledXQueryCacheImpl.java | 12 +- .../restxq/impl/RestXqServiceImpl.java | 24 +- .../impl/RestXqServiceRegistryManager.java | 4 +- .../RestXqServiceRegistryPersistence.java | 37 +-- .../impl/RestXqServiceSerializerImpl.java | 17 +- .../exquery/restxq/impl/RestXqServlet.java | 7 +- .../restxq/impl/RestXqStartupTrigger.java | 5 +- .../exquery/restxq/impl/RestXqTrigger.java | 5 +- .../exquery/restxq/impl/XQueryCompiler.java | 9 +- .../exquery/restxq/impl/XQueryInspector.java | 17 +- .../impl/adapters/AnnotationAdapter.java | 9 +- .../DomEnhancingNodeProxyAdapter.java | 13 +- .../adapters/FunctionSignatureAdapter.java | 5 +- .../adapters/HttpServletRequestAdapter.java | 18 +- .../adapters/HttpServletResponseAdapter.java | 7 +- .../restxq/impl/adapters/SequenceAdapter.java | 5 +- .../restxq/impl/adapters/TypeAdapter.java | 4 +- .../restxq/impl/xquery/RegistryFunctions.java | 45 +-- .../restxq/impl/xquery/RestXqModule.java | 15 +- .../restxq/impl/xquery/UriFunctions.java | 4 +- .../impl/xquery/exist/ExistRestXqModule.java | 13 +- .../impl/xquery/exist/RegistryFunctions.java | 58 ++-- .../impl/AbstractClassIntegrationTest.java | 2 +- .../impl/AbstractInstanceIntegrationTest.java | 2 +- .../restxq/impl/AbstractIntegrationTest.java | 6 +- .../restxq/impl/ExistXqueryRegistryTest.java | 3 +- .../restxq/impl/MediaTypeIntegrationTest.java | 8 +- ...portCircularDependencyIntegrationTest.java | 10 +- .../DomEnhancingNodeProxyAdapterTest.java | 3 - .../indexing/lucene/AbstractFieldConfig.java | 12 +- .../exist/indexing/lucene/AnalyzerConfig.java | 23 +- .../lucene/AnalyzingQueryRewriter.java | 8 +- .../lucene/ClassicQueryParserWrapper.java | 4 +- .../indexing/lucene/DefaultTextExtractor.java | 8 +- .../org/exist/indexing/lucene/FieldType.java | 14 +- .../exist/indexing/lucene/LuceneConfig.java | 63 ++-- .../indexing/lucene/LuceneFacetConfig.java | 4 +- .../indexing/lucene/LuceneFieldConfig.java | 6 +- .../exist/indexing/lucene/LuceneIndex.java | 36 ++- .../indexing/lucene/LuceneIndexConfig.java | 59 ++-- .../indexing/lucene/LuceneIndexWorker.java | 92 +++--- .../exist/indexing/lucene/LuceneMatch.java | 2 +- .../indexing/lucene/LuceneMatchListener.java | 32 +- .../org/exist/indexing/lucene/LuceneUtil.java | 14 +- .../lucene/LuceneVectorFieldConfig.java | 9 +- .../indexing/lucene/MarkableTokenFilter.java | 12 +- .../indexing/lucene/NodePathPattern.java | 34 +-- .../indexing/lucene/PlainTextHighlighter.java | 35 ++- .../indexing/lucene/PlainTextIndexConfig.java | 25 +- .../indexing/lucene/QueryParserWrapper.java | 2 +- .../lucene/StandardQueryParserWrapper.java | 4 +- .../org/exist/indexing/lucene/XMLToQuery.java | 88 +++--- .../EnglishStopwordsStandardAnalyzer.java | 7 +- .../NoDiacriticsStandardAnalyzer.java | 8 +- .../exist/xquery/modules/lucene/Facets.java | 8 +- .../exist/xquery/modules/lucene/Field.java | 4 +- .../exist/xquery/modules/lucene/GetField.java | 12 +- .../exist/xquery/modules/lucene/Index.java | 15 +- .../xquery/modules/lucene/InspectIndex.java | 15 +- .../modules/lucene/LuceneIndexKeys.java | 6 +- .../xquery/modules/lucene/LuceneModule.java | 20 +- .../exist/xquery/modules/lucene/Optimize.java | 7 +- .../exist/xquery/modules/lucene/Query.java | 21 +- .../xquery/modules/lucene/QueryField.java | 4 +- .../modules/lucene/QueryFieldVector.java | 6 +- .../xquery/modules/lucene/QueryOptions.java | 50 ++-- .../xquery/modules/lucene/QueryVector.java | 7 +- .../xquery/modules/lucene/RemoveIndex.java | 8 +- .../exist/xquery/modules/lucene/Score.java | 18 +- .../exist/xquery/modules/lucene/Search.java | 10 +- .../indexing/lucene/ConcurrencyTest.java | 27 +- .../FacetPollutionJavaReproducerTest.java | 10 +- .../indexing/lucene/LuceneIndexTest.java | 45 ++- .../lucene/LuceneMatchListenerTest.java | 36 ++- .../exist/indexing/lucene/OptimizerTest.java | 14 +- .../lucene/SerializeAttrMatchesTest.java | 2 +- .../lucene/VectorSearchEmbeddingTest.java | 6 +- .../org/exist/indexing/ngram/NGramIndex.java | 15 +- .../indexing/ngram/NGramIndexConfig.java | 2 +- .../indexing/ngram/NGramIndexWorker.java | 69 ++--- .../exist/xquery/modules/ngram/AddMatch.java | 24 +- .../modules/ngram/HighlightMatches.java | 33 +-- .../xquery/modules/ngram/NGramModule.java | 9 +- .../xquery/modules/ngram/NGramSearch.java | 120 ++++---- .../ngram/query/AlternativeStrings.java | 21 +- .../modules/ngram/query/EmptyExpression.java | 6 +- .../ngram/query/EvaluatableExpression.java | 6 +- .../modules/ngram/query/FixedString.java | 15 +- .../xquery/modules/ngram/query/Wildcard.java | 4 +- .../query/WildcardedExpressionSequence.java | 35 ++- .../query/WildcardedExpressionTriple.java | 14 +- .../exist/indexing/ngram/CustomIndexTest.java | 13 +- .../indexing/ngram/MatchListenerTest.java | 35 +-- .../range/ComplexRangeIndexConfigElement.java | 20 +- .../indexing/range/ComplexTextCollector.java | 14 +- .../org/exist/indexing/range/RangeIndex.java | 4 +- .../indexing/range/RangeIndexAnalyzer.java | 4 +- .../indexing/range/RangeIndexConfig.java | 16 +- .../RangeIndexConfigAttributeCondition.java | 8 +- .../range/RangeIndexConfigElement.java | 26 +- .../indexing/range/RangeIndexConfigField.java | 13 +- .../exist/indexing/range/RangeIndexDoc.java | 12 +- .../indexing/range/RangeIndexWorker.java | 117 ++++---- .../indexing/range/SimpleTextCollector.java | 6 +- .../exist/indexing/range/TextCollector.java | 4 +- .../range/conversion/DateConverter.java | 2 +- .../xquery/modules/range/FieldLookup.java | 24 +- .../exist/xquery/modules/range/IndexKeys.java | 8 +- .../exist/xquery/modules/range/Lookup.java | 44 ++- .../exist/xquery/modules/range/Optimize.java | 7 +- .../modules/range/OptimizeFieldPragma.java | 5 +- .../modules/range/RangeIndexModule.java | 14 +- .../modules/range/RangeQueryRewriter.java | 10 +- .../Issue4074IndexKeysServletContextTest.java | 2 +- .../org/exist/indexing/sort/SortIndex.java | 5 +- .../exist/indexing/sort/SortIndexWorker.java | 22 +- .../xquery/modules/sort/CreateOrderIndex.java | 61 ++-- .../exist/xquery/modules/sort/GetIndex.java | 5 +- .../exist/xquery/modules/sort/HasIndex.java | 2 +- .../xquery/modules/sort/RemoveIndex.java | 5 +- .../exist/xquery/modules/sort/SortModule.java | 10 +- .../spatial/AbstractGMLJDBCIndex.java | 16 +- .../spatial/AbstractGMLJDBCIndexWorker.java | 144 +++++---- .../exist/indexing/spatial/GMLHSQLIndex.java | 49 ++-- .../indexing/spatial/GMLHSQLIndexWorker.java | 76 ++--- .../indexing/spatial/GMLIndexConfig.java | 6 +- .../modules/spatial/FunGMLProducers.java | 93 +++--- .../spatial/FunGeometricProperties.java | 28 +- .../modules/spatial/FunSpatialSearch.java | 39 ++- .../xquery/modules/spatial/SpatialModule.java | 9 +- .../exist/indexing/spatial/GMLIndexTest.java | 33 +-- .../lucene/VectorSearchEmbeddingIT.java | 4 +- .../xquery/modules/cache/CacheFunctions.java | 3 +- .../xquery/modules/cache/CacheModule.java | 18 +- .../compression/AbstractCompressFunction.java | 10 +- .../compression/CompressionModule.java | 2 +- .../modules/compression/DeflateFunction.java | 10 +- .../modules/compression/EntryFunctions.java | 21 +- .../modules/compression/GZipFunction.java | 7 +- .../modules/compression/InflateFunction.java | 8 +- .../modules/compression/TarFunction.java | 8 +- .../modules/compression/UnGZipFunction.java | 7 +- .../modules/compression/UnTarFunction.java | 6 +- .../modules/compression/ZipFunction.java | 6 +- .../modules/counter/CounterFunctions.java | 19 +- .../xquery/modules/counter/CounterModule.java | 14 +- .../xquery/modules/counter/Counters.java | 27 +- .../xquery/modules/counter/CounterTest.java | 6 +- .../modules/cqlparser/CQLParserModule.java | 15 +- .../xquery/modules/cqlparser/ParseCQL.java | 37 +-- .../xquery/modules/example/EchoFunction.java | 13 +- .../xquery/modules/example/ExampleModule.java | 15 +- .../xquery/modules/exi/DecodeExiFunction.java | 30 +- .../exist/xquery/modules/exi/EXIUtils.java | 14 +- .../xquery/modules/exi/EncodeExiFunction.java | 24 +- .../exist/xquery/modules/exi/ExiModule.java | 18 +- .../java/org/exist/repo/ExampleFunctions.java | 2 +- .../java/org/exist/repo/ExampleModule.java | 2 +- .../java/org/exist/repo/ExampleTrigger.java | 2 +- .../org/exist/repo/ExampleModuleTest.java | 4 +- .../xquery/modules/expathrepo/Deploy.java | 31 +- .../modules/expathrepo/EXPathErrorCode.java | 22 +- .../expathrepo/ExpathPackageModule.java | 12 +- .../xquery/modules/expathrepo/GetAppRoot.java | 2 +- .../modules/expathrepo/GetResource.java | 9 +- .../modules/expathrepo/InstallFunction.java | 29 +- .../modules/expathrepo/ListFunction.java | 15 +- .../modules/expathrepo/RemoveFunction.java | 8 +- .../java/org/exist/repo/PackageTriggerIT.java | 9 +- .../exist/xquery/modules/file/Directory.java | 34 +-- .../xquery/modules/file/DirectoryCreate.java | 24 +- .../xquery/modules/file/DirectoryList.java | 23 +- .../exist/xquery/modules/file/FileDelete.java | 16 +- .../exist/xquery/modules/file/FileExists.java | 20 +- .../xquery/modules/file/FileIsDirectory.java | 20 +- .../xquery/modules/file/FileIsReadable.java | 16 +- .../xquery/modules/file/FileIsWriteable.java | 18 +- .../exist/xquery/modules/file/FileModule.java | 21 +- .../xquery/modules/file/FileModuleHelper.java | 8 +- .../exist/xquery/modules/file/FileMove.java | 22 +- .../exist/xquery/modules/file/FileRead.java | 24 +- .../xquery/modules/file/FileReadBinary.java | 15 +- .../xquery/modules/file/FileReadUnicode.java | 26 +- .../xquery/modules/file/SerializeToFile.java | 14 +- .../org/exist/xquery/modules/file/Sync.java | 51 ++-- .../xquery/modules/file/UnicodeReader.java | 19 +- .../modules/file/AbstractBinariesTest.java | 6 +- .../modules/file/EmbeddedBinariesTest.java | 2 +- .../xquery/modules/file/RestBinariesTest.java | 12 +- .../modules/file/XmldbBinariesTest.java | 2 +- .../xquery/modules/image/CropFunction.java | 35 +-- .../modules/image/GetHeightFunction.java | 20 +- .../modules/image/GetThumbnailsFunction.java | 76 +++-- .../modules/image/GetWidthFunction.java | 20 +- .../xquery/modules/image/ImageModule.java | 25 +- .../xquery/modules/image/ScaleFunction.java | 19 +- .../modules/jndi/CloseContextFunction.java | 12 +- .../xquery/modules/jndi/CreateFunction.java | 24 +- .../xquery/modules/jndi/DeleteFunction.java | 22 +- .../modules/jndi/GetDirContextFunction.java | 25 +- .../exist/xquery/modules/jndi/JNDIModule.java | 61 ++-- .../xquery/modules/jndi/ModifyFunction.java | 36 +-- .../xquery/modules/jndi/RenameFunction.java | 22 +- .../xquery/modules/jndi/SearchFunction.java | 34 +-- .../modules/mail/MailFolderFunctions.java | 15 +- .../exist/xquery/modules/mail/MailModule.java | 46 ++- .../modules/mail/MailSessionFunctions.java | 16 +- .../modules/mail/MailStoreFunctions.java | 14 +- .../xquery/modules/mail/MessageFunctions.java | 36 +-- .../modules/mail/MessageListFunctions.java | 55 +--- .../modules/mail/SendEmailFunction.java | 28 +- .../xquery/modules/mail/SendEmailIT.java | 6 +- .../xquery/modules/mail/WriteMessageTest.java | 6 +- .../persistentlogin/PersistentLogin.java | 19 +- .../PersistentLoginFunctions.java | 2 +- .../PersistentLoginModule.java | 12 +- .../persistentlogin/LoginModuleIT.java | 6 +- .../exist/xquery/modules/process/Execute.java | 28 +- .../xquery/modules/process/ProcessModule.java | 8 +- .../modules/scheduler/DeleteScheduledJob.java | 15 +- .../modules/scheduler/GetScheduledJobs.java | 14 +- .../modules/scheduler/PauseScheduledJob.java | 15 +- .../modules/scheduler/ResumeScheduledJob.java | 15 +- .../modules/scheduler/ScheduleFunctions.java | 41 ++- .../modules/scheduler/SchedulerModule.java | 23 +- .../modules/simpleql/ParseSimpleQL.java | 5 +- .../modules/simpleql/SimpleQLModule.java | 10 +- .../modules/oracle/ExecuteFunction.java | 46 +-- .../xquery/modules/oracle/OracleModule.java | 10 +- .../modules/sql/CloseConnectionFunction.java | 1 - .../xquery/modules/sql/ExecuteFunction.java | 58 ++-- .../modules/sql/GetConnectionFunction.java | 9 +- .../sql/GetJNDIConnectionFunction.java | 17 +- .../xquery/modules/sql/PrepareFunction.java | 16 +- .../modules/sql/PreparedStatementWithSQL.java | 8 +- .../exist/xquery/modules/sql/SQLModule.java | 24 +- .../exist/xquery/modules/sql/SQLUtils.java | 8 +- .../modules/sql/ExecuteFunctionTest.java | 13 +- .../modules/sql/H2DatabaseResource.java | 4 +- .../sql/ImplicitConnectionCloseIT.java | 6 +- .../xquery/modules/sql/JndiConnectionIT.java | 2 +- .../exist/xquery/modules/xmldiff/Compare.java | 5 +- .../xquery/modules/xmldiff/XmlDiffModule.java | 8 +- .../xslfo/ApacheFopProcessorAdapter.java | 19 +- .../modules/xslfo/ProcessorAdapter.java | 5 +- .../xquery/modules/xslfo/RenderFunction.java | 25 +- .../xslfo/RenderXXepProcessorAdapter.java | 22 +- .../xquery/modules/xslfo/XSLFOModule.java | 24 +- .../activedirectory/ActiveDirectoryRealm.java | 33 +-- .../realm/activedirectory/ContextFactory.java | 4 +- .../ActiveDirectoryRealmTest.java | 14 +- .../security/realm/iprange/IPRangeRealm.java | 8 +- .../realm/iprange/IPRangeServlet.java | 18 +- .../AbstractLDAPPrincipalRestrictionList.java | 12 +- .../ldap/AbstractLDAPSearchPrincipal.java | 20 +- .../security/realm/ldap/LDAPAccountImpl.java | 4 +- .../exist/security/realm/ldap/LDAPRealm.java | 42 ++- .../realm/ldap/LDAPSearchContext.java | 16 +- .../realm/ldap/LDAPTransformationContext.java | 12 +- .../realm/ldap/LdapContextFactory.java | 32 +- .../exist/security/realm/ldap/LdapUtils.java | 6 +- .../realm/ldap/xquery/AccountFunctions.java | 19 +- .../realm/ldap/xquery/LDAPModule.java | 8 +- .../security/realm/ldap/LDAPRealmTest.java | 13 +- .../org/exist/vector/HttpVectorProvider.java | 12 +- .../org/exist/vector/ModelPathResolver.java | 2 +- .../java/org/exist/vector/ModelRegistry.java | 18 +- .../org/exist/vector/OnnxVectorProvider.java | 3 +- .../exist/vector/VectorEmbeddingService.java | 4 +- .../xquery/modules/vector/Diagnostics.java | 14 +- .../exist/xquery/modules/vector/Embed.java | 16 +- .../xquery/modules/vector/EmbedBatch.java | 15 +- .../exist/xquery/modules/vector/Models.java | 10 +- .../xquery/modules/vector/VectorModule.java | 6 +- .../org/exist/webdav/ExistCollection.java | 7 +- .../java/org/exist/webdav/ExistDocument.java | 6 +- .../java/org/exist/webdav/ExistResource.java | 12 +- .../exist/webdav/ExistResourceFactory.java | 15 +- .../java/org/exist/webdav/MiltonDocument.java | 14 +- .../java/org/exist/webdav/MiltonResource.java | 42 ++- .../org/exist/webdav/MiltonWebDAVServlet.java | 6 +- .../test/java/com/ettrema/cache/Cache.java | 2 +- .../exist/webdav/CDataIntergationTest.java | 2 +- .../test/java/org/exist/webdav/CopyTest.java | 2 +- .../java/org/exist/webdav/DeleteTest.java | 2 +- .../java/org/exist/webdav/RenameTest.java | 2 +- .../java/org/exist/webdav/ReplaceTest.java | 2 +- .../org/exist/webdav/SerializationTest.java | 3 +- .../exist/webdav/StoreAndRetrieveTest.java | 2 +- .../java/org/exist/xqdoc/XQDocHelper.java | 2 +- .../java/org/exist/xqdoc/ant/XQDocTask.java | 48 +-- .../java/org/exist/xqdoc/xquery/Scan.java | 27 +- .../org/exist/xqdoc/xquery/XQDocModule.java | 7 +- 1797 files changed, 12200 insertions(+), 14557 deletions(-) diff --git a/exist-ant/src/main/java/org/exist/ant/AbstractXMLDBTask.java b/exist-ant/src/main/java/org/exist/ant/AbstractXMLDBTask.java index 255c02e0328..a12b1577138 100644 --- a/exist-ant/src/main/java/org/exist/ant/AbstractXMLDBTask.java +++ b/exist-ant/src/main/java/org/exist/ant/AbstractXMLDBTask.java @@ -51,12 +51,12 @@ public abstract class AbstractXMLDBTask extends Task protected String driver = "org.exist.xmldb.DatabaseImpl"; protected String user = "guest"; protected String password = "guest"; - protected String uri = null; - protected boolean ssl = false; - protected boolean createDatabase = false; - protected String configuration = null; + protected String uri; + protected boolean ssl; + protected boolean createDatabase; + protected String configuration; protected boolean failonerror = true; - protected String permissions = null; + protected String permissions; private final String UNIX_PERMS_REGEX = "([r-][w-][x-]){3}"; @@ -220,7 +220,7 @@ protected final Collection mkcol(final Collection rootCollection, final String b current = collection; } } - return( current ); + return current; } diff --git a/exist-ant/src/main/java/org/exist/ant/BackupTask.java b/exist-ant/src/main/java/org/exist/ant/BackupTask.java index f2aff34928b..a004d0a09db 100644 --- a/exist-ant/src/main/java/org/exist/ant/BackupTask.java +++ b/exist-ant/src/main/java/org/exist/ant/BackupTask.java @@ -36,8 +36,8 @@ */ public class BackupTask extends AbstractXMLDBTask { - private String dir = null; - private boolean deduplicateBlobs = false; + private String dir; + private boolean deduplicateBlobs; @Override public void execute() throws BuildException diff --git a/exist-ant/src/main/java/org/exist/ant/ChmodTask.java b/exist-ant/src/main/java/org/exist/ant/ChmodTask.java index c56bdecee14..01fc84547aa 100644 --- a/exist-ant/src/main/java/org/exist/ant/ChmodTask.java +++ b/exist-ant/src/main/java/org/exist/ant/ChmodTask.java @@ -35,8 +35,8 @@ */ public class ChmodTask extends UserTask { - private String resource = null; - private String mode = null; + private String resource; + private String mode; /* (non-Javadoc) * @see org.apache.tools.ant.Task#execute() diff --git a/exist-ant/src/main/java/org/exist/ant/ChownTask.java b/exist-ant/src/main/java/org/exist/ant/ChownTask.java index 2e49e488c4e..57be2c44ae5 100644 --- a/exist-ant/src/main/java/org/exist/ant/ChownTask.java +++ b/exist-ant/src/main/java/org/exist/ant/ChownTask.java @@ -35,9 +35,9 @@ */ public class ChownTask extends UserTask { - private String name = null; - private String group = null; - private String resource = null; + private String name; + private String group; + private String resource; /* (non-Javadoc) * @see org.apache.tools.ant.Task#execute() diff --git a/exist-ant/src/main/java/org/exist/ant/ListGroupsTask.java b/exist-ant/src/main/java/org/exist/ant/ListGroupsTask.java index 753559fe1b5..8c049f4abc7 100644 --- a/exist-ant/src/main/java/org/exist/ant/ListGroupsTask.java +++ b/exist-ant/src/main/java/org/exist/ant/ListGroupsTask.java @@ -33,7 +33,7 @@ */ public class ListGroupsTask extends UserTask { - private String outputproperty = null; + private String outputproperty; private String separator = ","; /* (non-Javadoc) diff --git a/exist-ant/src/main/java/org/exist/ant/ListUsersTask.java b/exist-ant/src/main/java/org/exist/ant/ListUsersTask.java index f64715adc35..1513753284f 100644 --- a/exist-ant/src/main/java/org/exist/ant/ListUsersTask.java +++ b/exist-ant/src/main/java/org/exist/ant/ListUsersTask.java @@ -34,7 +34,7 @@ */ public class ListUsersTask extends UserTask { - private String outputproperty = null; + private String outputproperty; private String separator = ","; /* (non-Javadoc) diff --git a/exist-ant/src/main/java/org/exist/ant/LockResourceTask.java b/exist-ant/src/main/java/org/exist/ant/LockResourceTask.java index 13bb272031f..0e211d2ac5f 100644 --- a/exist-ant/src/main/java/org/exist/ant/LockResourceTask.java +++ b/exist-ant/src/main/java/org/exist/ant/LockResourceTask.java @@ -35,8 +35,8 @@ */ public class LockResourceTask extends UserTask { - private String name = null; - private String resource = null; + private String name; + private String resource; /* (non-Javadoc) * @see org.apache.tools.ant.Task#execute() diff --git a/exist-ant/src/main/java/org/exist/ant/RemoveGroupTask.java b/exist-ant/src/main/java/org/exist/ant/RemoveGroupTask.java index 349ee703a08..a3075a479d1 100644 --- a/exist-ant/src/main/java/org/exist/ant/RemoveGroupTask.java +++ b/exist-ant/src/main/java/org/exist/ant/RemoveGroupTask.java @@ -32,7 +32,7 @@ */ public class RemoveGroupTask extends UserTask { - private String name = null; + private String name; /* (non-Javadoc) * @see org.apache.tools.ant.Task#execute() diff --git a/exist-ant/src/main/java/org/exist/ant/RemoveUserTask.java b/exist-ant/src/main/java/org/exist/ant/RemoveUserTask.java index 4367d0cf9ad..531f6dc8fdb 100644 --- a/exist-ant/src/main/java/org/exist/ant/RemoveUserTask.java +++ b/exist-ant/src/main/java/org/exist/ant/RemoveUserTask.java @@ -34,7 +34,7 @@ */ public class RemoveUserTask extends UserTask { - private String name = null; + private String name; /* (non-Javadoc) * @see org.apache.tools.ant.Task#execute() diff --git a/exist-ant/src/main/java/org/exist/ant/RestoreTask.java b/exist-ant/src/main/java/org/exist/ant/RestoreTask.java index 89750f5722b..a37ac5b830c 100644 --- a/exist-ant/src/main/java/org/exist/ant/RestoreTask.java +++ b/exist-ant/src/main/java/org/exist/ant/RestoreTask.java @@ -159,7 +159,7 @@ public void execute() throws BuildException public DirSet createDirSet() { this.dirSet = new DirSet(); - return( dirSet ); + return dirSet; } diff --git a/exist-ant/src/main/java/org/exist/ant/UserTask.java b/exist-ant/src/main/java/org/exist/ant/UserTask.java index 382cad210a4..4b5358e1815 100644 --- a/exist-ant/src/main/java/org/exist/ant/UserTask.java +++ b/exist-ant/src/main/java/org/exist/ant/UserTask.java @@ -37,8 +37,8 @@ */ public abstract class UserTask extends AbstractXMLDBTask { - protected UserManagementService service = null; - protected Collection base = null; + protected UserManagementService service; + protected Collection base; /* (non-Javadoc) * @see org.apache.tools.ant.Task#execute() diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBCopyTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBCopyTask.java index 4584c6f8a05..29dcdb3c992 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBCopyTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBCopyTask.java @@ -40,10 +40,10 @@ */ public class XMLDBCopyTask extends AbstractXMLDBTask { - private String resource = null; - private String collection = null; - private String destination = null; - private String name = null; + private String resource; + private String collection; + private String destination; + private String name; @Override public void execute() throws BuildException diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBCreateTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBCreateTask.java index 54e37401e3b..95e2b6f5937 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBCreateTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBCreateTask.java @@ -39,7 +39,7 @@ */ public class XMLDBCreateTask extends AbstractXMLDBTask { - private String collection = null; + private String collection; @Override public void execute() throws BuildException @@ -145,6 +145,6 @@ private Collection mkcol(final Collection root, final String base, /*String path current = c; } } - return( current ); + return current; } } diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBExistTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBExistTask.java index 687c379e747..c154eb15b2e 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBExistTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBExistTask.java @@ -37,7 +37,7 @@ */ public class XMLDBExistTask extends AbstractXMLDBTask implements Condition { - private String resource = null; + private String resource; @Override public boolean eval() throws BuildException @@ -77,7 +77,7 @@ public boolean eval() throws BuildException exist = false; } - return( exist ); + return exist; } diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBExtractTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBExtractTask.java index 66f93963e73..107ad26c318 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBExtractTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBExtractTask.java @@ -49,12 +49,12 @@ * @author jim.fuller at webcomposite.com to handle binary file extraction */ public class XMLDBExtractTask extends AbstractXMLDBTask { - private String resource = null; - private Path destFile = null; - private Path destDir = null; - private boolean createdirectories = false; - private boolean subcollections = false; - private boolean overwrite = false; + private String resource; + private Path destFile; + private Path destDir; + private boolean createdirectories; + private boolean subcollections; + private boolean overwrite; @Override @@ -249,7 +249,7 @@ private void writeXMLResource(final XMLResource res, final Path dest) throws IOE } } else { - final String msg = "Destination xml file " + ((dest != null) ? (dest.toAbsolutePath().toString() + " ") : "") + "exists. Use " + "overwrite property to overwrite this file."; + final String msg = "Destination xml file " + (dest != null ? (dest.toAbsolutePath().toString() + " ") : "") + "exists. Use " + "overwrite property to overwrite this file."; if (failonerror) { throw (new BuildException(msg)); @@ -300,7 +300,7 @@ private void writeBinaryResource(final Resource res, Path dest) throws XMLDBExce } } else { - final String msg = "Dest binary file " + ((dest != null) ? (dest.toAbsolutePath().toString() + " ") : "") + "exists. Use " + "overwrite property to overwrite file."; + final String msg = "Dest binary file " + (dest != null ? (dest.toAbsolutePath().toString() + " ") : "") + "exists. Use " + "overwrite property to overwrite file."; if (failonerror) { throw (new BuildException(msg)); diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBListTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBListTask.java index 76e1a5af5db..3299cead952 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBListTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBListTask.java @@ -37,8 +37,8 @@ */ public class XMLDBListTask extends AbstractXMLDBTask { - private boolean hasCollections = false; - private boolean hasResources = false; + private boolean hasCollections; + private boolean hasResources; private String separator = ","; private String outputproperty; diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBMoveTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBMoveTask.java index 8d13045bcc3..4ac085fc95a 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBMoveTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBMoveTask.java @@ -40,10 +40,10 @@ */ public class XMLDBMoveTask extends AbstractXMLDBTask { - private String resource = null; - private String collection = null; - private String destination = null; - private String name = null; + private String resource; + private String collection; + private String destination; + private String name; @Override public void execute() throws BuildException diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBRemoveTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBRemoveTask.java index 27952c972f2..e5a42e27f3e 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBRemoveTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBRemoveTask.java @@ -40,8 +40,8 @@ */ public class XMLDBRemoveTask extends AbstractXMLDBTask { - private String resource = null; - private String collection = null; + private String resource; + private String collection; @Override public void execute() throws BuildException diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBStoreTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBStoreTask.java index 14e8b0a96e2..498b00bc4d3 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBStoreTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBStoreTask.java @@ -55,17 +55,17 @@ * @author Peter Klotz */ public class XMLDBStoreTask extends AbstractXMLDBTask { - private File mimeTypesFile = null; - private File srcFile = null; - private String targetFile = null; - private ArrayList fileSetList = null; - private boolean createCollection = false; - private boolean createSubcollections = false; + private File mimeTypesFile; + private File srcFile; + private String targetFile; + private ArrayList fileSetList; + private boolean createCollection; + private boolean createSubcollections; private boolean includeEmptyDirs = true; - private String type = null; - private String defaultMimeType = null; - private String forceMimeType = null; - private MimeTable mtable = null; + private String type; + private String defaultMimeType; + private String forceMimeType; + private MimeTable mtable; @Override public void execute() throws BuildException { @@ -144,13 +144,13 @@ public void execute() throws BuildException { final MimeType mime; if ("xml".equals(type)) { - mime = (baseMimeType != null) ? new MimeType(baseMimeType, MimeType.XML) : MimeType.XML_TYPE; + mime = baseMimeType != null ? new MimeType(baseMimeType, MimeType.XML) : MimeType.XML_TYPE; } else if ("binary".equals(type)) { - mime = (baseMimeType != null) ? new MimeType(baseMimeType, MimeType.BINARY) : MimeType.BINARY_TYPE; + mime = baseMimeType != null ? new MimeType(baseMimeType, MimeType.BINARY) : MimeType.BINARY_TYPE; } else { final String msg = "Cannot guess mime-type kind for " + srcFile.getName() + ". Treating it as a binary."; log(msg, Project.MSG_ERR); - mime = (baseMimeType != null) ? new MimeType(baseMimeType, MimeType.BINARY) : MimeType.BINARY_TYPE; + mime = baseMimeType != null ? new MimeType(baseMimeType, MimeType.BINARY) : MimeType.BINARY_TYPE; } if (targetFile == null) { @@ -161,12 +161,11 @@ public void execute() throws BuildException { final Class resourceType = mime.isXMLType() ? XMLResource.class : BinaryResource.class; log("Creating resource " + targetFile + " in collection " + col.getName() + " of type " + resourceType.getName() + " with mime-type: " + mime.getName(), Project.MSG_DEBUG); try (Resource res = col.createResource(targetFile, resourceType)) { - if (srcFile.length() == 0) { - // note: solves bug id 2429889 when this task hits empty files - } else { + if (srcFile.length() != 0) { res.setContent(srcFile); ((EXistResource) res).setMimeType(mime.getName()); col.storeResource(res); + // note: solves bug id 2429889 when this task hits empty files } if (permissions != null) { @@ -283,16 +282,16 @@ public void execute() throws BuildException { if (type != null) { if ("xml".equals(type)) { - currentMime = (currentBaseMimeType != null) ? (new MimeType(currentBaseMimeType, MimeType.XML)) : MimeType.XML_TYPE; + currentMime = currentBaseMimeType != null ? (new MimeType(currentBaseMimeType, MimeType.XML)) : MimeType.XML_TYPE; } else if ("binary".equals(type)) { - currentMime = (currentBaseMimeType != null) ? (new MimeType(currentBaseMimeType, MimeType.BINARY)) : MimeType.BINARY_TYPE; + currentMime = currentBaseMimeType != null ? (new MimeType(currentBaseMimeType, MimeType.BINARY)) : MimeType.BINARY_TYPE; } } if (currentMime == null) { final String msg = "Cannot find mime-type kind for " + file.getName() + ". Treating it as a binary."; log(msg, Project.MSG_ERR); - currentMime = (currentBaseMimeType != null) ? (new MimeType(currentBaseMimeType, MimeType.BINARY)) : MimeType.BINARY_TYPE; + currentMime = currentBaseMimeType != null ? (new MimeType(currentBaseMimeType, MimeType.BINARY)) : MimeType.BINARY_TYPE; } final Class resourceType = currentMime.isXMLType() ? XMLResource.class : BinaryResource.class; diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBXPathTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBXPathTask.java index fee9bfe11f7..83dd722f5cb 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBXPathTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBXPathTask.java @@ -55,14 +55,14 @@ * @author Peter Klotz */ public class XMLDBXPathTask extends AbstractXMLDBTask { - private String resource = null; - private String namespace = null; - private String query = null; - private String text = null; + private String resource; + private String namespace; + private String query; + private String text; // count mode - private boolean count = false; - private File destDir = null; + private boolean count; + private File destDir; private String outputproperty; @Override diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBXQueryTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBXQueryTask.java index 07989ff1793..66c88d93b14 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBXQueryTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBXQueryTask.java @@ -57,13 +57,13 @@ * @author Peter Klotz */ public class XMLDBXQueryTask extends AbstractXMLDBTask { - private String text = null; - private String queryUri = null; - private String query = null; - private File queryFile = null; - private File destDir = null; + private String text; + private String queryUri; + private String query; + private File queryFile; + private File destDir; private String outputproperty; - private List variables = new ArrayList<>(); + private final List variables = new ArrayList<>(); @Override public void execute() throws BuildException { @@ -253,8 +253,8 @@ public void setOutputproperty(final String outputproperty) { * Defines a nested element to set an XQuery variable. */ public static class Variable { - private String name = null; - private String value = null; + private String name; + private String value; public Variable() { } diff --git a/exist-ant/src/main/java/org/exist/ant/XMLDBXUpdateTask.java b/exist-ant/src/main/java/org/exist/ant/XMLDBXUpdateTask.java index 116376aaf8f..339b9cb9620 100644 --- a/exist-ant/src/main/java/org/exist/ant/XMLDBXUpdateTask.java +++ b/exist-ant/src/main/java/org/exist/ant/XMLDBXUpdateTask.java @@ -37,8 +37,8 @@ */ public class XMLDBXUpdateTask extends AbstractXMLDBTask { - private String resource = null; - private String commands = null; + private String resource; + private String commands; @Override public void execute() throws BuildException diff --git a/exist-core-jcstress/src/main/java/org/exist/util/WeakLazyStripesStressTest.java b/exist-core-jcstress/src/main/java/org/exist/util/WeakLazyStripesStressTest.java index d4d356d8aed..8f3d8265d07 100644 --- a/exist-core-jcstress/src/main/java/org/exist/util/WeakLazyStripesStressTest.java +++ b/exist-core-jcstress/src/main/java/org/exist/util/WeakLazyStripesStressTest.java @@ -37,7 +37,7 @@ public class WeakLazyStripesStressTest { @Outcome(id = "true", expect = Expect.ACCEPTABLE, desc = "Same Object for Same Key") @State public static class SameObjectForSameKey { - WeakLazyStripes lockMap = new WeakLazyStripes<>((key) -> new ReentrantLock()); + WeakLazyStripes lockMap = new WeakLazyStripes<>(key -> new ReentrantLock()); Object ar1; Object ar2; Object ar3; @@ -99,7 +99,7 @@ public void arbiter(Z_Result r) { @Outcome(id = "true", expect = Expect.ACCEPTABLE, desc = "Different Object for Different Keys") @State public static class DifferentObjectForDifferentKeys { - WeakLazyStripes lockMap = new WeakLazyStripes<>((key) -> new ReentrantLock()); + WeakLazyStripes lockMap = new WeakLazyStripes<>(key -> new ReentrantLock()); Object ar1; Object ar2; Object ar3; diff --git a/exist-core-jmh/src/main/java/org/exist/storage/lock/LockTableBenchmark.java b/exist-core-jmh/src/main/java/org/exist/storage/lock/LockTableBenchmark.java index 452109bbe89..3737537423a 100644 --- a/exist-core-jmh/src/main/java/org/exist/storage/lock/LockTableBenchmark.java +++ b/exist-core-jmh/src/main/java/org/exist/storage/lock/LockTableBenchmark.java @@ -57,13 +57,13 @@ public static class LockTableState { @State(Scope.Thread) public static class EventsState { - private int btreeReads = 0; - private int collectionIntentionReads = 0; - private int collectionReads = 0; - private int documentReads = 0; + private int btreeReads; + private int collectionIntentionReads; + private int collectionReads; + private int documentReads; - private int dataSubCollectionIndex = 0; - private int documentsIndex = 0; + private int dataSubCollectionIndex; + private int documentsIndex; } @Benchmark @@ -186,7 +186,7 @@ public void testEvent(final LockTableState lockTableState, final EventsState eve } } - public static void main(final String args[]) { + public static void main(final String[] args) { // NOTE: just for running with the java debugger LockTableBenchmark lockTableBenchmark = new LockTableBenchmark(); LockTableState lockTableState = new LockTableState(); diff --git a/exist-core-jmh/src/main/java/org/exist/xquery/utils/StringJoinBenchmark.java b/exist-core-jmh/src/main/java/org/exist/xquery/utils/StringJoinBenchmark.java index d108bc045df..f2de9ab5e30 100644 --- a/exist-core-jmh/src/main/java/org/exist/xquery/utils/StringJoinBenchmark.java +++ b/exist-core-jmh/src/main/java/org/exist/xquery/utils/StringJoinBenchmark.java @@ -142,7 +142,7 @@ public String jdkApproach() { return String.join(", ", strings); } - public static void main(final String args[]) { + public static void main(final String[] args) { // NOTE: just for running with the java debugger final StringJoinBenchmark stringJoinBenchmark = new StringJoinBenchmark(); // stringJoinBenchmark.forApproach(); diff --git a/exist-core-jmh/src/main/java/org/exist/xquery/utils/URIUtilsBenchmark.java b/exist-core-jmh/src/main/java/org/exist/xquery/utils/URIUtilsBenchmark.java index ac71bd710e3..0c7791636f8 100644 --- a/exist-core-jmh/src/main/java/org/exist/xquery/utils/URIUtilsBenchmark.java +++ b/exist-core-jmh/src/main/java/org/exist/xquery/utils/URIUtilsBenchmark.java @@ -50,7 +50,7 @@ public String encodeForURI() { return URIUtils.encodeForURI(uri); } - public static void main(final String args[]) { + public static void main(final String[] args) { // NOTE: just for running with the java debugger final URIUtilsBenchmark uriUtilsBenchmark = new URIUtilsBenchmark(); // uriUtilsBenchmark.encodeForURI(); diff --git a/exist-core/src/main/java/org/exist/BTreeTest.java b/exist-core/src/main/java/org/exist/BTreeTest.java index f5d1bfa8a0f..31eb4e43fa6 100644 --- a/exist-core/src/main/java/org/exist/BTreeTest.java +++ b/exist-core/src/main/java/org/exist/BTreeTest.java @@ -34,12 +34,12 @@ public class BTreeTest { - private final static byte BTREE_TEST_FILE_ID = 0x7F; - private final static short BTREE_TEST_FILE_VERSION = Short.MIN_VALUE; + private static final byte BTREE_TEST_FILE_ID = 0x7F; + private static final short BTREE_TEST_FILE_VERSION = Short.MIN_VALUE; - private Path file; + private final Path file; - private BrokerPool pool = null; + private BrokerPool pool; public BTreeTest() { file = Path.of(System.getProperty("exist.home", ".")).resolve("test/test.dbx"); diff --git a/exist-core/src/main/java/org/exist/Database.java b/exist-core/src/main/java/org/exist/Database.java index adb8fa1855d..d6dbcd3efa8 100644 --- a/exist-core/src/main/java/org/exist/Database.java +++ b/exist-core/src/main/java/org/exist/Database.java @@ -21,11 +21,6 @@ */ package org.exist; -import java.nio.file.Path; -import java.util.Collection; -import java.util.Observer; -import java.util.Optional; - import org.exist.collections.CollectionConfigurationManager; import org.exist.collections.triggers.CollectionTrigger; import org.exist.collections.triggers.DocumentTrigger; @@ -48,6 +43,11 @@ import org.exist.util.Configuration; import org.exist.xquery.PerformanceStats; +import java.nio.file.Path; +import java.util.Collection; +import java.util.Observer; +import java.util.Optional; + /** * Database controller, all operation synchronized by this instance. (singleton) * diff --git a/exist-core/src/main/java/org/exist/Indexer.java b/exist-core/src/main/java/org/exist/Indexer.java index 16dc8e30289..dc68112965f 100644 --- a/exist-core/src/main/java/org/exist/Indexer.java +++ b/exist-core/src/main/java/org/exist/Indexer.java @@ -21,23 +21,11 @@ */ package org.exist; -import java.util.*; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.collections.CollectionConfiguration; import org.exist.dom.QName; -import org.exist.dom.persistent.AttrImpl; -import org.exist.dom.persistent.CDATASectionImpl; -import org.exist.dom.persistent.CommentImpl; -import org.exist.dom.persistent.DocumentImpl; -import org.exist.dom.persistent.DocumentTypeImpl; -import org.exist.dom.persistent.ElementImpl; -import org.exist.dom.persistent.NodeHandle; -import org.exist.dom.persistent.ProcessingInstructionImpl; -import org.exist.dom.persistent.StoredNode; -import org.exist.dom.persistent.TextImpl; -import org.exist.dom.persistent.XMLDeclarationImpl; +import org.exist.dom.persistent.*; import org.exist.indexing.StreamListener; import org.exist.indexing.StreamListener.ReindexMode; import org.exist.storage.DBBroker; @@ -55,15 +43,11 @@ import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.ErrorHandler; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; +import org.xml.sax.*; import org.xml.sax.ext.LexicalHandler; import javax.annotation.Nullable; +import java.util.*; /** * Parses a given input document via SAX, stores it to the database and handles @@ -80,7 +64,7 @@ public class Indexer implements ContentHandler, LexicalHandler, ErrorHandler { public static final String ATTR_IDREF_TYPE = "IDREF"; public static final String ATTR_IDREFS_TYPE = "IDREFS"; - private final static Logger LOG = LogManager.getLogger(Indexer.class); + private static final Logger LOG = LogManager.getLogger(Indexer.class); public static final String CONFIGURATION_ELEMENT_NAME = "indexer"; public static final String CONFIGURATION_INDEX_ELEMENT_NAME = "index"; @@ -88,7 +72,7 @@ public class Indexer implements ContentHandler, LexicalHandler, ErrorHandler { public static final String PRESERVE_WS_MIXED_CONTENT_ATTRIBUTE = "preserve-whitespace-mixed-content"; public static final String PROPERTY_INDEXER_CONFIG = "indexer.config"; - public final static String PROPERTY_SUPPRESS_WHITESPACE = "indexer.suppress-whitespace"; + public static final String PROPERTY_SUPPRESS_WHITESPACE = "indexer.suppress-whitespace"; public static final String PROPERTY_PRESERVE_WS_MIXED_CONTENT = "indexer.preserve-whitespace-mixed-content"; private final DBBroker broker; @@ -97,17 +81,17 @@ public class Indexer implements ContentHandler, LexicalHandler, ErrorHandler { private StreamListener indexListener; private XMLString charBuf = new XMLString(); - private boolean inCDATASection = false; - private int currentLine = 0; + private boolean inCDATASection; + private int currentLine; private final NodePath2 currentPath = new NodePath2(); - private DocumentImpl document = null; - private IndexSpec indexSpec = null; + private DocumentImpl document; + private IndexSpec indexSpec; - private boolean insideDTD = false; - private boolean validate = false; - private int level = 0; - private Locator locator = null; + private boolean insideDTD; + private boolean validate; + private int level; + private Locator locator; private int normalize = XMLString.SUPPRESS_BOTH; private final Map nsMappings = new HashMap<>(); private Element rootNode; @@ -115,14 +99,14 @@ public class Indexer implements ContentHandler, LexicalHandler, ErrorHandler { private final Deque stack = new ArrayDeque<>(); private final Deque nodeContentStack = new ArrayDeque<>(); - private StoredNode prevNode = null; + private StoredNode prevNode; - private String ignorePrefix = null; + private String ignorePrefix; private ProgressIndicator progress; - protected boolean preserveWSmixed = false; + protected boolean preserveWSmixed; - protected int docSize = 0; + protected int docSize; private enum ProcessTextParent { COMMENT, PI, CDATA_START, ELEMENT_START, ELEMENT_END} @@ -131,13 +115,13 @@ private enum ProcessTextParent { COMMENT, PI, CDATA_START, ELEMENT_START, ELEMEN * phase. later, when storing the nodes, we already know the child count and * don't need to update the element a second time. */ - private int childCnt[] = new int[0x1000]; + private int[] childCnt = new int[0x1000]; // the current position in childCnt - private int elementCnt = 0; + private int elementCnt; // the current nodeFactoryInstanceCnt - private int nodeFactoryInstanceCnt = 0; + private int nodeFactoryInstanceCnt; // reusable fields private final TextImpl text = new TextImpl((Expression) null); @@ -146,8 +130,8 @@ private enum ProcessTextParent { COMMENT, PI, CDATA_START, ELEMENT_START, ELEMEN // when storing the document data, validation will be switched off, so // entities will not be reported. We thus have to cache all needed entities // during the validation run. - private Map entityMap = null; - private String currentEntityName = null; + private Map entityMap; + private String currentEntityName; private final XMLString currentEntityValue = new XMLString(); /** @@ -394,7 +378,9 @@ private void processText(ElementImpl last, ProcessTextParent ptp) { text.setData(normalized); text.setOwnerDocument(document); last.appendChildInternal(prevNode, text); - if (!validate) storeText(); + if (!validate) { + storeText(); + } setPrevious(text); } charBuf.reset(); @@ -455,7 +441,7 @@ private void setChildCount(final ElementImpl last) { @Override public void endPrefixMapping(final String prefix) { - if (ignorePrefix != null && prefix.equals(ignorePrefix)) { + if (prefix.equals(ignorePrefix)) { ignorePrefix = null; } else { nsMappings.remove(prefix); @@ -488,7 +474,9 @@ public void processingInstruction(final String target, final String data) { if (stack.isEmpty()) { pi.setNodeId(broker.getBrokerPool().getNodeFactory().createInstance(nodeFactoryInstanceCnt++)); - if (!validate) broker.storeNode(transaction, pi, currentPath, indexSpec); + if (!validate) { + broker.storeNode(transaction, pi, currentPath, indexSpec); + } document.appendChild((NodeHandle)pi); } else { @@ -497,7 +485,9 @@ public void processingInstruction(final String target, final String data) { last.appendChildInternal(prevNode, pi); setPrevious(pi); - if (!validate) broker.storeNode(transaction, pi, currentPath, indexSpec); + if (!validate) { + broker.storeNode(transaction, pi, currentPath, indexSpec); + } } } @@ -569,14 +559,14 @@ public void startElement(final String namespace, final String name, final String final String attrNS = attributes.getURI(i); final String attrQName = attributes.getQName(i); if (attrQName.startsWith("xmlns") - || attrNS.equals(Namespaces.EXIST_NS)) { + || Namespaces.EXIST_NS.equals(attrNS)) { --attrLength; } } ElementImpl node; int p = qname.indexOf(':'); - final String prefix = (p != Constants.STRING_NOT_FOUND) ? qname.substring(0, p) : ""; + final String prefix = p != Constants.STRING_NOT_FOUND ? qname.substring(0, p) : ""; final QName qn = broker.getBrokerPool().getSymbols().getQName(Node.ELEMENT_NODE, namespace, name, prefix); if (!stack.isEmpty()) { @@ -587,7 +577,7 @@ public void startElement(final String namespace, final String name, final String node = usedElements.pop(); node.setNodeName(qn, broker.getBrokerPool().getSymbols()); } else { - node = new ElementImpl((last != null) ? last.getExpression() : null, qn, broker.getBrokerPool().getSymbols()); + node = new ElementImpl(last != null ? last.getExpression() : null, qn, broker.getBrokerPool().getSymbols()); } } catch (final DOMException e) { throw new SAXException(e.getMessage(), e); @@ -646,11 +636,11 @@ public void startElement(final String namespace, final String name, final String final String attrLocalName = attributes.getLocalName(i); final String attrQName = attributes.getQName(i); // skip xmlns-attributes and attributes in eXist's namespace - if (attrQName.startsWith("xmlns") || attrNS.equals(Namespaces.EXIST_NS)) { + if (attrQName.startsWith("xmlns") || Namespaces.EXIST_NS.equals(attrNS)) { --attrLength; } else { p = attrQName.indexOf(':'); - final String attrPrefix = (p != Constants.STRING_NOT_FOUND) ? attrQName.substring(0, p) : null; + final String attrPrefix = p != Constants.STRING_NOT_FOUND ? attrQName.substring(0, p) : null; final AttrImpl attr = (AttrImpl) NodePool.getInstance().borrowNode(Node.ATTRIBUTE_NODE); final QName attrQN = broker.getBrokerPool().getSymbols().getQName(Node.ATTRIBUTE_NODE, attrNS, attrLocalName, attrPrefix); try { @@ -660,11 +650,11 @@ public void startElement(final String namespace, final String name, final String } attr.setValue(attributes.getValue(i)); attr.setOwnerDocument(document); - if (attributes.getType(i).equals(ATTR_ID_TYPE)) { + if (ATTR_ID_TYPE.equals(attributes.getType(i))) { attr.setType(AttrImpl.ID); - } else if (attributes.getType(i).equals(ATTR_IDREF_TYPE)) { + } else if (ATTR_IDREF_TYPE.equals(attributes.getType(i))) { attr.setType(AttrImpl.IDREF); - } else if (attributes.getType(i).equals(ATTR_IDREFS_TYPE)) { + } else if (ATTR_IDREFS_TYPE.equals(attributes.getType(i))) { attr.setType(AttrImpl.IDREFS); } else if (attr.getQName().equals(Namespaces.XML_ID_QNAME)) { // an xml:id attribute. Normalize the attribute and set its diff --git a/exist-core/src/main/java/org/exist/SystemProperties.java b/exist-core/src/main/java/org/exist/SystemProperties.java index ba3214ab18f..1db5955cea8 100644 --- a/exist-core/src/main/java/org/exist/SystemProperties.java +++ b/exist-core/src/main/java/org/exist/SystemProperties.java @@ -21,26 +21,26 @@ */ package org.exist; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - import com.evolvedbinary.j8fu.lazy.LazyVal; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + /** * * @author aretter */ -public class SystemProperties { +public final class SystemProperties { private static final Logger LOG = LogManager.getLogger(SystemProperties.class); private static final SystemProperties instance = new SystemProperties(); private final LazyVal properties = new LazyVal<>(this::load); - public final static SystemProperties getInstance() { + public static SystemProperties getInstance() { return instance; } @@ -66,4 +66,4 @@ public String getSystemProperty(final String propertyName) { public String getSystemProperty(final String propertyName, final String defaultValue) { return properties.get().getProperty(propertyName, defaultValue); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/backup/AbstractBackupDescriptor.java b/exist-core/src/main/java/org/exist/backup/AbstractBackupDescriptor.java index 3c4d491e21e..f6474644559 100644 --- a/exist-core/src/main/java/org/exist/backup/AbstractBackupDescriptor.java +++ b/exist-core/src/main/java/org/exist/backup/AbstractBackupDescriptor.java @@ -35,7 +35,7 @@ public abstract class AbstractBackupDescriptor implements BackupDescriptor { - protected long numberOfFiles = 0; + protected long numberOfFiles; protected Date date; public Date getDate() { @@ -58,12 +58,12 @@ public Date getDate() { date = new Date(0); } } - return (date); + return date; } public boolean before(final long timestamp) { - return (timestamp > getDate().getTime()); + return timestamp > getDate().getTime(); } @Override diff --git a/exist-core/src/main/java/org/exist/backup/Backup.java b/exist-core/src/main/java/org/exist/backup/Backup.java index e760ee7e032..2d3b6433019 100644 --- a/exist-core/src/main/java/org/exist/backup/Backup.java +++ b/exist-core/src/main/java/org/exist/backup/Backup.java @@ -49,8 +49,8 @@ import java.io.*; import java.nio.file.Path; import java.time.Instant; -import java.util.List; import java.util.HashSet; +import java.util.List; import java.util.Properties; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; @@ -139,7 +139,7 @@ public static String encode(final String enco) { out.append(t); } } - return (out.toString()); + return out.toString(); } @@ -306,7 +306,7 @@ private void backup(final Set seenBlobIds, final Collection current, fin //The name should have come from an XmldbURI.toString() call attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", current.getName()); writeUnixStylePermissionAttributes(attr, currentPerms); - attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", "" + new DateTimeValue(cur.getCreationTime())); + attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", String.valueOf(new DateTimeValue(cur.getCreationTime()))); attr.addAttribute(Namespaces.EXIST_NS, "deduplicate-blobs", "deduplicate-blobs", "CDATA", Boolean.toString(deduplicateBlobs)); attr.addAttribute(Namespaces.EXIST_NS, "version", "version", "CDATA", String.valueOf(BACKUP_FORMAT_VERSION)); @@ -411,12 +411,12 @@ private void backup(final Set seenBlobIds, final Collection current, fin Instant date = ris.getCreationTime(); if (date != null) { - attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", "" + new DateTimeValue(date)); + attr.addAttribute(Namespaces.EXIST_NS, "created", "created", "CDATA", String.valueOf(new DateTimeValue(date))); } date = ris.getLastModificationTime(); if (date != null) { - attr.addAttribute(Namespaces.EXIST_NS, "modified", "modified", "CDATA", "" + new DateTimeValue(date)); + attr.addAttribute(Namespaces.EXIST_NS, "modified", "modified", "CDATA", String.valueOf(new DateTimeValue(date))); } attr.addAttribute(Namespaces.EXIST_NS, "filename", "filename", "CDATA", filename); @@ -456,7 +456,7 @@ private void backup(final Set seenBlobIds, final Collection current, fin // write sub-collections for (final String collection : collections) { - if (current.getName().equals(XmldbURI.SYSTEM_COLLECTION) && "temp".equals(collection)) { + if (XmldbURI.SYSTEM_COLLECTION.equals(current.getName()) && "temp".equals(collection)) { continue; } attr.clear(); @@ -480,7 +480,7 @@ private void backup(final Set seenBlobIds, final Collection current, fin for (final String collection : collections) { final Collection child = current.getChildCollection(collection); - if (child.getName().equals(XmldbURI.TEMP_COLLECTION)) { + if (XmldbURI.TEMP_COLLECTION.equals(child.getName())) { continue; } output.newCollection(encode(URIUtils.urlDecodeUtf8(collection))); diff --git a/exist-core/src/main/java/org/exist/backup/BackupDirectory.java b/exist-core/src/main/java/org/exist/backup/BackupDirectory.java index 051ac53b41d..25f5dd016c9 100644 --- a/exist-core/src/main/java/org/exist/backup/BackupDirectory.java +++ b/exist-core/src/main/java/org/exist/backup/BackupDirectory.java @@ -38,15 +38,15 @@ public class BackupDirectory { - public final static Logger LOG = LogManager.getLogger(BackupDirectory.class); + public static final Logger LOG = LogManager.getLogger(BackupDirectory.class); - public final static String PREFIX_FULL_BACKUP_FILE = "full"; - public final static String PREFIX_INC_BACKUP_FILE = "inc"; + public static final String PREFIX_FULL_BACKUP_FILE = "full"; + public static final String PREFIX_INC_BACKUP_FILE = "inc"; - public final static String FILE_REGEX = "(" + PREFIX_FULL_BACKUP_FILE + "|" + PREFIX_INC_BACKUP_FILE + ")(\\d{8}-\\d{4}).*"; + public static final String FILE_REGEX = "(" + PREFIX_FULL_BACKUP_FILE + "|" + PREFIX_INC_BACKUP_FILE + ")(\\d{8}-\\d{4}).*"; - public final static String DATE_FORMAT_PICTURE = "yyyyMMdd-HHmm"; + public static final String DATE_FORMAT_PICTURE = "yyyyMMdd-HHmm"; private final DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_PICTURE); @@ -136,7 +136,7 @@ public BackupDescriptor lastBackupFile() throws IOException { e.printStackTrace(); } } - return (descriptor); + return descriptor; } } diff --git a/exist-core/src/main/java/org/exist/backup/BackupFile.java b/exist-core/src/main/java/org/exist/backup/BackupFile.java index 295db2e4e00..7c0eb70a1e0 100644 --- a/exist-core/src/main/java/org/exist/backup/BackupFile.java +++ b/exist-core/src/main/java/org/exist/backup/BackupFile.java @@ -45,31 +45,31 @@ public BackupFile(final File file, final String dateTime) { } public boolean after(final BackupFile other) { - return (date.after(other.date)); + return date.after(other.date); } public boolean after(final long time) { - return (date.getTime() > time); + return date.getTime() > time; } public boolean before(final BackupFile other) { - return (date.before(other.date)); + return date.before(other.date); } public boolean before(final long time) { - return (time > date.getTime()); + return time > date.getTime(); } public File getFile() { - return (file); + return file; } public Date getDate() { - return (date); + return date; } } diff --git a/exist-core/src/main/java/org/exist/backup/ConsistencyCheck.java b/exist-core/src/main/java/org/exist/backup/ConsistencyCheck.java index 92d3db94624..5bc34bf53f7 100644 --- a/exist-core/src/main/java/org/exist/backup/ConsistencyCheck.java +++ b/exist-core/src/main/java/org/exist/backup/ConsistencyCheck.java @@ -474,24 +474,24 @@ public interface ProgressCallback { void error(final org.exist.backup.ErrorReport error); } - private static class ElementNode { + private static final class ElementNode { private final ElementImpl elem; - private int childCount = 0; - private NodeId prevSibling = null; + private int childCount; + private NodeId prevSibling; private ElementNode(final ElementImpl element) { this.elem = element; } } - private class DocumentCallback implements BTreeCallback { + private final class DocumentCallback implements BTreeCallback { @Nullable private final List errors; @Nullable private final ProgressCallback progress; private final boolean checkDocs; - private int docCount = 0; + private int docCount; private int lastPercentage = -1; private final Agent jmxAgent = AgentFactory.getInstance(); private final List docs = new ArrayList<>(100); diff --git a/exist-core/src/main/java/org/exist/backup/DescriptorResourceCounter.java b/exist-core/src/main/java/org/exist/backup/DescriptorResourceCounter.java index 56b3c1d2fdb..de9fa59f0ed 100644 --- a/exist-core/src/main/java/org/exist/backup/DescriptorResourceCounter.java +++ b/exist-core/src/main/java/org/exist/backup/DescriptorResourceCounter.java @@ -42,7 +42,7 @@ @NotThreadSafe public class DescriptorResourceCounter { - private final static SAXParserFactory saxFactory = ExistSAXParserFactory.getSAXParserFactory(); + private static final SAXParserFactory saxFactory = ExistSAXParserFactory.getSAXParserFactory(); static { saxFactory.setNamespaceAware(true); } @@ -68,7 +68,7 @@ public long count(final InputStream descriptorInputStream) throws IOException, S } private static class CounterHandler extends DefaultHandler { - long numberOfFiles = 0; + long numberOfFiles; @Override public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { diff --git a/exist-core/src/main/java/org/exist/backup/ErrorReport.java b/exist-core/src/main/java/org/exist/backup/ErrorReport.java index 4a0fbe4ccb2..295f90dea8c 100644 --- a/exist-core/src/main/java/org/exist/backup/ErrorReport.java +++ b/exist-core/src/main/java/org/exist/backup/ErrorReport.java @@ -25,25 +25,25 @@ public class ErrorReport { - public final static int INCORRECT_NODE_ID = 0; - public final static int INCORRECT_NODE_TYPE = 1; - public final static int NODE_HIERARCHY = 2; - public final static int ACCESS_FAILED = 3; - public final static int CHILD_COLLECTION = 4; - public final static int RESOURCE_ACCESS_FAILED = 5; - public final static int DOM_INDEX = 6; - public final static int CONFIGURATION_FAILD = 7; - - public final static String[] ERRCODES = { + public static final int INCORRECT_NODE_ID = 0; + public static final int INCORRECT_NODE_TYPE = 1; + public static final int NODE_HIERARCHY = 2; + public static final int ACCESS_FAILED = 3; + public static final int CHILD_COLLECTION = 4; + public static final int RESOURCE_ACCESS_FAILED = 5; + public static final int DOM_INDEX = 6; + public static final int CONFIGURATION_FAILD = 7; + + public static final String[] ERRCODES = { "ERR_NODE_ID", "ERR_NODE_TYPE", "ERR_NODE_HIERARCHY", "ERR_ACCESS", "ERR_CHILD_COLLECTION", "RESOURCE_ACCESS_FAILED", "ERR_DOM_INDEX" }; private final int code; - private String message = null; + private String message; - private Throwable exception = null; + private Throwable exception; public ErrorReport(final int code, final String message) { this.code = code; @@ -58,17 +58,17 @@ public ErrorReport(final int code, final String message, final Throwable excepti } public int getErrcode() { - return (code); + return code; } public String getErrcodeString() { - return (ERRCODES[code]); + return ERRCODES[code]; } public String getMessage() { - return (message); + return message; } @@ -78,7 +78,7 @@ public void setMessage(final String message) { public Throwable getException() { - return (exception); + return exception; } @@ -94,7 +94,7 @@ public String toString() { if (message != null) { sb.append(message); } - return (sb.toString()); + return sb.toString(); } public static class ResourceError extends ErrorReport { @@ -110,7 +110,7 @@ public ResourceError(final int code, final String message, final Throwable excep } public int getDocumentId() { - return (documentId); + return documentId; } @@ -120,7 +120,7 @@ public void setDocumentId(final int documentId) { public String toString() { - return (super.toString() + "\nDocument ID: " + documentId); + return super.toString() + "\nDocument ID: " + documentId; } } @@ -128,7 +128,7 @@ public String toString() { public static class CollectionError extends ErrorReport { private int collectionId = -1; - private XmldbURI collectionURI = null; + private XmldbURI collectionURI; public CollectionError(final int code, final String message) { super(code, message); @@ -140,7 +140,7 @@ public CollectionError(final int code, final String message, final Throwable exc } public int getCollectionId() { - return (collectionId); + return collectionId; } @@ -149,7 +149,7 @@ public void setCollectionId(final int collectionId) { } public XmldbURI getCollectionURI() { - return (collectionURI); + return collectionURI; } public void setCollectionURI(final XmldbURI collectionURI) { @@ -157,7 +157,7 @@ public void setCollectionURI(final XmldbURI collectionURI) { } public String toString() { - return (super.toString() + "\nCollection ID: " + collectionId); + return super.toString() + "\nCollection ID: " + collectionId; } } @@ -177,12 +177,12 @@ public IndexError(final int code, final String message, final Throwable exceptio } public int getDocumentId() { - return (documentId); + return documentId; } public String toString() { - return (super.toString() + "\nDocument ID: " + documentId); + return super.toString() + "\nDocument ID: " + documentId; } } } diff --git a/exist-core/src/main/java/org/exist/backup/ExportGUI.java b/exist-core/src/main/java/org/exist/backup/ExportGUI.java index 1fef9e4ef8d..a011adf7505 100644 --- a/exist-core/src/main/java/org/exist/backup/ExportGUI.java +++ b/exist-core/src/main/java/org/exist/backup/ExportGUI.java @@ -28,11 +28,7 @@ import org.exist.storage.BrokerPool; import org.exist.storage.DBBroker; import org.exist.storage.txn.Txn; -import org.exist.util.Configuration; -import org.exist.util.MimeTable; -import org.exist.util.MimeType; -import org.exist.util.OSUtil; -import org.exist.util.SystemExitCodes; +import org.exist.util.*; import org.exist.xquery.TerminatedException; import se.softhouse.jargo.Argument; import se.softhouse.jargo.ArgumentException; @@ -67,9 +63,9 @@ public class ExportGUI extends javax.swing.JFrame { /* general arguments */ private static final Argument helpArg = helpArgument("-h", "--help"); - private BrokerPool pool = null; - private int documentCount = 0; - private PrintWriter logWriter = null; + private BrokerPool pool; + private int documentCount; + private PrintWriter logWriter; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnChangeDir; @@ -416,7 +412,7 @@ private void btnConfSelectActionPerformed(final java.awt.event.ActionEvent evt) chooser.setFileFilter(new FileFilter() { public boolean accept(final File f) { if (f.isDirectory()) { - return (true); + return true; } final MimeType mime = MimeTable.getInstance().getContentTypeFor(f.getName()); @@ -428,7 +424,7 @@ public boolean accept(final File f) { public String getDescription() { - return ("Database XML configuration file"); + return "Database XML configuration file"; } }); @@ -512,7 +508,7 @@ public void error(final String message, final Throwable exception) { private List checkDB() { if (!startDB()) { - return (null); + return null; } try (final DBBroker broker = pool.get(Optional.of(pool.getSecurityManager().getSystemSubject())); @@ -583,7 +579,7 @@ public void startCollection(final String path) { progress.setValue(0); currentTask.setText(" "); } - return (null); + return null; } diff --git a/exist-core/src/main/java/org/exist/backup/ExportMain.java b/exist-core/src/main/java/org/exist/backup/ExportMain.java index 0d731359286..8401adfc5c2 100644 --- a/exist-core/src/main/java/org/exist/backup/ExportMain.java +++ b/exist-core/src/main/java/org/exist/backup/ExportMain.java @@ -113,11 +113,11 @@ protected static BrokerPool startDB(final Optional configFile) { } config.setProperty(BrokerPool.PROPERTY_EXPORT_ONLY, Boolean.TRUE); BrokerPool.configure(1, 5, config); - return (BrokerPool.getInstance()); + return BrokerPool.getInstance(); } catch (final DatabaseConfigurationException | EXistException e) { System.err.println("ERROR: Failed to open database: " + e.getMessage()); } - return (null); + return null; } @@ -224,7 +224,7 @@ private static void process(final ParsedArguments arguments) { private static class Callback implements SystemExport.StatusCallback { - private boolean verbose = false; + private boolean verbose; public Callback(final boolean verbose) { this.verbose = verbose; diff --git a/exist-core/src/main/java/org/exist/backup/FileSystemBackupDescriptor.java b/exist-core/src/main/java/org/exist/backup/FileSystemBackupDescriptor.java index cee725837a3..7f87e25ff85 100644 --- a/exist-core/src/main/java/org/exist/backup/FileSystemBackupDescriptor.java +++ b/exist-core/src/main/java/org/exist/backup/FileSystemBackupDescriptor.java @@ -46,13 +46,13 @@ public class FileSystemBackupDescriptor extends AbstractBackupDescriptor { - private final static Logger LOG = LogManager.getLogger(); + private static final Logger LOG = LogManager.getLogger(); protected Path root; protected Path descriptor; public FileSystemBackupDescriptor(final Path root, final Path descriptor) throws FileNotFoundException { - if (!FileUtils.fileName(descriptor).equals(BackupDescriptor.COLLECTION_DESCRIPTOR) || Files.isDirectory(descriptor) || !Files.isReadable(descriptor)) { + if (!BackupDescriptor.COLLECTION_DESCRIPTOR.equals(FileUtils.fileName(descriptor)) || Files.isDirectory(descriptor) || !Files.isReadable(descriptor)) { throw new FileNotFoundException(descriptor.toAbsolutePath() + " is not a valid collection descriptor"); } this.descriptor = descriptor; @@ -154,7 +154,7 @@ public String getSymbolicPath(final String describedItem, final boolean isChildD if (isChildDescriptor) { resbase = resbase.resolve(BackupDescriptor.COLLECTION_DESCRIPTOR); } - return (resbase.toAbsolutePath().toString()); + return resbase.toAbsolutePath().toString(); } @Override @@ -179,12 +179,12 @@ public Properties getProperties() throws IOException { @Override public Path getParentDir() { - return (descriptor.getParent().getParent().getParent()); + return descriptor.getParent().getParent().getParent(); } @Override public String getName() { - return (FileUtils.fileName(descriptor.getParent().getParent())); + return FileUtils.fileName(descriptor.getParent().getParent()); } @Override diff --git a/exist-core/src/main/java/org/exist/backup/FileSystemWriter.java b/exist-core/src/main/java/org/exist/backup/FileSystemWriter.java index 3561af10a39..db91284e323 100644 --- a/exist-core/src/main/java/org/exist/backup/FileSystemWriter.java +++ b/exist-core/src/main/java/org/exist/backup/FileSystemWriter.java @@ -44,7 +44,7 @@ public class FileSystemWriter implements BackupWriter { private Path currentContents; private Writer currentContentsOut; private OutputStream currentOut; - private boolean dataWritten = false; + private boolean dataWritten; public FileSystemWriter(final String path) throws IOException { this(Path.of(path)); @@ -95,7 +95,7 @@ public Writer newContents() throws IOException { currentContents = currentDir.resolve("__contents__.xml"); currentContentsOut = Files.newBufferedWriter(currentContents, StandardCharsets.UTF_8); dataWritten = true; - return (currentContentsOut); + return currentContentsOut; } @Override @@ -107,7 +107,7 @@ public void closeContents() throws IOException { public OutputStream newEntry(final String name) throws IOException { currentOut = new BufferedOutputStream(Files.newOutputStream(currentDir.resolve(name))); dataWritten = true; - return (currentOut); + return currentOut; } @Override diff --git a/exist-core/src/main/java/org/exist/backup/GuiRestoreServiceTaskListener.java b/exist-core/src/main/java/org/exist/backup/GuiRestoreServiceTaskListener.java index 66e9cbf6725..6cd25562c68 100644 --- a/exist-core/src/main/java/org/exist/backup/GuiRestoreServiceTaskListener.java +++ b/exist-core/src/main/java/org/exist/backup/GuiRestoreServiceTaskListener.java @@ -31,7 +31,7 @@ */ public class GuiRestoreServiceTaskListener extends AbstractRestoreServiceTaskListener { private final RestoreDialog dialog; - private StringBuilder allProblems = null; + private StringBuilder allProblems; public GuiRestoreServiceTaskListener() { this(null); diff --git a/exist-core/src/main/java/org/exist/backup/Main.java b/exist-core/src/main/java/org/exist/backup/Main.java index d84ec0610ac..fefd37a5a5c 100644 --- a/exist-core/src/main/java/org/exist/backup/Main.java +++ b/exist-core/src/main/java/org/exist/backup/Main.java @@ -330,7 +330,7 @@ private static void restoreWithoutGui(final String username, final String passwo } private static class AggregatingConsoleRestoreServiceTaskListener extends ConsoleRestoreServiceTaskListener { - private StringBuilder allProblems = null; + private StringBuilder allProblems; public AggregatingConsoleRestoreServiceTaskListener(final boolean quiet) { super(quiet); diff --git a/exist-core/src/main/java/org/exist/backup/RestoreDialog.java b/exist-core/src/main/java/org/exist/backup/RestoreDialog.java index de30c1c7ee8..56e95284f62 100644 --- a/exist-core/src/main/java/org/exist/backup/RestoreDialog.java +++ b/exist-core/src/main/java/org/exist/backup/RestoreDialog.java @@ -39,14 +39,14 @@ public class RestoreDialog extends JDialog { JProgressBar progress; JButton dismissButton; - private long totalRestoreUncompressedSize = 0; - private long zippedUncompressedSize = 0; + private long totalRestoreUncompressedSize; + private long zippedUncompressedSize; - private long totalTransferSize = 0; - private long transferredSize = 0; + private long totalTransferSize; + private long transferredSize; - private long totalNumberOfFiles = 0; - private long fileCounter = 0; + private long totalNumberOfFiles; + private long fileCounter; /** diff --git a/exist-core/src/main/java/org/exist/backup/SystemExport.java b/exist-core/src/main/java/org/exist/backup/SystemExport.java index 7953f4c7963..ac1c3a8626f 100644 --- a/exist-core/src/main/java/org/exist/backup/SystemExport.java +++ b/exist-core/src/main/java/org/exist/backup/SystemExport.java @@ -97,14 +97,14 @@ * #export(org.exist.collections.Collection, BackupWriter, java.util.Date, BackupDescriptor, java.util.List, org.exist.dom.persistent.MutableDocumentSet)}. */ public class SystemExport { - public final static Logger LOG = LogManager.getLogger(SystemExport.class); + public static final Logger LOG = LogManager.getLogger(SystemExport.class); private static final XmldbURI TEMP_COLLECTION = XmldbURI.createInternal(XmldbURI.TEMP_COLLECTION); private static final XmldbURI CONTENTS_URI = XmldbURI.createInternal("__contents__.xml"); private static final XmldbURI LOST_URI = XmldbURI.createInternal("__lost_and_found__"); - public final static String CONFIGURATION_ELEMENT = "backup-filter"; - public final static String CONFIG_FILTERS = "backup.serialization.filters"; + public static final String CONFIGURATION_ELEMENT = "backup-filter"; + public static final String CONFIG_FILTERS = "backup.serialization.filters"; private static final int currVersion = 1; @@ -117,9 +117,9 @@ public class SystemExport { private final DBBroker broker; private final Txn transaction; - private StatusCallback callback = null; - private boolean directAccess = false; - private ProcessMonitor.Monitor monitor = null; + private StatusCallback callback; + private boolean directAccess; + private ProcessMonitor.Monitor monitor; private ChainOfReceiversFactory chainFactory; public SystemExport(final DBBroker broker, final Txn transaction, final StatusCallback callback, final ProcessMonitor.Monitor monitor, @@ -152,7 +152,7 @@ public SystemExport(final DBBroker broker, final Txn transaction, final StatusCa } public Path export(final String targetDir, final boolean incremental, final boolean zip, final List errorList) { - return (export(targetDir, incremental, -1, zip, errorList)); + return export(targetDir, incremental, -1, zip, errorList); } @@ -177,14 +177,14 @@ public Path export(final String targetDir, boolean incremental, final int maxInc if (incremental) { prevBackup = directory.lastBackupFile(); - LOG.info("Creating incremental backup. Prev backup: {}", (prevBackup == null) ? "none" : prevBackup.getSymbolicPath()); + LOG.info("Creating incremental backup. Prev backup: {}", prevBackup == null ? "none" : prevBackup.getSymbolicPath()); } final Properties properties = new Properties(); int seqNr = 1; if (incremental) { - properties.setProperty(BackupDescriptor.PREVIOUS_PROP_NAME, (prevBackup == null) ? "" : prevBackup.getName()); + properties.setProperty(BackupDescriptor.PREVIOUS_PROP_NAME, prevBackup == null ? "" : prevBackup.getName()); if (prevBackup != null) { final Properties prevProp = prevBackup.getProperties(); @@ -232,7 +232,7 @@ public Path export(final String targetDir, boolean incremental, final int maxInc // output.addToRoot(RepoBackup.REPO_ARCHIVE, repoBackup); // FileUtils.forceDelete(repoBackup); - final Date date = (prevBackup == null) ? null : prevBackup.getDate(); + final Date date = prevBackup == null ? null : prevBackup.getDate(); final CollectionCallback cb = new CollectionCallback(output, date, prevBackup, errorList, true); broker.getCollectionsFailsafe(transaction, cb); @@ -264,47 +264,47 @@ private void reportError(final String message, final Throwable e) { private static boolean isDamaged(final DocumentImpl doc, final List errorList) { if (errorList == null) { - return (false); + return false; } for (final org.exist.backup.ErrorReport report : errorList) { if ((report.getErrcode() == org.exist.backup.ErrorReport.RESOURCE_ACCESS_FAILED) && (((ErrorReport.ResourceError) report).getDocumentId() == doc.getDocId())) { - return (true); + return true; } } - return (false); + return false; } @SuppressWarnings("unused") private static boolean isDamaged(final Collection collection, final List errorList) { if (errorList == null) { - return (false); + return false; } for (final ErrorReport report : errorList) { if ((report.getErrcode() == org.exist.backup.ErrorReport.CHILD_COLLECTION) && (((ErrorReport.CollectionError) report).getCollectionId() == collection.getId())) { - return (true); + return true; } } - return (false); + return false; } private static boolean isDamagedChild(final XmldbURI uri, final List errorList) { if (errorList == null) { - return (false); + return false; } for (final org.exist.backup.ErrorReport report : errorList) { if ((report.getErrcode() == org.exist.backup.ErrorReport.CHILD_COLLECTION) && ((org.exist.backup.ErrorReport.CollectionError) report).getCollectionURI().equalsInternal(uri)) { - return (true); + return true; } } - return (false); + return false; } @@ -521,9 +521,9 @@ private void exportDocument(final BackupWriter output, final Date date, final Ba // store permissions final AttributesImpl attr = new AttributesImpl(); - attr.addAttribute(Namespaces.EXIST_NS, "type", "type", "CDATA", (doc.getResourceType() == DocumentImpl.BINARY_FILE) ? "BinaryResource" : "XMLResource"); + attr.addAttribute(Namespaces.EXIST_NS, "type", "type", "CDATA", doc.getResourceType() == DocumentImpl.BINARY_FILE ? "BinaryResource" : "XMLResource"); attr.addAttribute(Namespaces.EXIST_NS, "name", "name", "CDATA", doc.getFileURI().toString()); - attr.addAttribute(Namespaces.EXIST_NS, "skip", "skip", "CDATA", (needsBackup ? "no" : "yes")); + attr.addAttribute(Namespaces.EXIST_NS, "skip", "skip", "CDATA", needsBackup ? "no" : "yes"); Backup.writeUnixStylePermissionAttributes(attr, perms); // be careful when accessing document metadata: it is stored in a @@ -692,7 +692,7 @@ public int getCollectionCount() throws TerminatedException { AccountImpl.getSecurityProperties().enableCheckPasswords(true); } } - return (collectionCount); + return collectionCount; } public interface StatusCallback { @@ -705,13 +705,13 @@ public interface StatusCallback { void error(String message, Throwable exception); } - private class CollectionCallback implements BTreeCallback { + private final class CollectionCallback implements BTreeCallback { private final BackupWriter writer; private final BackupDescriptor prevBackup; private final Date date; private final List errors; private final MutableDocumentSet docs = new DefaultDocumentSet(); - private int collectionCount = 0; + private int collectionCount; private final boolean exportCollection; private int lastPercentage = -1; private final Agent jmxAgent = AgentFactory.getInstance(); @@ -735,7 +735,7 @@ public boolean indexInfo(final Value value, final long pointer) throws Terminate uri = UTF8.decode(value.data(), value.start() + CollectionStore.CollectionKey.OFFSET_VALUE, value.getLength() - CollectionStore.CollectionKey.OFFSET_VALUE).toString(); if (CollectionStore.NEXT_COLLECTION_ID_KEY.equals(uri) || CollectionStore.NEXT_DOC_ID_KEY.equals(uri) || CollectionStore.FREE_COLLECTION_ID_KEY.equals(uri) || CollectionStore.FREE_DOC_ID_KEY.equals(uri)) { - return (true); + return true; } if (callback != null) { @@ -762,23 +762,23 @@ public boolean indexInfo(final Value value, final long pointer) throws Terminate reportError("Terminating system export upon request", e); // rethrow - throw (e); + throw e; } catch (final Exception e) { reportError("Caught exception while scanning collections: " + uri, e); } - return (true); + return true; } public DocumentSet getDocs() { - return (docs); + return docs; } } - private class DocumentCallback implements BTreeCallback { + private final class DocumentCallback implements BTreeCallback { private final DocumentSet exportedDocs; - private Set writtenDocs = null; + private Set writtenDocs; private final SAXSerializer serializer; private final BackupWriter output; private final Date date; @@ -830,12 +830,12 @@ public boolean indexInfo(final Value key, final long pointer) throws TerminatedE reportError("Caught an exception while scanning documents: " + e.getMessage(), e); } } - return (true); + return true; } } - private class CheckDeletedHandler extends DefaultHandler { + private final class CheckDeletedHandler extends DefaultHandler { private final Collection collection; private final SAXSerializer serializer; @@ -846,7 +846,7 @@ private CheckDeletedHandler(final Collection collection, final SAXSerializer ser @Override public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException { - if (uri.equals(Namespaces.EXIST_NS)) { + if (Namespaces.EXIST_NS.equals(uri)) { try { if ("subcollection".equals(localName)) { diff --git a/exist-core/src/main/java/org/exist/backup/SystemImport.java b/exist-core/src/main/java/org/exist/backup/SystemImport.java index 9d016748021..1b4f63bb98d 100644 --- a/exist-core/src/main/java/org/exist/backup/SystemImport.java +++ b/exist-core/src/main/java/org/exist/backup/SystemImport.java @@ -57,7 +57,7 @@ */ public class SystemImport { - public final static Logger LOG = LogManager.getLogger( SystemImport.class ); + public static final Logger LOG = LogManager.getLogger( SystemImport.class ); private final Database db; @@ -167,4 +167,4 @@ private void setAdminCredentials(final DBBroker broker, final String newCredenti subject.setPassword(newCredentials); subject.save(broker); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/backup/ZipArchiveBackupDescriptor.java b/exist-core/src/main/java/org/exist/backup/ZipArchiveBackupDescriptor.java index ca5caa23c42..641f644919b 100644 --- a/exist-core/src/main/java/org/exist/backup/ZipArchiveBackupDescriptor.java +++ b/exist-core/src/main/java/org/exist/backup/ZipArchiveBackupDescriptor.java @@ -49,7 +49,7 @@ public class ZipArchiveBackupDescriptor extends AbstractBackupDescriptor { - private final static Logger LOG = LogManager.getLogger(); + private static final Logger LOG = LogManager.getLogger(); protected ZipFile archive; protected ZipEntry descriptor; diff --git a/exist-core/src/main/java/org/exist/backup/ZipWriter.java b/exist-core/src/main/java/org/exist/backup/ZipWriter.java index 8c3f94a5a84..a48ee1cc490 100644 --- a/exist-core/src/main/java/org/exist/backup/ZipWriter.java +++ b/exist-core/src/main/java/org/exist/backup/ZipWriter.java @@ -38,7 +38,7 @@ public class ZipWriter implements BackupWriter private String currentPath; private final ZipOutputStream out; private StringWriter contents; - private boolean dataWritten = false; + private boolean dataWritten; public ZipWriter(final String zipFile, final String collection) throws IOException { @@ -55,7 +55,7 @@ public ZipWriter(final Path zipFile, final String collection) throws IOException public Writer newContents() throws IOException { contents = new StringWriter(); - return( contents ); + return contents; } @@ -77,7 +77,7 @@ public OutputStream newEntry(final String name ) throws IOException final ZipEntry entry = new ZipEntry( mkRelative( currentPath ) + '/' + name ); out.putNextEntry( entry ); dataWritten = true; - return( out ); + return out; } public OutputStream newBlobEntry(final String blobId) throws IOException @@ -137,8 +137,8 @@ public void setProperties(final Properties properties ) throws IOException private String mkRelative(final String path ) { if( (!path.isEmpty()) && ( path.charAt( 0 ) == '/' ) ) { - return( path.substring( 1 ) ); + return path.substring( 1 ); } - return( path ); + return path; } } diff --git a/exist-core/src/main/java/org/exist/backup/restore/AbstractDeferredPermission.java b/exist-core/src/main/java/org/exist/backup/restore/AbstractDeferredPermission.java index 5f326daa877..fe15090ed3f 100644 --- a/exist-core/src/main/java/org/exist/backup/restore/AbstractDeferredPermission.java +++ b/exist-core/src/main/java/org/exist/backup/restore/AbstractDeferredPermission.java @@ -36,14 +36,14 @@ */ abstract class AbstractDeferredPermission implements DeferredPermission { - final private RestoreListener listener; - final private XmldbURI target; - final private String owner; - final private String group; - final private int mode; + private final RestoreListener listener; + private final XmldbURI target; + private final String owner; + private final String group; + private final int mode; final List aces = new ArrayList<>(); - public AbstractDeferredPermission(final RestoreListener listener, final XmldbURI target, final String owner, final String group, final int mode) { + protected AbstractDeferredPermission(final RestoreListener listener, final XmldbURI target, final String owner, final String group, final int mode) { this.listener = listener; this.target = target; this.owner = owner; @@ -80,4 +80,4 @@ protected String getOwner() { public void addACE(final int index, final ACE_TARGET target, final String who, final ACE_ACCESS_TYPE access_type, final int mode) { aces.add(new ACEAider(access_type, target, who, mode)); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/backup/restore/AbstractRestoreHandler.java b/exist-core/src/main/java/org/exist/backup/restore/AbstractRestoreHandler.java index a3022b30a6f..f7250ae73ac 100644 --- a/exist-core/src/main/java/org/exist/backup/restore/AbstractRestoreHandler.java +++ b/exist-core/src/main/java/org/exist/backup/restore/AbstractRestoreHandler.java @@ -93,9 +93,9 @@ public abstract class AbstractRestoreHandler extends DefaultHandler { @Nullable private final Set pathsToIgnore; //handler state - private int version = 0; - private boolean deduplicateBlobs = false; - @Nullable private XmldbURI currentCollectionUri = null; + private int version; + private boolean deduplicateBlobs; + @Nullable private XmldbURI currentCollectionUri; private final Deque deferredPermissions = new ArrayDeque<>(); /** @@ -139,7 +139,7 @@ public void startDocument() throws SAXException { public void startElement(final String namespaceURI, final String localName, final String qName, final Attributes atts) throws SAXException { // only process entries in the eXist-db namespace - if (namespaceURI != null && !namespaceURI.equals(Namespaces.EXIST_NS)) { + if (namespaceURI != null && !Namespaces.EXIST_NS.equals(namespaceURI)) { return; } @@ -310,7 +310,7 @@ private DeferredPermission restoreResourceEntry(final Attributes attributes) thr throw new SAXException("Resource requires a name attribute"); } - final boolean xmlType = Optional.ofNullable(attributes.getValue("type")).filter(s -> "XMLResource".equals(s)).isPresent(); + final boolean xmlType = Optional.ofNullable(attributes.getValue("type")).filter("XMLResource"::equals).isPresent(); final String filename = getAttr(attributes, "filename", commonAttributes.name); @Nullable final String mimeTypeStr = attributes.getValue("mimetype"); @Nullable final String dateModifiedStr = attributes.getValue("modified"); @@ -391,9 +391,6 @@ private DeferredPermission restoreResourceEntry(final Attributes attributes) thr notifyStartDocumentRestore(docUri, attributes); transaction.commit(); - - // NOTE: early release of Collection lock inline with Asymmetrical Locking scheme - collection.close(); } } finally { /* @@ -484,9 +481,6 @@ private void restoreDeletedEntry(final Attributes atts) { transaction.commit(); - // NOTE: early release of Collection lock inline with Asymmetrical Locking scheme - collection.close(); - } catch (final PermissionDeniedException | TransactionException | TriggerException | LockException | IOException e) { listener.warn("Failed to remove deleted resource: " + name + ": " + e.getMessage()); } @@ -620,7 +614,7 @@ protected void notifyEndDocumentRestore(final XmldbURI documentUri) throws Permi // no-op by default, may be overridden by subclass } - private static class EntryCommonMetadataAttributes { + private static final class EntryCommonMetadataAttributes { final boolean skip; @Nullable final String name; final String owner; diff --git a/exist-core/src/main/java/org/exist/backup/restore/AppRestoreUtils.java b/exist-core/src/main/java/org/exist/backup/restore/AppRestoreUtils.java index 6c9220cf284..523f1c02bdb 100644 --- a/exist-core/src/main/java/org/exist/backup/restore/AppRestoreUtils.java +++ b/exist-core/src/main/java/org/exist/backup/restore/AppRestoreUtils.java @@ -51,9 +51,9 @@ */ public class AppRestoreUtils { - private final static Logger LOG = LogManager.getLogger(AppRestoreUtils.class); + private static final Logger LOG = LogManager.getLogger(AppRestoreUtils.class); - private final static String PKG_NAMESPACE = "http://expath.org/ns/pkg"; + private static final String PKG_NAMESPACE = "http://expath.org/ns/pkg"; /** * Inspects the apps contained in the backup against installed apps in the database @@ -198,7 +198,7 @@ private static String getAppRoot(final DBBroker broker) { return appRoot; } - final static class AppDetail { + static final class AppDetail { protected final String path; protected final String name; protected final Semver version; diff --git a/exist-core/src/main/java/org/exist/backup/restore/CollectionDeferredPermission.java b/exist-core/src/main/java/org/exist/backup/restore/CollectionDeferredPermission.java index 35826a1384d..823c2d8a774 100644 --- a/exist-core/src/main/java/org/exist/backup/restore/CollectionDeferredPermission.java +++ b/exist-core/src/main/java/org/exist/backup/restore/CollectionDeferredPermission.java @@ -43,7 +43,7 @@ */ class CollectionDeferredPermission extends AbstractDeferredPermission { - private final static Logger LOG = LogManager.getLogger(CollectionDeferredPermission.class); + private static final Logger LOG = LogManager.getLogger(CollectionDeferredPermission.class); public CollectionDeferredPermission(final RestoreListener listener, final XmldbURI collectionUri, final String owner, final String group, final Integer mode) { super(listener, collectionUri, owner, group, mode); diff --git a/exist-core/src/main/java/org/exist/backup/restore/ResourceDeferredPermission.java b/exist-core/src/main/java/org/exist/backup/restore/ResourceDeferredPermission.java index db9c75a9356..ef86ce5329d 100644 --- a/exist-core/src/main/java/org/exist/backup/restore/ResourceDeferredPermission.java +++ b/exist-core/src/main/java/org/exist/backup/restore/ResourceDeferredPermission.java @@ -43,7 +43,7 @@ */ class ResourceDeferredPermission extends AbstractDeferredPermission { - private final static Logger LOG = LogManager.getLogger(ResourceDeferredPermission.class); + private static final Logger LOG = LogManager.getLogger(ResourceDeferredPermission.class); public ResourceDeferredPermission(final RestoreListener listener, final XmldbURI resourceUri, final String owner, final String group, final Integer mode) { super(listener, resourceUri, owner, group, mode); diff --git a/exist-core/src/main/java/org/exist/backup/restore/listener/LogRestoreListener.java b/exist-core/src/main/java/org/exist/backup/restore/listener/LogRestoreListener.java index cb054205e8a..03d6c56755b 100644 --- a/exist-core/src/main/java/org/exist/backup/restore/listener/LogRestoreListener.java +++ b/exist-core/src/main/java/org/exist/backup/restore/listener/LogRestoreListener.java @@ -30,7 +30,7 @@ */ public class LogRestoreListener extends AbstractRestoreListener { - public final static Logger LOG = LogManager.getLogger(LogRestoreListener.class); + public static final Logger LOG = LogManager.getLogger(LogRestoreListener.class); @Override public void info(final String message) { @@ -46,4 +46,4 @@ public void warn(final String message) { public void error(final String message) { LOG.error(message); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/backup/xquery/BackupModule.java b/exist-core/src/main/java/org/exist/backup/xquery/BackupModule.java index b42c07b2633..eb945e479c8 100644 --- a/exist-core/src/main/java/org/exist/backup/xquery/BackupModule.java +++ b/exist-core/src/main/java/org/exist/backup/xquery/BackupModule.java @@ -39,8 +39,8 @@ public class BackupModule extends AbstractInternalModule public static final String NAMESPACE_URI = "http://exist-db.org/xquery/backups"; public static final String PREFIX = "backups"; - public final static String INCLUSION_DATE = "2009-02-02"; - public final static String RELEASED_IN_VERSION = "eXist-1.2.6"; + public static final String INCLUSION_DATE = "2009-02-02"; + public static final String RELEASED_IN_VERSION = "eXist-1.2.6"; public static final FunctionDef[] functions = { new FunctionDef( ListBackups.signature, ListBackups.class ), @@ -54,25 +54,25 @@ public BackupModule(final Map> parameters) public String getNamespaceURI() { - return( NAMESPACE_URI ); + return NAMESPACE_URI; } public String getDefaultPrefix() { - return( PREFIX ); + return PREFIX; } public String getDescription() { - return( "A module for access to database backups available on the server file system" ); + return "A module for access to database backups available on the server file system"; } public String getReleaseVersion() { - return( RELEASED_IN_VERSION ); + return RELEASED_IN_VERSION; } } diff --git a/exist-core/src/main/java/org/exist/backup/xquery/ListBackups.java b/exist-core/src/main/java/org/exist/backup/xquery/ListBackups.java index f44e4ca7218..407d7f91af9 100644 --- a/exist-core/src/main/java/org/exist/backup/xquery/ListBackups.java +++ b/exist-core/src/main/java/org/exist/backup/xquery/ListBackups.java @@ -45,14 +45,14 @@ public class ListBackups extends BasicFunction { - private final static String returnText = "an XML fragment listing all eXist backups found in the specified backup directory: " + " " + " " + "value" + "value" + " " + " " + "value" + "value" + " " + " " + "Where key is a property name and value is a property value for the given .zip file."; + private static final String returnText = "an XML fragment listing all eXist backups found in the specified backup directory: " + " " + " " + "value" + "value" + " " + " " + "value" + "value" + " " + " " + "Where key is a property name and value is a property value for the given .zip file."; - public final static FunctionSignature signature = new FunctionSignature( new QName( "list", BackupModule.NAMESPACE_URI, BackupModule.PREFIX ), "Returns an XML fragment listing all eXist backups found in a specified backup directory.", new SequenceType[] { + public static final FunctionSignature signature = new FunctionSignature( new QName( "list", BackupModule.NAMESPACE_URI, BackupModule.PREFIX ), "Returns an XML fragment listing all eXist backups found in a specified backup directory.", new SequenceType[] { new FunctionParameterSequenceType( "directory", Type.STRING, Cardinality.EXACTLY_ONE, "The path to the directory to show the list of backups on." ) }, new FunctionReturnSequenceType( Type.NODE, Cardinality.EXACTLY_ONE, returnText ) ); - public final static QName DIRECTORY_ELEMENT = new QName( "directory", Namespaces.EXIST_NS, "" ); - public final static QName BACKUP_ELEMENT = new QName( "backup", Namespaces.EXIST_NS, "" ); + public static final QName DIRECTORY_ELEMENT = new QName( "directory", Namespaces.EXIST_NS, "" ); + public static final QName BACKUP_ELEMENT = new QName( "backup", Namespaces.EXIST_NS, "" ); public ListBackups(final XQueryContext context ) { @@ -119,7 +119,7 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence ) thr } } builder.endElement(); - return( builder.getDocument().getNode( nodeNr ) ); + return builder.getDocument().getNode( nodeNr ); } catch (final IOException ioe) { throw new XPathException(this, ioe); } diff --git a/exist-core/src/main/java/org/exist/backup/xquery/RetrieveBackup.java b/exist-core/src/main/java/org/exist/backup/xquery/RetrieveBackup.java index 7777220d646..93b6f1d6f9b 100644 --- a/exist-core/src/main/java/org/exist/backup/xquery/RetrieveBackup.java +++ b/exist-core/src/main/java/org/exist/backup/xquery/RetrieveBackup.java @@ -42,7 +42,7 @@ public class RetrieveBackup extends BasicFunction { - public final static FunctionSignature signature = new FunctionSignature( new QName( "retrieve", BackupModule.NAMESPACE_URI, BackupModule.PREFIX ), "Retrieves a zipped backup archive, $name, and directly streams it to the HTTP response. " + "For security reasons, the function will only read .zip files in the specified directory, $directory.", new SequenceType[] { + public static final FunctionSignature signature = new FunctionSignature( new QName( "retrieve", BackupModule.NAMESPACE_URI, BackupModule.PREFIX ), "Retrieves a zipped backup archive, $name, and directly streams it to the HTTP response. " + "For security reasons, the function will only read .zip files in the specified directory, $directory.", new SequenceType[] { new FunctionParameterSequenceType( "directory", Type.STRING, Cardinality.EXACTLY_ONE, "The path to the directory where the backup file is located." ), new FunctionParameterSequenceType( "name", Type.STRING, Cardinality.EXACTLY_ONE, "The name of the file to retrieve." ) }, new SequenceType( Type.ITEM, Cardinality.EMPTY_SEQUENCE ) ); @@ -68,7 +68,7 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence ) thr final Path backupFile = dir.resolve(name); if( !Files.isReadable(backupFile)) { - return( Sequence.EMPTY_SEQUENCE ); + return Sequence.EMPTY_SEQUENCE; } if( !name.endsWith( ".zip" ) ) { @@ -111,6 +111,6 @@ public Sequence eval(final Sequence[] args, final Sequence contextSequence ) thr catch( final IOException e ) { throw( new XPathException( this, "An IO error occurred while reading the backup archive" ) ); } - return( Sequence.EMPTY_SEQUENCE ); + return Sequence.EMPTY_SEQUENCE; } } diff --git a/exist-core/src/main/java/org/exist/client/BackupContentsFilter.java b/exist-core/src/main/java/org/exist/client/BackupContentsFilter.java index 266d8332609..2075fc5b505 100644 --- a/exist-core/src/main/java/org/exist/client/BackupContentsFilter.java +++ b/exist-core/src/main/java/org/exist/client/BackupContentsFilter.java @@ -21,8 +21,8 @@ */ package org.exist.client; -import java.io.File; import javax.swing.filechooser.FileFilter; +import java.io.File; public class BackupContentsFilter extends FileFilter { @Override diff --git a/exist-core/src/main/java/org/exist/client/CheckboxTableCellEditor.java b/exist-core/src/main/java/org/exist/client/CheckboxTableCellEditor.java index 84956a6780b..e22191155f9 100644 --- a/exist-core/src/main/java/org/exist/client/CheckboxTableCellEditor.java +++ b/exist-core/src/main/java/org/exist/client/CheckboxTableCellEditor.java @@ -23,13 +23,13 @@ import com.evolvedbinary.j8fu.tuple.Tuple2; -import java.awt.Component; -import java.util.function.Function; -import javax.swing.JTable; -import javax.swing.table.TableCellEditor; import javax.swing.AbstractCellEditor; import javax.swing.JCheckBox; +import javax.swing.JTable; import javax.swing.SwingConstants; +import javax.swing.table.TableCellEditor; +import java.awt.Component; +import java.util.function.Function; import static com.evolvedbinary.j8fu.tuple.Tuple.Tuple; diff --git a/exist-core/src/main/java/org/exist/client/CheckboxTableCellRenderer.java b/exist-core/src/main/java/org/exist/client/CheckboxTableCellRenderer.java index 3bcb6748c54..e1cfa81ff7b 100644 --- a/exist-core/src/main/java/org/exist/client/CheckboxTableCellRenderer.java +++ b/exist-core/src/main/java/org/exist/client/CheckboxTableCellRenderer.java @@ -23,8 +23,6 @@ import com.evolvedbinary.j8fu.tuple.Tuple2; -import java.awt.Component; -import java.util.function.Function; import javax.swing.JCheckBox; import javax.swing.JTable; import javax.swing.SwingConstants; @@ -33,6 +31,8 @@ import javax.swing.border.EmptyBorder; import javax.swing.plaf.UIResource; import javax.swing.table.TableCellRenderer; +import java.awt.Component; +import java.util.function.Function; /** * Renders a T as a JCheckBox. diff --git a/exist-core/src/main/java/org/exist/client/ClientFrame.java b/exist-core/src/main/java/org/exist/client/ClientFrame.java index 1ea9fd688c4..7ffd49a10e8 100644 --- a/exist-core/src/main/java/org/exist/client/ClientFrame.java +++ b/exist-core/src/main/java/org/exist/client/ClientFrame.java @@ -110,9 +110,9 @@ public class ClientFrame extends JFrame implements WindowFocusListener, KeyListe private static final String NON_APPLICABLE = "N/A"; private static final String COLLECTION_MIME_TYPE = "exist/collection"; - private int commandStart = 0; + private int commandStart; - private boolean gotUp = false; + private boolean gotUp; private DefaultStyledDocument doc; private JLabel statusbar; private JTable fileman; @@ -121,9 +121,9 @@ public class ClientFrame extends JFrame implements WindowFocusListener, KeyListe private JPopupMenu shellPopup; private final ProcessRunnable processRunnable; private final Thread processThread; - private Preferences preferences; + private final Preferences preferences; - private XmldbURI path = null; + private XmldbURI path; private Properties properties; private final InteractiveClient client; @@ -493,7 +493,7 @@ private JMenuBar createMenuBar() { menubar.add(HelpMenu); item = new JMenuItem(Messages.getString("ClientFrame.90"), KeyEvent.VK_A); //$NON-NLS-1$ - item.addActionListener(e -> AboutAction()); + item.addActionListener(e -> aboutAction()); HelpMenu.add(item); return menubar; @@ -659,11 +659,11 @@ private synchronized void type(final KeyEvent e) { @Override public void actionPerformed(final ActionEvent e) { final String cmd = e.getActionCommand(); - if (cmd.equals(CUT)) { + if (CUT.equals(cmd)) { shell.cut(); - } else if (cmd.equals(COPY)) { + } else if (COPY.equals(cmd)) { shell.copy(); - } else if (cmd.equals(PASTE)) { + } else if (PASTE.equals(cmd)) { shell.paste(); } } @@ -927,7 +927,7 @@ private void reindexAction(final ActionEvent ev) { for (int i = 0; i < selRows.length; i++) { res[i] = resources.getRow(fileman.convertRowIndexToModel(selRows[i])); - if (!(res[i].isCollection())) { + if (!res[i].isCollection()) { JOptionPane.showMessageDialog(this, Messages.getString("ClientFrame.136"), Messages.getString("ClientFrame.137"), JOptionPane.ERROR_MESSAGE); //$NON-NLS-1$ //$NON-NLS-2$ return; } @@ -937,7 +937,7 @@ private void reindexAction(final ActionEvent ev) { if (JOptionPane.showConfirmDialog(this, Messages.getString("ClientFrame.138"), //$NON-NLS-1$ Messages.getString("ClientFrame.139"), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { //$NON-NLS-1$ - final ResourceDescriptor collections[] = res; + final ResourceDescriptor[] collections = res; final Runnable reindexThread = () -> { ClientFrame.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final IndexQueryService service; @@ -999,7 +999,7 @@ private void backupAction(final ActionEvent ev) { //get the collection to highlight in the backup dialog final String defaultSelectedCollection; - final ResourceDescriptor selResources[] = getSelectedResources(); + final ResourceDescriptor[] selResources = getSelectedResources(); if (selResources != null) { if (selResources.length == 1 && selResources[0].isCollection()) { //use the selected collection @@ -1111,7 +1111,7 @@ private void doRestore(final GuiRestoreServiceTaskListener listener, final Strin listener.enableDismissDialogButton(); - if (properties.getProperty(InteractiveClient.USER, SecurityManager.DBA_USER).equals(SecurityManager.DBA_USER) && dbaPassword != null) { + if (SecurityManager.DBA_USER.equals(properties.getProperty(InteractiveClient.USER, SecurityManager.DBA_USER)) && dbaPassword != null) { properties.setProperty(InteractiveClient.PASSWORD, dbaPassword); } @@ -1482,7 +1482,7 @@ private void close() { System.exit(SystemExitCodes.OK_EXIT_CODE); } - private void AboutAction() { + private void aboutAction() { JOptionPane.showMessageDialog(this, client.getNotice()); } @@ -1584,7 +1584,7 @@ static class ResourceTableModel extends AbstractTableModel { , Messages.getString("ClientFrame.211") //$NON-NLS-1$ }; - private List rows = null; + private List rows; public void setData(final List rows) { rows.sort(new ResourceComparator()); @@ -1696,7 +1696,7 @@ protected static Properties getLoginData(final Properties props) { if (!connection.getUri().isEmpty()) { properties.setProperty(InteractiveClient.URI, connection.getUri()); - properties.setProperty(InteractiveClient.SSL_ENABLE, Boolean.valueOf(connection.isSsl()).toString().toUpperCase()); + properties.setProperty(InteractiveClient.SSL_ENABLE, Boolean.toString(connection.isSsl()).toUpperCase()); properties.setProperty(InteractiveClient.LOCAL_MODE, "FALSE"); } else { properties.setProperty(InteractiveClient.CONFIGURATION, connection.getConfiguration()); diff --git a/exist-core/src/main/java/org/exist/client/CollectionXConf.java b/exist-core/src/main/java/org/exist/client/CollectionXConf.java index 0e3caa853dc..239889a5ca7 100644 --- a/exist-core/src/main/java/org/exist/client/CollectionXConf.java +++ b/exist-core/src/main/java/org/exist/client/CollectionXConf.java @@ -21,25 +21,22 @@ */ package org.exist.client; -import java.io.IOException; -import java.util.*; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; +import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream; import org.exist.collections.CollectionConfiguration; import org.exist.collections.CollectionConfigurationManager; -import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; +import org.w3c.dom.*; import org.xml.sax.SAXException; import org.xmldb.api.base.Collection; import org.xmldb.api.base.Resource; import org.xmldb.api.base.XMLDBException; import org.xmldb.api.modules.XMLResource; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import java.io.IOException; +import java.util.*; + import static org.xmldb.api.base.ResourceType.BINARY_RESOURCE; /** @@ -55,16 +52,16 @@ public class CollectionXConf public static final String TYPE_QNAME = "qname"; public static final String TYPE_PATH = "path"; - private InteractiveClient client = null; //the client - private String path = null; //path of the collection.xconf file - Collection collection = null; //the configuration collection - Resource resConfig = null; //the collection.xconf resource + private final InteractiveClient client; //the client + private final String path; //path of the collection.xconf file + Collection collection; //the configuration collection + Resource resConfig; //the collection.xconf resource private LinkedHashMap customNamespaces = null; //custom namespaces - private RangeIndex[] rangeIndexes = null; //range indexes model - private Trigger[] triggers = null; //triggers model + private RangeIndex[] rangeIndexes; //range indexes model + private Trigger[] triggers; //triggers model - private boolean hasChanged = false; //indicates if changes have been made to the current collection configuration + private boolean hasChanged; //indicates if changes have been made to the current collection configuration /** @@ -185,7 +182,7 @@ public void deleteRangeIndex(int index) else { //else remove the item at index from the array - RangeIndex newRangeIndexes[] = new RangeIndex[rangeIndexes.length - 1]; + RangeIndex[] newRangeIndexes = new RangeIndex[rangeIndexes.length - 1]; int x = 0; for(int i = 0; i < rangeIndexes.length; i++) { @@ -240,7 +237,7 @@ public void addRangeIndex(String type, String XPath, String xsType) } else { - RangeIndex newRangeIndexes[] = new RangeIndex[rangeIndexes.length + 1]; + RangeIndex[] newRangeIndexes = new RangeIndex[rangeIndexes.length + 1]; System.arraycopy(rangeIndexes, 0, newRangeIndexes, 0, rangeIndexes.length); newRangeIndexes[rangeIndexes.length] = new RangeIndex(type, XPath, xsType); rangeIndexes = newRangeIndexes; @@ -306,7 +303,7 @@ public void deleteTrigger(int index) else { //else remove the item at index from the array - Trigger newTriggers[] = new Trigger[triggers.length - 1]; + Trigger[] newTriggers = new Trigger[triggers.length - 1]; int x = 0; for(int i = 0; i < triggers.length; i++) { @@ -360,7 +357,7 @@ public void addTrigger(String triggerClass, Properties parameters) } else { - Trigger newTriggers[] = new Trigger[triggers.length + 1]; + Trigger[] newTriggers = new Trigger[triggers.length + 1]; System.arraycopy(triggers, 0, newTriggers, 0, triggers.length); newTriggers[triggers.length] = new Trigger(triggerClass, parameters); triggers = newTriggers; @@ -567,8 +564,8 @@ public boolean Save() protected class RangeIndex { private String type = TYPE_QNAME; - private String XPath = null; - private String xsType = null; + private String XPath; + private String xsType; /** * Constructor @@ -586,12 +583,12 @@ protected class RangeIndex public String getXPath() { - return(XPath); + return XPath; } public String getxsType() { - return(xsType); + return xsType; } public String getType() { @@ -635,8 +632,8 @@ protected String toXMLString() */ protected static class Trigger { - private String triggerClass = null; - private Properties parameters = null; + private String triggerClass; + private Properties parameters; /** * Constructor diff --git a/exist-core/src/main/java/org/exist/client/CommandlineOptions.java b/exist-core/src/main/java/org/exist/client/CommandlineOptions.java index 3c42d6577f2..797e188ce83 100644 --- a/exist-core/src/main/java/org/exist/client/CommandlineOptions.java +++ b/exist-core/src/main/java/org/exist/client/CommandlineOptions.java @@ -21,16 +21,16 @@ */ package org.exist.client; -import java.io.File; -import java.net.URISyntaxException; -import java.nio.file.Path; -import java.util.*; - import org.exist.util.OSUtil; import org.exist.xmldb.XmldbURI; import org.exist.xquery.util.URIUtils; import se.softhouse.jargo.*; +import java.io.File; +import java.net.URISyntaxException; +import java.nio.file.Path; +import java.util.*; + import static org.exist.util.ArgumentUtil.*; import static se.softhouse.jargo.Arguments.*; diff --git a/exist-core/src/main/java/org/exist/client/ConnectionDialog.java b/exist-core/src/main/java/org/exist/client/ConnectionDialog.java index fc1c02769b8..467459920a7 100644 --- a/exist-core/src/main/java/org/exist/client/ConnectionDialog.java +++ b/exist-core/src/main/java/org/exist/client/ConnectionDialog.java @@ -21,6 +21,7 @@ */ package org.exist.client; +import javax.swing.*; import java.awt.Graphics; import java.io.IOException; import java.nio.file.Files; @@ -30,13 +31,6 @@ import java.util.List; import java.util.prefs.BackingStoreException; import java.util.prefs.InvalidPreferencesFormatException; -import javax.swing.ComboBoxModel; -import javax.swing.DefaultComboBoxModel; -import javax.swing.DefaultListModel; -import javax.swing.JFileChooser; -import javax.swing.JOptionPane; -import javax.swing.ListModel; -import javax.swing.SwingUtilities; /** * @author Adam Retter @@ -45,8 +39,8 @@ public class ConnectionDialog extends javax.swing.JDialog implements DialogWithR private static final String PROVIDED_PASSWORD_PLACEHOLDER = "__PROVIDED__PASSWORD__"; - private ComboBoxModel connectionTypeModel = null; - private DefaultListModel favouritesModel = null; + private ComboBoxModel connectionTypeModel; + private DefaultListModel favouritesModel; private final DefaultConnectionSettings defaultConnectionSettings; private final boolean disableEmbeddedConnectionType; private Path config; @@ -461,7 +455,7 @@ private void btnConnectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FI }//GEN-LAST:event_btnConnectActionPerformed private void cmbConnectionTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbConnectionTypeActionPerformed - final boolean remote = (((ConnectionType) cmbConnectionType.getSelectedItem()) == ConnectionType.Remote); + final boolean remote = ((ConnectionType) cmbConnectionType.getSelectedItem()) == ConnectionType.Remote; toggleRemoteEmbeddedDisplayTab(remote); }//GEN-LAST:event_cmbConnectionTypeActionPerformed diff --git a/exist-core/src/main/java/org/exist/client/DocumentView.java b/exist-core/src/main/java/org/exist/client/DocumentView.java index 1867bac300d..6781cf94e93 100644 --- a/exist-core/src/main/java/org/exist/client/DocumentView.java +++ b/exist-core/src/main/java/org/exist/client/DocumentView.java @@ -21,6 +21,23 @@ */ package org.exist.client; +import org.exist.security.Account; +import org.exist.storage.ElementIndex; +import org.exist.util.ProgressIndicator; +import org.exist.xmldb.UserManagementService; +import org.exist.xmldb.XmldbURI; +import org.exist.xquery.util.URIUtils; +import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; +import org.fife.ui.rsyntaxtextarea.SyntaxConstants; +import org.fife.ui.rtextarea.RTextScrollPane; +import org.xmldb.api.base.Collection; +import org.xmldb.api.base.Resource; +import org.xmldb.api.base.XMLDBException; +import org.xmldb.api.modules.XMLResource; + +import javax.swing.*; +import javax.swing.border.BevelBorder; +import javax.xml.transform.OutputKeys; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; @@ -38,41 +55,6 @@ import java.util.Observer; import java.util.Properties; -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPopupMenu; -import javax.swing.JProgressBar; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.JToolBar; -import javax.swing.KeyStroke; -import javax.swing.border.BevelBorder; -import javax.xml.transform.OutputKeys; - -import org.exist.security.Account; -import org.exist.storage.ElementIndex; -import org.exist.util.ProgressIndicator; -import org.exist.xmldb.UserManagementService; -import org.exist.xmldb.XmldbURI; -import org.exist.xquery.util.URIUtils; -import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea; -import org.fife.ui.rsyntaxtextarea.SyntaxConstants; -import org.fife.ui.rtextarea.RTextScrollPane; -import org.xmldb.api.base.Collection; -import org.xmldb.api.base.Resource; -import org.xmldb.api.base.XMLDBException; -import org.xmldb.api.modules.XMLResource; - import static org.xmldb.api.base.ResourceType.XML_RESOURCE; class DocumentView extends JFrame { @@ -81,10 +63,10 @@ class DocumentView extends JFrame { private static final long serialVersionUID = 1L; protected InteractiveClient client; - private XmldbURI resourceName; + private final XmldbURI resourceName; protected Resource resource; protected Collection collection; - protected boolean readOnly = false; + protected boolean readOnly; protected RSyntaxTextArea text; protected RTextScrollPane textScrollPane; protected JButton saveButton; @@ -178,7 +160,6 @@ private static void showErrorMessage(String message, Throwable t) { dialog.setResizable(true); dialog.pack(); dialog.setVisible(true); - return; } public void setReadOnly() { diff --git a/exist-core/src/main/java/org/exist/client/EnterKeyAdapter.java b/exist-core/src/main/java/org/exist/client/EnterKeyAdapter.java index a40005a6bdd..c1d92255bc0 100644 --- a/exist-core/src/main/java/org/exist/client/EnterKeyAdapter.java +++ b/exist-core/src/main/java/org/exist/client/EnterKeyAdapter.java @@ -21,12 +21,12 @@ */ package org.exist.client; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; import javax.swing.AbstractButton; +import javax.swing.JComboBox; import javax.swing.JPasswordField; import javax.swing.JTextField; -import javax.swing.JComboBox; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; /** * The class EnterKeyAdapter listens for VK_ENTER key events diff --git a/exist-core/src/main/java/org/exist/client/FavouriteConnections.java b/exist-core/src/main/java/org/exist/client/FavouriteConnections.java index d780e3c060c..2503faaf202 100644 --- a/exist-core/src/main/java/org/exist/client/FavouriteConnections.java +++ b/exist-core/src/main/java/org/exist/client/FavouriteConnections.java @@ -21,6 +21,8 @@ */ package org.exist.client; +import org.exist.xmldb.XmldbURI; + import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -32,7 +34,6 @@ import java.util.prefs.BackingStoreException; import java.util.prefs.InvalidPreferencesFormatException; import java.util.prefs.Preferences; -import org.exist.xmldb.XmldbURI; public class FavouriteConnections { @@ -72,7 +73,7 @@ public static void store(final List favourites) { favouriteNode.put(FavouriteConnection.URI, favourite.getUri()); favouriteNode.put(FavouriteConnection.CONFIGURATION, favourite.getConfiguration()); - favouriteNode.put(FavouriteConnection.SSL, Boolean.valueOf(favourite.isSsl()).toString().toUpperCase()); + favouriteNode.put(FavouriteConnection.SSL, Boolean.toString(favourite.isSsl()).toUpperCase()); } } } @@ -83,7 +84,7 @@ public static List load() { final Preferences favouritesNode = prefs.node(FAVOURITES_NODE); // Get all favourites - String favouriteNodeNames[] =new String[0]; + String[] favouriteNodeNames =new String[0]; try { favouriteNodeNames = favouritesNode.childrenNames(); } catch (final BackingStoreException ex) { diff --git a/exist-core/src/main/java/org/exist/client/HighlightedTableCellRenderer.java b/exist-core/src/main/java/org/exist/client/HighlightedTableCellRenderer.java index e2075f2adc2..8be0a4c8dfe 100644 --- a/exist-core/src/main/java/org/exist/client/HighlightedTableCellRenderer.java +++ b/exist-core/src/main/java/org/exist/client/HighlightedTableCellRenderer.java @@ -21,23 +21,24 @@ */ package org.exist.client; -import java.awt.Color; -import java.awt.Component; +import org.exist.client.ClientFrame.ResourceTableModel; +import org.exist.xmldb.XmldbURI; + import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; -import org.exist.client.ClientFrame.ResourceTableModel; -import org.exist.xmldb.XmldbURI; +import java.awt.Color; +import java.awt.Component; public class HighlightedTableCellRenderer extends DefaultTableCellRenderer { - private final static Color collectionBackground = new Color(225, 235, 224); - private final static Color collectionForeground = Color.black; - private final static Color highBackground = new Color(115, 130, 189); - private final static Color highForeground = Color.white; - private final static Color altBackground = new Color(235, 235, 235); + private static final Color collectionBackground = new Color(225, 235, 224); + private static final Color collectionForeground = Color.black; + private static final Color highBackground = new Color(115, 130, 189); + private static final Color highForeground = Color.white; + private static final Color altBackground = new Color(235, 235, 235); /* * (non-Javadoc) diff --git a/exist-core/src/main/java/org/exist/client/IndexDialog.java b/exist-core/src/main/java/org/exist/client/IndexDialog.java index e0aeff35292..3cf64a8cb4d 100644 --- a/exist-core/src/main/java/org/exist/client/IndexDialog.java +++ b/exist-core/src/main/java/org/exist/client/IndexDialog.java @@ -63,14 +63,14 @@ class IndexDialog extends JFrame { "xs:string" }; - private CollectionXConf cx = null; + private CollectionXConf cx; private JComboBox cmbCollections; private JTable tblRangeIndexes; private RangeIndexTableModel rangeIndexModel; - private InteractiveClient client; + private final InteractiveClient client; public IndexDialog(String title, InteractiveClient client) diff --git a/exist-core/src/main/java/org/exist/client/InteractiveClient.java b/exist-core/src/main/java/org/exist/client/InteractiveClient.java index 6c045bca3b2..0b2989b86ef 100644 --- a/exist-core/src/main/java/org/exist/client/InteractiveClient.java +++ b/exist-core/src/main/java/org/exist/client/InteractiveClient.java @@ -21,33 +21,6 @@ */ package org.exist.client; -import java.awt.Dimension; -import java.io.*; -import java.lang.reflect.Field; -import java.net.URISyntaxException; -import java.net.URLDecoder; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.time.Instant; -import java.time.format.DateTimeFormatter; -import java.util.*; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BinaryOperator; -import java.util.function.UnaryOperator; -import java.util.regex.Pattern; -import java.util.stream.Stream; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import javax.swing.ImageIcon; -import javax.swing.UIManager; -import javax.swing.UnsupportedLookAndFeelException; -import javax.xml.XMLConstants; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.transform.OutputKeys; - import org.apache.tools.ant.DirectoryScanner; import org.exist.SystemProperties; import org.exist.dom.persistent.XMLUtil; @@ -62,14 +35,7 @@ import org.exist.util.*; import org.exist.util.serializer.SAXSerializer; import org.exist.util.serializer.SerializerPool; -import org.exist.xmldb.EXistCollectionManagementService; -import org.exist.xmldb.DatabaseInstanceManager; -import org.exist.xmldb.EXistResource; -import org.exist.xmldb.ExtendedResource; -import org.exist.xmldb.IndexQueryService; -import org.exist.xmldb.UserManagementService; -import org.exist.xmldb.EXistXPathQueryService; -import org.exist.xmldb.XmldbURI; +import org.exist.xmldb.*; import org.exist.xquery.Constants; import org.jline.reader.*; import org.jline.reader.impl.history.DefaultHistory; @@ -88,6 +54,33 @@ import org.xmldb.api.modules.XUpdateQueryService; import se.softhouse.jargo.ArgumentException; +import javax.swing.ImageIcon; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.transform.OutputKeys; +import java.awt.Dimension; +import java.io.*; +import java.lang.reflect.Field; +import java.net.URISyntaxException; +import java.net.URLDecoder; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Instant; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BinaryOperator; +import java.util.function.UnaryOperator; +import java.util.regex.Pattern; +import java.util.stream.Stream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + import static java.nio.charset.StandardCharsets.UTF_8; import static java.time.ZoneOffset.UTC; import static javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION; @@ -157,9 +150,10 @@ public class InteractiveClient { DEFAULT_PROPERTIES.setProperty(EXPAND_XINCLUDES, "true"); DEFAULT_PROPERTIES.setProperty(SSL_ENABLE, SSL_ENABLE_DEFAULT); } + protected static final int[] COL_SIZES = new int[]{10, 10, 10, -1}; - protected static String configuration = null; + protected static String configuration; protected final TreeSet completions = new TreeSet<>(); protected final LinkedList queryHistory = new LinkedList<>(); @@ -169,24 +163,24 @@ public class InteractiveClient { protected Path queryHistoryFile; protected Path historyFile; - protected LineReader console = null; + protected LineReader console; - private Database database = null; - protected Collection current = null; + private Database database; + protected Collection current; protected int nextInSet = 1; - protected String[] resources = null; - protected ResourceSet result = null; + protected String[] resources; + protected ResourceSet result; /** * number of files of a recursive store */ - protected int filesCount = 0; + protected int filesCount; /** * total length of a recursive store */ - protected long totalLength = 0; + protected long totalLength; protected ClientFrame frame; @@ -489,7 +483,7 @@ protected boolean process(final String line) { if (options.startGUI) { frame.setPath(path); } - final String args[]; + final String[] args; if (line.startsWith("find")) { args = new String[2]; args[0] = "find"; @@ -875,7 +869,7 @@ protected boolean process(final String line) { } } else if ("users".equalsIgnoreCase(args[0])) { final UserManagementService mgtService = current.getService(UserManagementService.class); - final Account users[] = mgtService.getAccounts(); + final Account[] users = mgtService.getAccounts(); messageln("User\t\tGroups"); messageln("-----------------------------------------"); for (Account user : users) { @@ -1151,7 +1145,7 @@ private Optional getTraceWriter() { } private ResourceSet find(String xpath) throws XMLDBException { - if (xpath.substring(xpath.length() - EOL.length()).equals(EOL)) { + if (EOL.equals(xpath.substring(xpath.length() - EOL.length()))) { xpath = xpath.substring(0, xpath.length() - EOL.length()); } @@ -1185,7 +1179,7 @@ private ResourceSet find(String xpath) throws XMLDBException { service.setNamespace(mapping.getKey(), mapping.getValue()); } - return (sortBy == null) ? service.query(xpath) : service.query(xpath, sortBy); + return sortBy == null ? service.query(xpath) : service.query(xpath, sortBy); } protected final Resource retrieve(final XmldbURI resource) throws XMLDBException { @@ -1635,7 +1629,7 @@ protected synchronized boolean parseZip(final Path zipPath) throws XMLDBExceptio mimeType = MimeType.BINARY_TYPE; } try (final Resource document = base.createResource(localName, mimeType.getXMLDBType())) { - message("storing Zip-entry document " + localName + " (" + (number) + message("storing Zip-entry document " + localName + " (" + number + " of " + zfile.size() + ") ..."); document.setContent(new ZipEntryInputSource(zfile, ze)); ((EXistResource) document).setMimeType(mimeType.getName()); @@ -1957,7 +1951,7 @@ private boolean processCommandLineActions() throws IOException { if (options.xpath.isPresent()) { final String xpathStr = options.xpath.get(); - if (!xpathStr.equals(CommandlineOptions.XPATH_STDIN)) { + if (!CommandlineOptions.XPATH_STDIN.equals(xpathStr)) { xpath = xpathStr; } else { // read from stdin @@ -2137,7 +2131,9 @@ public boolean run() throws Exception { } if (interactive) { - if (initializeGui()) return false; + if (initializeGui()) { + return false; + } } else { shutdown(false); } @@ -2497,7 +2493,7 @@ final void messageln(final String msg) { } } - static final void consoleOut(final String msg) { + static void consoleOut(final String msg) { System.out.println(msg); //NOSONAR this has to go to the console } @@ -2509,7 +2505,7 @@ final void errorln(final String msg) { } } - static final void consoleErr(final String msg) { + static void consoleErr(final String msg) { System.err.println(msg); //NOSONAR this has to go to the console } @@ -2570,7 +2566,7 @@ public void complete(final LineReader lineReader, final ParsedLine parsedLine, f public static class ProgressObserver implements Observer { final ProgressBar elementsProgress = new ProgressBar("storing elements"); - Observable lastObservable = null; + Observable lastObservable; final ProgressBar parseProgress = new ProgressBar("storing nodes "); @Override diff --git a/exist-core/src/main/java/org/exist/client/Messages.java b/exist-core/src/main/java/org/exist/client/Messages.java index cb344cab249..b81fa91ad33 100644 --- a/exist-core/src/main/java/org/exist/client/Messages.java +++ b/exist-core/src/main/java/org/exist/client/Messages.java @@ -24,7 +24,7 @@ import java.util.MissingResourceException; import java.util.ResourceBundle; -public class Messages { +public final class Messages { private static final String BUNDLE_NAME = "org.exist.client.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle diff --git a/exist-core/src/main/java/org/exist/client/MimeTypeFileFilter.java b/exist-core/src/main/java/org/exist/client/MimeTypeFileFilter.java index 611aa6e537b..91e84c4c9a6 100644 --- a/exist-core/src/main/java/org/exist/client/MimeTypeFileFilter.java +++ b/exist-core/src/main/java/org/exist/client/MimeTypeFileFilter.java @@ -21,13 +21,12 @@ */ package org.exist.client; +import org.exist.util.MimeTable; + +import javax.swing.filechooser.FileFilter; import java.io.File; import java.util.Iterator; - import java.util.List; -import javax.swing.filechooser.FileFilter; - -import org.exist.util.MimeTable; /** @@ -38,8 +37,8 @@ */ public class MimeTypeFileFilter extends FileFilter { - private String description = null; - private List extensions = null; + private final String description; + private final List extensions; public MimeTypeFileFilter(String mimeType) { description = MimeTable.getInstance().getContentType(mimeType).getDescription(); @@ -86,4 +85,4 @@ public String getDescription() { return description.toString(); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/client/NewResourceDialog.java b/exist-core/src/main/java/org/exist/client/NewResourceDialog.java index 373e9831be7..8c4c6c67625 100644 --- a/exist-core/src/main/java/org/exist/client/NewResourceDialog.java +++ b/exist-core/src/main/java/org/exist/client/NewResourceDialog.java @@ -21,6 +21,16 @@ */ package org.exist.client; +import org.exist.xmldb.EXistResource; +import org.exist.xquery.util.URIUtils; +import org.xmldb.api.base.Collection; +import org.xmldb.api.base.Resource; +import org.xmldb.api.base.XMLDBException; +import org.xmldb.api.modules.BinaryResource; +import org.xmldb.api.modules.XMLResource; + +import javax.swing.*; +import javax.swing.border.EtchedBorder; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; @@ -29,21 +39,6 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.border.EtchedBorder; -import org.exist.xmldb.EXistResource; -import org.exist.xquery.util.URIUtils; -import org.xmldb.api.base.Collection; -import org.xmldb.api.base.Resource; -import org.xmldb.api.base.XMLDBException; -import org.xmldb.api.modules.BinaryResource; -import org.xmldb.api.modules.XMLResource; /** * @@ -51,10 +46,10 @@ */ public class NewResourceDialog extends JFrame { - private final static String DEFAULT_FILENAME = "new-resource"; + private static final String DEFAULT_FILENAME = "new-resource"; - private final static String DEFAULT_MODULE_NS = "http://module1"; - private final static String DEFAULT_MODULE_NS_PREFIX = "mod1"; + private static final String DEFAULT_MODULE_NS = "http://module1"; + private static final String DEFAULT_MODULE_NS_PREFIX = "mod1"; private final InteractiveClient client; @@ -262,7 +257,7 @@ private void createResource(final ResourceType resourceType, final String filena final StringBuilder resourceContentBuilder = new StringBuilder(); try(final InputStream is = getClass().getResourceAsStream(resourceType.getTemplatePath()); final Reader reader = new InputStreamReader(is)) { - final char buf[] = new char[1024]; + final char[] buf = new char[1024]; int read = -1; while((read = reader.read(buf)) > -1) { resourceContentBuilder.append(buf, 0, read); @@ -301,4 +296,4 @@ private void createResource(final ResourceType resourceType, final String filena private boolean isNullOrEmpty(String str) { return str == null || str.isEmpty(); } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/client/PrettyXmldbURI.java b/exist-core/src/main/java/org/exist/client/PrettyXmldbURI.java index e7a162a0350..daee031049d 100644 --- a/exist-core/src/main/java/org/exist/client/PrettyXmldbURI.java +++ b/exist-core/src/main/java/org/exist/client/PrettyXmldbURI.java @@ -26,7 +26,7 @@ public class PrettyXmldbURI { - private XmldbURI target; + private final XmldbURI target; public PrettyXmldbURI(XmldbURI target) { this.target=target; diff --git a/exist-core/src/main/java/org/exist/client/QueryDialog.java b/exist-core/src/main/java/org/exist/client/QueryDialog.java index 188010222e0..69786adc00b 100644 --- a/exist-core/src/main/java/org/exist/client/QueryDialog.java +++ b/exist-core/src/main/java/org/exist/client/QueryDialog.java @@ -21,46 +21,6 @@ */ package org.exist.client; -import java.awt.BorderLayout; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.event.ItemEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.*; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.DefaultComboBoxModel; -import javax.swing.ImageIcon; -import javax.swing.JButton; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JFileChooser; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.JSpinner; -import javax.swing.JSplitPane; -import javax.swing.JTabbedPane; -import javax.swing.JTextField; -import javax.swing.JToolBar; -import javax.swing.SpinnerNumberModel; -import javax.swing.SwingWorker; -import javax.swing.border.BevelBorder; -import javax.swing.event.PopupMenuEvent; -import javax.swing.event.PopupMenuListener; -import javax.xml.transform.OutputKeys; - import org.exist.security.PermissionDeniedException; import org.exist.util.Holder; import org.exist.xmldb.EXistXQueryService; @@ -81,6 +41,27 @@ import org.xmldb.api.base.ResourceSet; import org.xmldb.api.base.XMLDBException; +import javax.swing.*; +import javax.swing.border.BevelBorder; +import javax.swing.event.PopupMenuEvent; +import javax.swing.event.PopupMenuListener; +import javax.xml.transform.OutputKeys; +import java.awt.BorderLayout; +import java.awt.Cursor; +import java.awt.Dimension; +import java.awt.event.ItemEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.*; +import java.net.URL; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; + import static java.nio.charset.StandardCharsets.UTF_8; import static org.xmldb.api.base.ResourceType.XML_RESOURCE; @@ -105,15 +86,15 @@ public class QueryDialog extends JFrame { private RTextScrollPane resultDisplayScrollPane; private RSyntaxTextArea exprDisplay; private RTextScrollPane exprDisplayScrollPane; - private JComboBox collections = null; + private JComboBox collections; private SpinnerNumberModel count; private DefaultComboBoxModel history = new DefaultComboBoxModel<>(); private JTextField statusMessage; private JProgressBar progress; private JButton submitButton; private JButton killButton; - private QueryRunnable queryRunnable = null; - private Resource resource = null; + private QueryRunnable queryRunnable; + private Resource resource; private QueryDialog(final InteractiveClient client, final Collection collection, final Properties properties, boolean loadedFromDb) { super(Messages.getString("QueryDialog.0")); @@ -644,12 +625,13 @@ public void run() { context.runCleanupTasks(); } context = null; - if (result != null) + if (result != null) { try { result.clear(); } catch (final XMLDBException e) { // ignore error } + } } if (client.queryHistory.isEmpty() || !client.queryHistory.getLast().equals(xpath)) { client.addToHistory(xpath); diff --git a/exist-core/src/main/java/org/exist/client/ResourceDescriptor.java b/exist-core/src/main/java/org/exist/client/ResourceDescriptor.java index 9f0b87cf98b..16c09d2ef2e 100644 --- a/exist-core/src/main/java/org/exist/client/ResourceDescriptor.java +++ b/exist-core/src/main/java/org/exist/client/ResourceDescriptor.java @@ -21,12 +21,12 @@ */ package org.exist.client; -import java.time.Instant; - import org.exist.security.ACLPermission; import org.exist.security.Permission; import org.exist.xmldb.XmldbURI; +import java.time.Instant; + /** * Description of a resource, suitable for display by the graphical * client for instance. @@ -38,7 +38,7 @@ public abstract class ResourceDescriptor { protected final Permission permissions; private final Instant instant; - public ResourceDescriptor(final XmldbURI name, final Permission permissions, final Instant instant) { + protected ResourceDescriptor(final XmldbURI name, final Permission permissions, final Instant instant) { this.name = name; this.permissions = permissions; this.instant = instant; @@ -80,7 +80,7 @@ public boolean isCollection() { @Override public String getPermissionsDescription() { - return "-" + ((permissions instanceof ACLPermission aclp && aclp.getACECount() > 0) ? permissions.toString() + '+' : permissions.toString()); + return "-" + (permissions instanceof ACLPermission aclp && aclp.getACECount() > 0 ? permissions.toString() + '+' : permissions.toString()); } } @@ -100,7 +100,7 @@ public boolean isCollection() { @Override public String getPermissionsDescription() { - return "c" + ((permissions instanceof ACLPermission aclp && aclp.getACECount() > 0) ? permissions.toString() + '+' : permissions.toString()); + return "c" + (permissions instanceof ACLPermission aclp && aclp.getACECount() > 0 ? permissions.toString() + '+' : permissions.toString()); } } diff --git a/exist-core/src/main/java/org/exist/client/TriggersDialog.java b/exist-core/src/main/java/org/exist/client/TriggersDialog.java index 398aeddae41..f97cfb87766 100644 --- a/exist-core/src/main/java/org/exist/client/TriggersDialog.java +++ b/exist-core/src/main/java/org/exist/client/TriggersDialog.java @@ -21,6 +21,15 @@ */ package org.exist.client; +import org.exist.security.PermissionDeniedException; +import org.exist.xmldb.XmldbURI; +import org.xmldb.api.base.Collection; +import org.xmldb.api.base.XMLDBException; + +import javax.swing.*; +import javax.swing.border.TitledBorder; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableCellRenderer; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; @@ -31,24 +40,6 @@ import java.io.Serial; import java.util.ArrayList; import java.util.List; -import javax.swing.Box; -import javax.swing.DefaultCellEditor; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.border.TitledBorder; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.TableCellRenderer; -import org.exist.security.PermissionDeniedException; -import org.exist.xmldb.XmldbURI; -import org.xmldb.api.base.Collection; -import org.xmldb.api.base.XMLDBException; /** * Dialog for viewing and editing Triggers in the Admin Client @@ -62,14 +53,14 @@ class TriggersDialog extends JFrame { @Serial private static final long serialVersionUID = 1L; - private CollectionXConf cx = null; + private CollectionXConf cx; private JComboBox cmbCollections; private JTable tblTriggers; private TriggersTableModel triggersModel; - private InteractiveClient client; + private final InteractiveClient client; public TriggersDialog(final String title, final InteractiveClient client) { super(title); @@ -278,7 +269,7 @@ public Component getTableCellRendererComponent(final JTable table, final Object } // Set the state - setSelected((value != null && (Boolean) value)); + setSelected(value != null && (Boolean) value); return this; } } diff --git a/exist-core/src/main/java/org/exist/client/UploadDialog.java b/exist-core/src/main/java/org/exist/client/UploadDialog.java index 6de37f8a9cb..b99f583042f 100644 --- a/exist-core/src/main/java/org/exist/client/UploadDialog.java +++ b/exist-core/src/main/java/org/exist/client/UploadDialog.java @@ -21,6 +21,10 @@ */ package org.exist.client; +import org.exist.storage.ElementIndex; +import org.exist.util.ProgressIndicator; + +import javax.swing.*; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; @@ -28,18 +32,6 @@ import java.util.Observable; import java.util.Observer; -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JProgressBar; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JTextField; - -import org.exist.storage.ElementIndex; -import org.exist.util.ProgressIndicator; - class UploadDialog extends JFrame { @Serial @@ -52,7 +44,7 @@ class UploadDialog extends JFrame { JProgressBar progress; JProgressBar byDirProgress; - boolean cancelled = false; + boolean cancelled; final JButton closeBtn; public UploadDialog() { diff --git a/exist-core/src/main/java/org/exist/client/ZipFilter.java b/exist-core/src/main/java/org/exist/client/ZipFilter.java index c2698ed6f48..06a8a070b97 100644 --- a/exist-core/src/main/java/org/exist/client/ZipFilter.java +++ b/exist-core/src/main/java/org/exist/client/ZipFilter.java @@ -21,8 +21,8 @@ */ package org.exist.client; -import java.io.File; import javax.swing.filechooser.FileFilter; +import java.io.File; public class ZipFilter extends FileFilter { @Override diff --git a/exist-core/src/main/java/org/exist/client/security/AccessControlEntryDialog.java b/exist-core/src/main/java/org/exist/client/security/AccessControlEntryDialog.java index 5bf16b25f6e..f7356b4ca88 100644 --- a/exist-core/src/main/java/org/exist/client/security/AccessControlEntryDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/AccessControlEntryDialog.java @@ -21,13 +21,10 @@ */ package org.exist.client.security; -import java.util.*; -import javax.swing.ComboBoxModel; -import javax.swing.DefaultComboBoxModel; -import javax.swing.table.DefaultTableModel; import org.exist.client.DialogCompleteWithResponse; import org.exist.client.DialogWithResponse; import org.exist.client.InteractiveClient; +import org.exist.security.ACLPermission; import org.exist.security.ACLPermission.ACE_ACCESS_TYPE; import org.exist.security.ACLPermission.ACE_TARGET; import org.exist.security.Account; @@ -36,6 +33,11 @@ import org.exist.xmldb.UserManagementService; import org.xmldb.api.base.XMLDBException; +import javax.swing.ComboBoxModel; +import javax.swing.DefaultComboBoxModel; +import javax.swing.table.DefaultTableModel; +import java.util.*; + /** * * @author Adam Retter @@ -44,10 +46,10 @@ public class AccessControlEntryDialog extends javax.swing.JFrame implements Dial private final UserManagementService userManagementService; - private DefaultTableModel permissionTableModel = null; + private DefaultTableModel permissionTableModel; private DefaultComboBoxModel usernameModel; private final Set allUsernames; - private DefaultComboBoxModel groupNameModel = null; + private DefaultComboBoxModel groupNameModel; private final Set allGroupNames; private final List> dialogCompleteWithResponseCallbacks = new ArrayList<>(); @@ -298,16 +300,12 @@ private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRS private void cmbTargetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTargetActionPerformed final ACE_TARGET aceTarget = ACE_TARGET.valueOf((String)cmbTarget.getSelectedItem()); - switch(aceTarget) { - case USER: - cmbGroupName.setEnabled(false); - cmbUsername.setEnabled(true); - break; - - case GROUP: - cmbUsername.setEnabled(false); - cmbGroupName.setEnabled(true); - break; + if (aceTarget == ACLPermission.ACE_TARGET.USER) { + cmbGroupName.setEnabled(false); + cmbUsername.setEnabled(true); + } else if (aceTarget == ACLPermission.ACE_TARGET.GROUP) { + cmbUsername.setEnabled(false); + cmbGroupName.setEnabled(true); } }//GEN-LAST:event_cmbTargetActionPerformed diff --git a/exist-core/src/main/java/org/exist/client/security/AclTableModel.java b/exist-core/src/main/java/org/exist/client/security/AclTableModel.java index dcb9a93a6d6..643fed88381 100644 --- a/exist-core/src/main/java/org/exist/client/security/AclTableModel.java +++ b/exist-core/src/main/java/org/exist/client/security/AclTableModel.java @@ -21,17 +21,18 @@ */ package org.exist.client.security; -import javax.swing.table.DefaultTableModel; import org.exist.security.ACLPermission; import org.exist.security.Permission; +import javax.swing.table.DefaultTableModel; + /** * * @author Adam Retter */ public class AclTableModel extends DefaultTableModel { - private final static String[] COLUMN_NAMES = new String [] {"Target", "Subject", "Access", "Read", "Write", "Execute"}; + private static final String[] COLUMN_NAMES = new String [] {"Target", "Subject", "Access", "Read", "Write", "Execute"}; public AclTableModel(final Permission permission) { super(); diff --git a/exist-core/src/main/java/org/exist/client/security/AutoCompletion.java b/exist-core/src/main/java/org/exist/client/security/AutoCompletion.java index fe371c6bf8d..5db96ac41f0 100644 --- a/exist-core/src/main/java/org/exist/client/security/AutoCompletion.java +++ b/exist-core/src/main/java/org/exist/client/security/AutoCompletion.java @@ -21,9 +21,9 @@ */ package org.exist.client.security; -import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; +import java.awt.event.*; /** * Provides Auto Completion for JComboBox's. @@ -40,10 +40,10 @@ public class AutoCompletion extends PlainDocument { // flag to indicate if setSelectedItem has been called // subsequent calls to remove/insertString should be ignored - private boolean selecting = false; + private boolean selecting; private final boolean hidePopupOnFocusLoss; - private boolean hitBackspace = false; + private boolean hitBackspace; private boolean hitBackspaceOnSelection; private final KeyListener editorKeyListener; @@ -76,18 +76,12 @@ public void keyPressed(final KeyEvent e) { comboBox.setPopupVisible(true); } hitBackspace = false; - switch (e.getKeyCode()) { - // determine if the pressed key is backspace (needed by the remove method) - case KeyEvent.VK_BACK_SPACE: - hitBackspace = true; - hitBackspaceOnSelection = editor.getSelectionStart() != editor.getSelectionEnd(); - break; - - // ignore delete key - case KeyEvent.VK_DELETE: - e.consume(); - comboBox.getToolkit().beep(); - break; + if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { + hitBackspace = true; + hitBackspaceOnSelection = editor.getSelectionStart() != editor.getSelectionEnd(); + } else if (e.getKeyCode() == KeyEvent.VK_DELETE) { + e.consume(); + comboBox.getToolkit().beep(); } } }; diff --git a/exist-core/src/main/java/org/exist/client/security/BasicPermissionsTableModel.java b/exist-core/src/main/java/org/exist/client/security/BasicPermissionsTableModel.java index c6895fc56e1..b0e0c355e0e 100644 --- a/exist-core/src/main/java/org/exist/client/security/BasicPermissionsTableModel.java +++ b/exist-core/src/main/java/org/exist/client/security/BasicPermissionsTableModel.java @@ -21,9 +21,10 @@ */ package org.exist.client.security; -import javax.swing.table.DefaultTableModel; import org.exist.client.LabelledBoolean; +import javax.swing.table.DefaultTableModel; + /** * @author Adam Retter */ diff --git a/exist-core/src/main/java/org/exist/client/security/EditGroupDialog.java b/exist-core/src/main/java/org/exist/client/security/EditGroupDialog.java index 707477a63ab..ee272c1e621 100644 --- a/exist-core/src/main/java/org/exist/client/security/EditGroupDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/EditGroupDialog.java @@ -21,12 +21,6 @@ */ package org.exist.client.security; -import java.io.Serial; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import javax.swing.JOptionPane; import org.exist.security.Account; import org.exist.security.EXistSchemaType; import org.exist.security.Group; @@ -34,6 +28,13 @@ import org.exist.xmldb.UserManagementService; import org.xmldb.api.base.XMLDBException; +import javax.swing.JOptionPane; +import java.io.Serial; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + /** * * @author Adam Retter @@ -156,7 +157,7 @@ protected Group getGroup() { @Override protected boolean canModifyGroupMembers() { try { - return (getUserManagementService().getAccount(getCurrentUser()).hasDbaRole() || isGroupManager(group.getManagers(), getCurrentUser())); + return getUserManagementService().getAccount(getCurrentUser()).hasDbaRole() || isGroupManager(group.getManagers(), getCurrentUser()); } catch(final XMLDBException | PermissionDeniedException xmldbe) { JOptionPane.showMessageDialog(this, "Could not establish user " + getCurrentUser() + "'s group permissions: " + xmldbe.getMessage(), "Edit Group Error", JOptionPane.ERROR_MESSAGE); return false; diff --git a/exist-core/src/main/java/org/exist/client/security/EditPropertiesDialog.java b/exist-core/src/main/java/org/exist/client/security/EditPropertiesDialog.java index 5768b37cc1f..ca76fb789cd 100644 --- a/exist-core/src/main/java/org/exist/client/security/EditPropertiesDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/EditPropertiesDialog.java @@ -21,18 +21,9 @@ */ package org.exist.client.security; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import javax.annotation.Nullable; -import javax.swing.JOptionPane; -import javax.swing.table.DefaultTableModel; - import org.exist.client.*; -import org.exist.client.tristatecheckbox.TristateCheckboxTableCellEditor; import org.exist.client.tristatecheckbox.TristateCheckBoxTableCellRenderer; +import org.exist.client.tristatecheckbox.TristateCheckboxTableCellEditor; import org.exist.client.tristatecheckbox.TristateState; import org.exist.security.ACLPermission; import org.exist.security.Permission; @@ -45,6 +36,15 @@ import org.xmldb.api.base.Resource; import org.xmldb.api.base.XMLDBException; +import javax.annotation.Nullable; +import javax.swing.JOptionPane; +import javax.swing.table.DefaultTableModel; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + import static com.evolvedbinary.j8fu.tuple.Tuple.Tuple; import static org.exist.client.ClientFrame.MULTIPLE_INDICATOR; @@ -60,7 +60,7 @@ public class EditPropertiesDialog extends javax.swing.JFrame { private final String internetMediaType; private final String created; private final String lastModified; - private String size; + private final String size; private final String messageDigestType; private final String messageDigestValue; private final String owner; @@ -69,10 +69,10 @@ public class EditPropertiesDialog extends javax.swing.JFrame { @Nullable private final SimpleACLPermissionAider acl; private final List applyTo; - private BasicPermissionsTableModel basicPermissionsTableModel = null; - private DefaultTableModel aclTableModel = null; + private BasicPermissionsTableModel basicPermissionsTableModel; + private DefaultTableModel aclTableModel; - private final static String ERROR_TITLE = "Edit Properties Error"; + private static final String ERROR_TITLE = "Edit Properties Error"; public EditPropertiesDialog(final UserManagementService userManagementService, final String currentUser, final Collection parent, final String uri, final String internetMediaType, final String created, final String lastModified, final String size, final String messageDigestType, final String messageDigestValue, final String owner, final String group, final ModeDisplay mode, @Nullable final SimpleACLPermissionAider acl, final List applyTo) { this.userManagementService = userManagementService; diff --git a/exist-core/src/main/java/org/exist/client/security/EditUserDialog.java b/exist-core/src/main/java/org/exist/client/security/EditUserDialog.java index 13f200c5463..a41712bd8fc 100644 --- a/exist-core/src/main/java/org/exist/client/security/EditUserDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/EditUserDialog.java @@ -21,9 +21,6 @@ */ package org.exist.client.security; -import java.io.Serial; -import java.util.*; -import javax.swing.JOptionPane; import org.exist.client.DialogCompleteWithResponse; import org.exist.client.DialogWithResponse; import org.exist.security.AXSchemaType; @@ -34,6 +31,10 @@ import org.exist.xmldb.UserManagementService; import org.xmldb.api.base.XMLDBException; +import javax.swing.JOptionPane; +import java.io.Serial; +import java.util.*; + /** * * @author Adam Retter @@ -43,7 +44,7 @@ public class EditUserDialog extends UserDialog implements DialogWithResponse> dialogCompleteWithResponseCallbacks = new ArrayList<>(); @@ -146,7 +147,7 @@ private void updateUser() { private boolean isPasswordChanged() { final String password = new String(txtPassword.getPassword()); - return !password.equals(HIDDEN_PASSWORD_CONST); + return !HIDDEN_PASSWORD_CONST.equals(password); } private void modifyAccountGroupMembership() throws XMLDBException { diff --git a/exist-core/src/main/java/org/exist/client/security/FindGroupForm.java b/exist-core/src/main/java/org/exist/client/security/FindGroupForm.java index 21b8949f554..d9bd4b64708 100644 --- a/exist-core/src/main/java/org/exist/client/security/FindGroupForm.java +++ b/exist-core/src/main/java/org/exist/client/security/FindGroupForm.java @@ -23,12 +23,12 @@ import org.exist.client.DialogCompleteWithResponse; import org.exist.client.DialogWithResponse; +import org.exist.xmldb.UserManagementService; +import org.xmldb.api.base.XMLDBException; -import java.util.*; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; -import org.exist.xmldb.UserManagementService; -import org.xmldb.api.base.XMLDBException; +import java.util.*; /** * diff --git a/exist-core/src/main/java/org/exist/client/security/FindUserForm.java b/exist-core/src/main/java/org/exist/client/security/FindUserForm.java index 3cdcea4d3b5..3a5bff1a580 100644 --- a/exist-core/src/main/java/org/exist/client/security/FindUserForm.java +++ b/exist-core/src/main/java/org/exist/client/security/FindUserForm.java @@ -23,15 +23,16 @@ import org.exist.client.DialogCompleteWithResponse; import org.exist.client.DialogWithResponse; +import org.exist.security.Account; +import org.exist.xmldb.UserManagementService; +import org.xmldb.api.base.XMLDBException; + +import javax.swing.ComboBoxModel; +import javax.swing.DefaultComboBoxModel; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; -import javax.swing.ComboBoxModel; -import javax.swing.DefaultComboBoxModel; -import org.exist.security.Account; -import org.exist.xmldb.UserManagementService; -import org.xmldb.api.base.XMLDBException; /** * diff --git a/exist-core/src/main/java/org/exist/client/security/GroupDialog.java b/exist-core/src/main/java/org/exist/client/security/GroupDialog.java index f621f9f8d60..30cf61d00cc 100644 --- a/exist-core/src/main/java/org/exist/client/security/GroupDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/GroupDialog.java @@ -21,11 +21,6 @@ */ package org.exist.client.security; -import java.io.Serial; -import java.util.regex.Pattern; -import javax.swing.InputVerifier; -import javax.swing.JOptionPane; -import javax.swing.table.DefaultTableModel; import org.exist.client.DialogCompleteWithResponse; import org.exist.client.HighlightedTableCellRenderer; import org.exist.security.EXistSchemaType; @@ -34,6 +29,12 @@ import org.exist.xmldb.UserManagementService; import org.xmldb.api.base.XMLDBException; +import javax.swing.InputVerifier; +import javax.swing.JOptionPane; +import javax.swing.table.DefaultTableModel; +import java.io.Serial; +import java.util.regex.Pattern; + /** * * @author Adam Retter @@ -48,7 +49,7 @@ public class GroupDialog extends javax.swing.JFrame { private final UserManagementService userManagementService; private final String currentUser; - private DefaultTableModel groupMembersTableModel = null; + private DefaultTableModel groupMembersTableModel; public GroupDialog(final UserManagementService userManagementService, final String currentUser) { this.userManagementService = userManagementService; diff --git a/exist-core/src/main/java/org/exist/client/security/MemberOfGroupsListCellRenderer.java b/exist-core/src/main/java/org/exist/client/security/MemberOfGroupsListCellRenderer.java index cf4f8230355..dea301f34d0 100644 --- a/exist-core/src/main/java/org/exist/client/security/MemberOfGroupsListCellRenderer.java +++ b/exist-core/src/main/java/org/exist/client/security/MemberOfGroupsListCellRenderer.java @@ -21,11 +21,11 @@ */ package org.exist.client.security; -import java.awt.Component; -import java.awt.Font; import javax.swing.DefaultListCellRenderer; import javax.swing.JLabel; import javax.swing.JList; +import java.awt.Component; +import java.awt.Font; /** * @@ -33,7 +33,7 @@ */ public class MemberOfGroupsListCellRenderer extends DefaultListCellRenderer { - private String cellOfInterest = null; + private String cellOfInterest; public void setCellOfInterest(final String cellOfInterest) { this.cellOfInterest = cellOfInterest; @@ -44,7 +44,7 @@ public Component getListCellRendererComponent(JList list, Object value, int inde final JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //make the cellOfInterest BOLD font - if(cellOfInterest != null && label.getText().equals(cellOfInterest)) { + if(label.getText().equals(cellOfInterest)) { label.setFont(label.getFont().deriveFont(Font.BOLD)); } diff --git a/exist-core/src/main/java/org/exist/client/security/ReadOnlyDefaultTableModel.java b/exist-core/src/main/java/org/exist/client/security/ReadOnlyDefaultTableModel.java index 01c0edbfee2..7febaf74f66 100644 --- a/exist-core/src/main/java/org/exist/client/security/ReadOnlyDefaultTableModel.java +++ b/exist-core/src/main/java/org/exist/client/security/ReadOnlyDefaultTableModel.java @@ -22,7 +22,6 @@ package org.exist.client.security; import javax.swing.table.DefaultTableModel; - import java.io.Serial; /** diff --git a/exist-core/src/main/java/org/exist/client/security/RegExpInputVerifier.java b/exist-core/src/main/java/org/exist/client/security/RegExpInputVerifier.java index 8e7b928ac7e..07653487a7a 100644 --- a/exist-core/src/main/java/org/exist/client/security/RegExpInputVerifier.java +++ b/exist-core/src/main/java/org/exist/client/security/RegExpInputVerifier.java @@ -21,11 +21,11 @@ */ package org.exist.client.security; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import javax.swing.InputVerifier; import javax.swing.JComponent; import javax.swing.JTextField; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * diff --git a/exist-core/src/main/java/org/exist/client/security/SortedListModel.java b/exist-core/src/main/java/org/exist/client/security/SortedListModel.java index 01b90990bf3..9ad261aa5c1 100644 --- a/exist-core/src/main/java/org/exist/client/security/SortedListModel.java +++ b/exist-core/src/main/java/org/exist/client/security/SortedListModel.java @@ -21,13 +21,9 @@ */ package org.exist.client.security; -import java.io.Serial; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.SortedSet; -import java.util.TreeSet; import javax.swing.AbstractListModel; +import java.io.Serial; +import java.util.*; public class SortedListModel extends AbstractListModel { @@ -56,7 +52,7 @@ public void add(final T element) { } } - public void addAll(final T elements[]) { + public void addAll(final T[] elements) { final Collection c = Arrays.asList(elements); model.addAll(c); fireContentsChanged(this, 0, getSize()); diff --git a/exist-core/src/main/java/org/exist/client/security/UmaskDocumentFilter.java b/exist-core/src/main/java/org/exist/client/security/UmaskDocumentFilter.java index 921807486a2..c79af0fcdf6 100644 --- a/exist-core/src/main/java/org/exist/client/security/UmaskDocumentFilter.java +++ b/exist-core/src/main/java/org/exist/client/security/UmaskDocumentFilter.java @@ -21,12 +21,12 @@ */ package org.exist.client.security; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.DocumentFilter; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * @@ -34,7 +34,7 @@ */ public class UmaskDocumentFilter extends DocumentFilter { - final static Pattern ptnUmask = Pattern.compile("0?[0-7]{1,3}"); + static final Pattern ptnUmask = Pattern.compile("0?[0-7]{1,3}"); final Matcher mtcUmask = ptnUmask.matcher(""); @Override diff --git a/exist-core/src/main/java/org/exist/client/security/UmaskEditor.java b/exist-core/src/main/java/org/exist/client/security/UmaskEditor.java index 62e2e5551f7..78202859a20 100644 --- a/exist-core/src/main/java/org/exist/client/security/UmaskEditor.java +++ b/exist-core/src/main/java/org/exist/client/security/UmaskEditor.java @@ -26,7 +26,6 @@ import javax.swing.JSpinner.DefaultEditor; import javax.swing.JTextField; import javax.swing.text.DefaultFormatterFactory; - import java.io.Serial; /** diff --git a/exist-core/src/main/java/org/exist/client/security/UmaskEditorFormatter.java b/exist-core/src/main/java/org/exist/client/security/UmaskEditorFormatter.java index 5fbef34ad6f..09a242f793a 100644 --- a/exist-core/src/main/java/org/exist/client/security/UmaskEditorFormatter.java +++ b/exist-core/src/main/java/org/exist/client/security/UmaskEditorFormatter.java @@ -21,10 +21,10 @@ */ package org.exist.client.security; -import java.io.Serial; -import java.text.ParseException; import javax.swing.JFormattedTextField.AbstractFormatter; import javax.swing.text.DocumentFilter; +import java.io.Serial; +import java.text.ParseException; /** * diff --git a/exist-core/src/main/java/org/exist/client/security/UmaskSpinnerModel.java b/exist-core/src/main/java/org/exist/client/security/UmaskSpinnerModel.java index 86fb9c06c5a..883a6c3d9c8 100644 --- a/exist-core/src/main/java/org/exist/client/security/UmaskSpinnerModel.java +++ b/exist-core/src/main/java/org/exist/client/security/UmaskSpinnerModel.java @@ -29,8 +29,8 @@ */ public class UmaskSpinnerModel extends AbstractSpinnerModel { - private int umask = 0765; - public final static int OCTAL_RADIX = 8; + private int umask = 501; + public static final int OCTAL_RADIX = 8; @Override public Object getValue() { @@ -54,7 +54,7 @@ public void setValue(Object value) { @Override public Object getNextValue() { final String result; - if(umask < 0777) { + if(umask < 511) { result = intToOctalUmask(nextUmask(umask)); } else { result = "0777"; @@ -74,22 +74,22 @@ public Object getPreviousValue() { } private int prevUmask(int umask) { - if(umask == 0070) { - return 0007; - } else if(umask == 0700) { - return 0077; + if(umask == 56) { + return 7; + } else if(umask == 448) { + return 63; } else { - return umask - 01; + return umask - 1; } } private int nextUmask(int umask) { - if(umask == 0007) { - return 0010; - } else if(umask == 0070) { - return 0100; + if(umask == 7) { + return 8; + } else if(umask == 56) { + return 64; } else { - return umask + 01; + return umask + 1; } } diff --git a/exist-core/src/main/java/org/exist/client/security/UserDialog.java b/exist-core/src/main/java/org/exist/client/security/UserDialog.java index 76f1a62578f..454258f621e 100644 --- a/exist-core/src/main/java/org/exist/client/security/UserDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/UserDialog.java @@ -21,11 +21,6 @@ */ package org.exist.client.security; -import java.io.Serial; -import java.util.Iterator; -import java.util.regex.Pattern; -import javax.swing.InputVerifier; -import javax.swing.JOptionPane; import org.exist.client.InteractiveClient; import org.exist.security.AXSchemaType; import org.exist.security.EXistSchemaType; @@ -36,6 +31,12 @@ import org.exist.xmldb.UserManagementService; import org.xmldb.api.base.XMLDBException; +import javax.swing.InputVerifier; +import javax.swing.JOptionPane; +import java.io.Serial; +import java.util.Iterator; +import java.util.regex.Pattern; + /** * * @author Adam Retter @@ -48,11 +49,11 @@ public class UserDialog extends javax.swing.JFrame { private final Pattern PTN_USERNAME = Pattern.compile("[a-zA-Z0-9\\-\\._@]{3,}"); private final Pattern PTN_PASSWORD = Pattern.compile(".{3,}"); private UserManagementService userManagementService; - private SortedListModel availableGroupsModel = null; - private SortedListModel memberOfGroupsModel = null; - private String primaryGroup = null; + private SortedListModel availableGroupsModel; + private SortedListModel memberOfGroupsModel; + private String primaryGroup; - private MemberOfGroupsListCellRenderer memberOfGroupsListCellRenderer = null; + private MemberOfGroupsListCellRenderer memberOfGroupsListCellRenderer; public UserDialog(final UserManagementService userManagementService) { this.userManagementService = userManagementService; @@ -512,7 +513,7 @@ private String getUmask() { protected SortedListModel getAvailableGroupsListModel() { if(availableGroupsModel == null) { try { - final String groupNames[] = getUserManagementService().getGroups(); + final String[] groupNames = getUserManagementService().getGroups(); availableGroupsModel = new SortedListModel<>(); availableGroupsModel.addAll(groupNames); } catch (final XMLDBException xmldbe) { diff --git a/exist-core/src/main/java/org/exist/client/security/UserManagerDialog.java b/exist-core/src/main/java/org/exist/client/security/UserManagerDialog.java index 9148415e6c4..30b336f2bfe 100644 --- a/exist-core/src/main/java/org/exist/client/security/UserManagerDialog.java +++ b/exist-core/src/main/java/org/exist/client/security/UserManagerDialog.java @@ -21,16 +21,8 @@ */ package org.exist.client.security; -import org.exist.client.DialogCompleteWithResponse; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.io.Serial; -import java.util.Arrays; -import java.util.Properties; -import javax.swing.JOptionPane; -import javax.swing.table.DefaultTableModel; -import javax.swing.table.TableModel; import org.exist.client.ClientFrame; +import org.exist.client.DialogCompleteWithResponse; import org.exist.client.HighlightedTableCellRenderer; import org.exist.client.InteractiveClient; import org.exist.security.AXSchemaType; @@ -42,6 +34,15 @@ import org.exist.xmldb.UserManagementService; import org.xmldb.api.base.XMLDBException; +import javax.swing.JOptionPane; +import javax.swing.table.DefaultTableModel; +import javax.swing.table.TableModel; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.Serial; +import java.util.Arrays; +import java.util.Properties; + /** * * @author Adam Retter @@ -55,8 +56,8 @@ public class UserManagerDialog extends javax.swing.JFrame { private final String currentUser; private final ClientFrame client; - private DefaultTableModel usersTableModel = null; - private DefaultTableModel groupsTableModel = null; + private DefaultTableModel usersTableModel; + private DefaultTableModel groupsTableModel; public UserManagerDialog(final UserManagementService userManagementService, final String currentUser, final ClientFrame client) { this.userManagementService = userManagementService; @@ -72,11 +73,11 @@ private TableModel getUsersTableModel() { if(usersTableModel == null) { try { - final Account accounts[] = userManagementService.getAccounts(); + final Account[] accounts = userManagementService.getAccounts(); Arrays.sort(accounts, new AccountComparator()); - final String tableData[][] = new String[accounts.length][3]; + final String[][] tableData = new String[accounts.length][3]; for(int i = 0; i < accounts.length; i++) { tableData[i][0] = accounts[i].getName(); tableData[i][1] = accounts[i].getMetadataValue(AXSchemaType.FULLNAME); @@ -100,11 +101,11 @@ private TableModel getGroupsTableModel() { if(groupsTableModel == null) { try { - final String groupNames[] = userManagementService.getGroups(); + final String[] groupNames = userManagementService.getGroups(); Arrays.sort(groupNames); - final String tableData[][] = new String[groupNames.length][2]; + final String[][] tableData = new String[groupNames.length][2]; for(int i = 0; i < groupNames.length; i++) { tableData[i][0] = groupNames[i]; tableData[i][1] = userManagementService.getGroup(groupNames[i]).getMetadataValue(EXistSchemaType.DESCRIPTION); @@ -130,7 +131,7 @@ public void refreshUsersTableModel() { } try { - final Account accounts[] = userManagementService.getAccounts(); + final Account[] accounts = userManagementService.getAccounts(); Arrays.sort(accounts, new AccountComparator()); @@ -153,7 +154,7 @@ public void refreshGroupsTableModel() { } try { - final String groupNames[] = userManagementService.getGroups(); + final String[] groupNames = userManagementService.getGroups(); Arrays.sort(groupNames); @@ -439,8 +440,8 @@ private void tblUsersMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:ev final boolean userSelected = tblUsers.getSelectedRow() > -1; final String selectedUsername = getSelectedUsername(); - boolean canModify = userSelected && !selectedUsername.equals(SecurityManager.SYSTEM); - boolean canDelete = userSelected && !(selectedUsername.equals(SecurityManager.SYSTEM) || selectedUsername.equals(SecurityManager.DBA_USER) || selectedUsername.equals(SecurityManager.GUEST_USER)); + boolean canModify = userSelected && !SecurityManager.SYSTEM.equals(selectedUsername); + boolean canDelete = userSelected && !(SecurityManager.SYSTEM.equals(selectedUsername) || SecurityManager.DBA_USER.equals(selectedUsername) || SecurityManager.GUEST_USER.equals(selectedUsername)); miEditUser.setEnabled(canModify); miRemoveUser.setEnabled(canDelete); @@ -482,7 +483,7 @@ private void tblGroupsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:e final boolean groupSelected = tblGroups.getSelectedRow() > -1; final String selectedGroup = getSelectedGroup(); - boolean canDelete = groupSelected && !(selectedGroup.equals(SecurityManager.DBA_GROUP) || selectedGroup.equals(SecurityManager.GUEST_GROUP)); + boolean canDelete = groupSelected && !(SecurityManager.DBA_GROUP.equals(selectedGroup) || SecurityManager.GUEST_GROUP.equals(selectedGroup)); miRemoveGroup.setEnabled(canDelete); diff --git a/exist-core/src/main/java/org/exist/client/tristatecheckbox/TristateCheckBox.java b/exist-core/src/main/java/org/exist/client/tristatecheckbox/TristateCheckBox.java index 7ede9cb3a9d..7c3beaf2560 100644 --- a/exist-core/src/main/java/org/exist/client/tristatecheckbox/TristateCheckBox.java +++ b/exist-core/src/main/java/org/exist/client/tristatecheckbox/TristateCheckBox.java @@ -53,6 +53,7 @@ public TristateCheckBox(final String text, final TristateState state) { switch (state) { case SELECTED: setSelected(true); + break; case INDETERMINATE: case DESELECTED: putClientProperty("SelectionState", state); @@ -74,8 +75,8 @@ public boolean isSelected() { } public TristateState getSelectionState() { - return (getClientProperty("SelectionState") != null ? (TristateState) getClientProperty("SelectionState") : - super.isSelected() ? TristateState.SELECTED : TristateState.DESELECTED); + return getClientProperty("SelectionState") != null ? (TristateState) getClientProperty("SelectionState") : + super.isSelected() ? TristateState.SELECTED : TristateState.DESELECTED; } public void setSelectionState(final TristateState state) { diff --git a/exist-core/src/main/java/org/exist/collections/CollectionCache.java b/exist-core/src/main/java/org/exist/collections/CollectionCache.java index ea6643ad819..8bd94defd45 100644 --- a/exist-core/src/main/java/org/exist/collections/CollectionCache.java +++ b/exist-core/src/main/java/org/exist/collections/CollectionCache.java @@ -21,10 +21,6 @@ */ package org.exist.collections; -import java.beans.ConstructorProperties; -import java.util.Optional; -import java.util.function.Function; - import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import com.github.benmanes.caffeine.cache.Weigher; @@ -39,6 +35,9 @@ import org.exist.xmldb.XmldbURI; import javax.annotation.Nullable; +import java.beans.ConstructorProperties; +import java.util.Optional; +import java.util.function.Function; /** * Global cache for {@link org.exist.collections.Collection} objects. @@ -52,7 +51,7 @@ */ @ThreadSafe public class CollectionCache implements BrokerPoolService { - private final static Logger LOG = LogManager.getLogger(CollectionCache.class); + private static final Logger LOG = LogManager.getLogger(CollectionCache.class); public static final int DEFAULT_CACHE_SIZE_BYTES = 64 * 1024 * 1024; // 64 MB public static final String CACHE_SIZE_ATTRIBUTE = "collectionCache"; diff --git a/exist-core/src/main/java/org/exist/collections/CollectionConfiguration.java b/exist-core/src/main/java/org/exist/collections/CollectionConfiguration.java index 379eb2e6b90..c4c2d4bedfb 100644 --- a/exist-core/src/main/java/org/exist/collections/CollectionConfiguration.java +++ b/exist-core/src/main/java/org/exist/collections/CollectionConfiguration.java @@ -21,19 +21,9 @@ */ package org.exist.collections; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.exist.collections.triggers.CollectionTrigger; -import org.exist.collections.triggers.CollectionTriggerProxy; -import org.exist.collections.triggers.DocumentTrigger; -import org.exist.collections.triggers.DocumentTriggerProxy; -import org.exist.collections.triggers.Trigger; -import org.exist.collections.triggers.TriggerException; -import org.exist.collections.triggers.TriggerProxy; +import org.exist.collections.triggers.*; import org.exist.config.annotation.ConfigurationClass; import org.exist.storage.BrokerPool; import org.exist.storage.DBBroker; @@ -47,15 +37,19 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + @ConfigurationClass("collection") public class CollectionConfiguration { - public final static String COLLECTION_CONFIG_SUFFIX = ".xconf"; - public final static XmldbURI COLLECTION_CONFIG_SUFFIX_URI = XmldbURI.create(COLLECTION_CONFIG_SUFFIX); - public final static String DEFAULT_COLLECTION_CONFIG_FILE = "collection" + COLLECTION_CONFIG_SUFFIX; - public final static XmldbURI DEFAULT_COLLECTION_CONFIG_FILE_URI = XmldbURI.create(DEFAULT_COLLECTION_CONFIG_FILE); + public static final String COLLECTION_CONFIG_SUFFIX = ".xconf"; + public static final XmldbURI COLLECTION_CONFIG_SUFFIX_URI = XmldbURI.create(COLLECTION_CONFIG_SUFFIX); + public static final String DEFAULT_COLLECTION_CONFIG_FILE = "collection" + COLLECTION_CONFIG_SUFFIX; + public static final XmldbURI DEFAULT_COLLECTION_CONFIG_FILE_URI = XmldbURI.create(DEFAULT_COLLECTION_CONFIG_FILE); - public final static String NAMESPACE = "http://exist-db.org/collection-config/1.0"; + public static final String NAMESPACE = "http://exist-db.org/collection-config/1.0"; private static final String ROOT_ELEMENT = "collection"; @@ -83,9 +77,9 @@ public class CollectionConfiguration { private final List> colTriggers = new ArrayList<>(); private final List> docTriggers = new ArrayList<>(); - private IndexSpec indexSpec = null; + private IndexSpec indexSpec; - private XmldbURI docName = null; + private XmldbURI docName; private XmldbURI srcCollectionURI; private XMLReaderObjectFactory.VALIDATION_SETTING validationMode = XMLReaderObjectFactory.VALIDATION_SETTING.UNKNOWN; @@ -138,7 +132,7 @@ protected void read(final DBBroker broker, final Document doc, final boolean che final NodeList triggers = node.getChildNodes(); for (int j = 0; j < triggers.getLength(); j++) { node = triggers.item(j); - if (node.getNodeType() == Node.ELEMENT_NODE && node.getLocalName().equals(TRIGGER_ELEMENT)) { + if (node.getNodeType() == Node.ELEMENT_NODE && TRIGGER_ELEMENT.equals(node.getLocalName())) { configureTrigger(broker.getBrokerPool().getClassLoader(), (Element) node, srcCollectionURI, checkOnly); } } diff --git a/exist-core/src/main/java/org/exist/collections/CollectionConfigurationManager.java b/exist-core/src/main/java/org/exist/collections/CollectionConfigurationManager.java index 824fbb59679..1a767b6225a 100644 --- a/exist-core/src/main/java/org/exist/collections/CollectionConfigurationManager.java +++ b/exist-core/src/main/java/org/exist/collections/CollectionConfigurationManager.java @@ -26,9 +26,9 @@ import org.exist.EXistException; import org.exist.Namespaces; import org.exist.collections.triggers.TriggerException; +import org.exist.dom.memtree.SAXAdapter; import org.exist.dom.persistent.BinaryDocument; import org.exist.dom.persistent.DocumentImpl; -import org.exist.dom.memtree.SAXAdapter; import org.exist.security.PermissionDeniedException; import org.exist.storage.*; import org.exist.storage.lock.Lock.LockMode; diff --git a/exist-core/src/main/java/org/exist/collections/CollectionURI.java b/exist-core/src/main/java/org/exist/collections/CollectionURI.java index d1c6499068f..be4bc403d53 100644 --- a/exist-core/src/main/java/org/exist/collections/CollectionURI.java +++ b/exist-core/src/main/java/org/exist/collections/CollectionURI.java @@ -26,10 +26,10 @@ * */ public class CollectionURI { - public final static char FRAGMENT_SEPARATOR = '/'; + public static final char FRAGMENT_SEPARATOR = '/'; - private char[] uri = null; - private int length = 0; + private char[] uri; + private int length; private int hash; // Default to 0 diff --git a/exist-core/src/main/java/org/exist/collections/IndexInfo.java b/exist-core/src/main/java/org/exist/collections/IndexInfo.java index 0f987241024..fe71b2da2bf 100644 --- a/exist-core/src/main/java/org/exist/collections/IndexInfo.java +++ b/exist-core/src/main/java/org/exist/collections/IndexInfo.java @@ -31,11 +31,7 @@ import org.exist.storage.txn.Txn; import org.exist.util.serializer.DOMStreamer; import org.exist.xmldb.XmldbURI; -import org.xml.sax.ContentHandler; -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; -import org.xml.sax.XMLReader; +import org.xml.sax.*; import org.xml.sax.ext.LexicalHandler; /** @@ -53,8 +49,8 @@ public class IndexInfo { private DOMStreamer streamer; private DocumentTriggers docTriggers; - private boolean creating = false; - private Permission oldDocPermissions = null; + private boolean creating; + private Permission oldDocPermissions; IndexInfo(final Indexer indexer, final CollectionConfiguration collectionConfig, final ManagedDocumentLock documentLock) { this.indexer = indexer; diff --git a/exist-core/src/main/java/org/exist/collections/ManagedLocks.java b/exist-core/src/main/java/org/exist/collections/ManagedLocks.java index 6cf3ae7b751..66069cc76cb 100644 --- a/exist-core/src/main/java/org/exist/collections/ManagedLocks.java +++ b/exist-core/src/main/java/org/exist/collections/ManagedLocks.java @@ -40,7 +40,7 @@ */ public class ManagedLocks implements Iterable, AutoCloseable { - private final static Logger LOG = LogManager.getLogger(ManagedLocks.class); + private static final Logger LOG = LogManager.getLogger(ManagedLocks.class); private final List managedLocks; diff --git a/exist-core/src/main/java/org/exist/collections/MutableCollection.java b/exist-core/src/main/java/org/exist/collections/MutableCollection.java index 3e7fbe61d3b..0f31e1eeb9b 100644 --- a/exist-core/src/main/java/org/exist/collections/MutableCollection.java +++ b/exist-core/src/main/java/org/exist/collections/MutableCollection.java @@ -25,20 +25,17 @@ import com.evolvedbinary.j8fu.function.Consumer2E; import net.jcip.annotations.GuardedBy; import net.jcip.annotations.NotThreadSafe; -import org.apache.commons.io.input.CloseShieldReader; -import org.exist.dom.QName; -import org.exist.dom.persistent.*; - -import java.io.*; -import java.util.*; - import org.apache.commons.io.input.CloseShieldInputStream; +import org.apache.commons.io.input.CloseShieldReader; +import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.Database; import org.exist.EXistException; import org.exist.Indexer; import org.exist.collections.triggers.*; +import org.exist.dom.QName; +import org.exist.dom.persistent.*; import org.exist.indexing.IndexController; import org.exist.indexing.StreamListener; import org.exist.security.Account; @@ -59,7 +56,6 @@ import org.exist.util.MimeType; import org.exist.util.XMLReaderObjectFactory; import org.exist.util.XMLReaderObjectFactory.VALIDATION_SETTING; -import org.apache.commons.io.input.UnsynchronizedByteArrayInputStream; import org.exist.util.serializer.DOMStreamer; import org.exist.xmldb.XmldbURI; import org.exist.xquery.Constants; @@ -70,6 +66,8 @@ import org.xml.sax.XMLReader; import javax.annotation.Nullable; +import java.io.*; +import java.util.*; import static org.exist.storage.lock.Lock.LockMode.*; @@ -115,7 +113,7 @@ public class MutableCollection implements Collection { private long created; private volatile boolean isTempCollection; private final Permission permissions; - @Deprecated private CollectionMetadata collectionMetadata = null; + @Deprecated private CollectionMetadata collectionMetadata; /** * Constructs a Collection Object (not yet persisted) @@ -197,7 +195,7 @@ public final void setPath(XmldbURI path) { public final void setPath(XmldbURI path, final boolean updateChildren) { path = path.toCollectionPathURI(); //TODO : see if the URI resolves against DBBroker.TEMP_COLLECTION - this.isTempCollection = path.getRawCollectionPath().equals(XmldbURI.TEMP_COLLECTION); + this.isTempCollection = XmldbURI.TEMP_COLLECTION.equals(path.getRawCollectionPath()); this.path = path; if (updateChildren) { @@ -705,9 +703,6 @@ public LockedDocument getDocumentWithLock(final DBBroker broker, final XmldbURI final DocumentImpl doc = documents.get(name.lastSegmentString()); - // NOTE: early release of Collection lock inline with Asymmetrical Locking scheme - collectionLock.close(); - if(doc == null) { unlockFn.run(); return null; @@ -780,7 +775,7 @@ public XmldbURI getParentURI() { } @Override - final public Permission getPermissions() { + public final Permission getPermissions() { try(final ManagedCollectionLock collectionLock = lockManager.acquireCollectionReadLock(path)) { return permissions; } catch(final LockException e) { @@ -1383,7 +1378,7 @@ private void storeXMLInternal(final Txn transaction, final DBBroker broker, fina info.getTriggers().afterUpdateDocument(broker, transaction, document); } - db.getNotificationService().notifyUpdate(document, (info.isCreating() ? UpdateListener.ADD : UpdateListener.UPDATE)); + db.getNotificationService().notifyUpdate(document, info.isCreating() ? UpdateListener.ADD : UpdateListener.UPDATE); //Is it a collection configuration file ? final XmldbURI docName = document.getFileURI(); //WARNING : there is no reason to lock the collection since setPath() is normally called in a safe way @@ -1432,7 +1427,7 @@ public IndexInfo validateXMLResource(final Txn transaction, final DBBroker broke } private IndexInfo validateXMLResource(final Txn transaction, final DBBroker broker, final XmldbURI name, final CollectionConfiguration colconf, final InputSource source, final XMLReader reader) throws EXistException, PermissionDeniedException, TriggerException, SAXException, LockException, IOException { - return validateXMLResourceInternal(transaction, broker, name, colconf, (info) -> { + return validateXMLResourceInternal(transaction, broker, name, colconf, info -> { info.setReader(reader, null); try { @@ -1485,7 +1480,7 @@ private InputSource closeShieldInputSource(final InputSource source) { @Deprecated @Override public IndexInfo validateXMLResource(final Txn transaction, final DBBroker broker, final XmldbURI name, final Node node) throws EXistException, PermissionDeniedException, TriggerException, SAXException, LockException, IOException { - return validateXMLResourceInternal(transaction, broker, name, getConfiguration(broker), (info) -> { + return validateXMLResourceInternal(transaction, broker, name, getConfiguration(broker), info -> { info.setDOMStreamer(new DOMStreamer()); info.getDOMStreamer().serialize(node, true); }); @@ -1531,7 +1526,7 @@ private IndexInfo validateXMLResourceInternal(final Txn transaction, final DBBro checkPermissionsForAddDocument(broker, oldDoc); // NOTE: the new `document` object actually gets discarded in favour of the `oldDoc` below if there is an oldDoc and it is XML (so we can use -1 as the docId because it will never be used) - final int docId = (oldDoc != null && oldDoc.getResourceType() == DocumentImpl.XML_FILE) ? - 1 : broker.getNextResourceId(transaction); + final int docId = oldDoc != null && oldDoc.getResourceType() == DocumentImpl.XML_FILE ? - 1 : broker.getNextResourceId(transaction); DocumentImpl document = new DocumentImpl(null, (BrokerPool) db, this, docId, name); checkCollectionConflict(name); @@ -1965,19 +1960,19 @@ public IndexSpec getIndexConfiguration(final DBBroker broker) { //... otherwise return the general config (the broker's one) // Fall back to broker config when collection.xconf has no element (fixes #2948) final IndexSpec spec = conf.getIndexConfiguration(); - return (spec != null) ? spec : broker.getIndexConfiguration(); + return spec != null ? spec : broker.getIndexConfiguration(); } @Override public GeneralRangeIndexSpec getIndexByPathConfiguration(final DBBroker broker, final NodePath nodePath) { final IndexSpec idxSpec = getIndexConfiguration(broker); - return (idxSpec == null) ? null : idxSpec.getIndexByPath(nodePath); + return idxSpec == null ? null : idxSpec.getIndexByPath(nodePath); } @Override public QNameRangeIndexSpec getIndexByQNameConfiguration(final DBBroker broker, final QName nodeName) { final IndexSpec idxSpec = getIndexConfiguration(broker); - return (idxSpec == null) ? null : idxSpec.getIndexByQName(nodeName); + return idxSpec == null ? null : idxSpec.getIndexByQName(nodeName); } @Override diff --git a/exist-core/src/main/java/org/exist/collections/triggers/AbstractTriggerProxy.java b/exist-core/src/main/java/org/exist/collections/triggers/AbstractTriggerProxy.java index cdb9620ecb9..aafc8949f2f 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/AbstractTriggerProxy.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/AbstractTriggerProxy.java @@ -21,13 +21,13 @@ */ package org.exist.collections.triggers; -import java.util.List; -import java.util.Map; - import org.exist.collections.Collection; import org.exist.storage.DBBroker; import org.exist.storage.txn.Txn; +import java.util.List; +import java.util.Map; + /** * * @author aretter @@ -37,11 +37,11 @@ public abstract class AbstractTriggerProxy implements Trigger private final Class clazz; private Map> parameters; - public AbstractTriggerProxy(final Class clazz) { + protected AbstractTriggerProxy(final Class clazz) { this.clazz = clazz; } - public AbstractTriggerProxy(final Class clazz, final Map> parameters) { + protected AbstractTriggerProxy(final Class clazz, final Map> parameters) { this.clazz = clazz; this.parameters = parameters; } diff --git a/exist-core/src/main/java/org/exist/collections/triggers/AbstractTriggersVisitor.java b/exist-core/src/main/java/org/exist/collections/triggers/AbstractTriggersVisitor.java index c2da43af4ac..e40ffee6095 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/AbstractTriggersVisitor.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/AbstractTriggersVisitor.java @@ -21,22 +21,22 @@ */ package org.exist.collections.triggers; -import java.util.List; -import java.util.Map; - import org.exist.collections.Collection; import org.exist.storage.DBBroker; import org.exist.storage.txn.Txn; +import java.util.List; +import java.util.Map; + /** * * @author aretter */ public abstract class AbstractTriggersVisitor implements TriggersVisitor { - private List triggers; + private final List triggers; - public AbstractTriggersVisitor(List triggers) { + protected AbstractTriggersVisitor(List triggers) { this.triggers = triggers; } diff --git a/exist-core/src/main/java/org/exist/collections/triggers/CSVExtractingTrigger.java b/exist-core/src/main/java/org/exist/collections/triggers/CSVExtractingTrigger.java index f3196e602c9..068b8fba056 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/CSVExtractingTrigger.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/CSVExtractingTrigger.java @@ -21,9 +21,6 @@ */ package org.exist.collections.triggers; -import java.util.*; -import javax.xml.XMLConstants; -import javax.xml.namespace.QName; import org.exist.collections.Collection; import org.exist.dom.persistent.DocumentImpl; import org.exist.storage.DBBroker; @@ -32,6 +29,10 @@ import org.xml.sax.Attributes; import org.xml.sax.SAXException; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import java.util.*; + /** * Extracts CSV data from an element into a number of new child elements * @@ -85,13 +86,13 @@ public class CSVExtractingTrigger extends FilteringTrigger { private String separator; //key is the xpath to extract for, and value is the extractions to make from the value at that path - private Map extractions = new HashMap<>(); + private final Map extractions = new HashMap<>(); //the current node path of the SAX stream - private NodePath currentNodePath = new NodePath(); + private final NodePath currentNodePath = new NodePath(); - private boolean capture = false; //flag to indicate whether to buffer character data for extraction of csv values - private StringBuilder charactersBuf = new StringBuilder(); //buffer for character data, which will then be parsed to extract csv values + private boolean capture; //flag to indicate whether to buffer character data for extraction of csv values + private final StringBuilder charactersBuf = new StringBuilder(); //buffer for character data, which will then be parsed to extract csv values @SuppressWarnings("unchecked") @@ -289,7 +290,7 @@ public void setMatchAttribute(final String attrName, final String attrValue) { } public boolean mustMatchAttribute() { - return(this.matchAttrName != null && this.matchAttrValue != null); + return this.matchAttrName != null && this.matchAttrValue != null; } public boolean matchesAttribute(final String attrName, final String attrValue) { diff --git a/exist-core/src/main/java/org/exist/collections/triggers/CollectionTriggers.java b/exist-core/src/main/java/org/exist/collections/triggers/CollectionTriggers.java index 412b0e08aa6..cfa1f864b11 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/CollectionTriggers.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/CollectionTriggers.java @@ -21,16 +21,16 @@ */ package org.exist.collections.triggers; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import org.exist.collections.Collection; import org.exist.collections.CollectionConfiguration; import org.exist.storage.DBBroker; import org.exist.storage.txn.Txn; import org.exist.xmldb.XmldbURI; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + /** * @author Dmitriy Shabanov * diff --git a/exist-core/src/main/java/org/exist/collections/triggers/DeferrableFilteringTrigger.java b/exist-core/src/main/java/org/exist/collections/triggers/DeferrableFilteringTrigger.java index 1452e10fe3f..9c2fa6d11e0 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/DeferrableFilteringTrigger.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/DeferrableFilteringTrigger.java @@ -46,7 +46,7 @@ */ public abstract class DeferrableFilteringTrigger extends FilteringTrigger { - private boolean defer = false; + private boolean defer; protected Deque deferred = new ArrayDeque<>(); public boolean isDeferring() { @@ -242,29 +242,29 @@ protected void applyDeferredEvents() throws SAXException { SAXEvent event = null; while((event = deferred.poll()) != null) { switch (event) { - case SetDocumentLocator setDocumentLocator -> setDocumentLocator_deferred(setDocumentLocator.locator); - case StartDocument startDocument -> startDocument_deferred(); - case EndDocument endDocument -> endDocument_deferred(); + case SetDocumentLocator setDocumentLocator -> setDocumentLocatorDeferred(setDocumentLocator.locator); + case StartDocument startDocument -> startDocumentDeferred(); + case EndDocument endDocument -> endDocumentDeferred(); case StartPrefixMapping startPrefixMapping -> - startPrefixMapping_deferred(startPrefixMapping.prefix, startPrefixMapping.uri); - case EndPrefixMapping endPrefixMapping -> endPrefixMapping_deferred(endPrefixMapping.prefix); + startPrefixMappingDeferred(startPrefixMapping.prefix, startPrefixMapping.uri); + case EndPrefixMapping endPrefixMapping -> endPrefixMappingDeferred(endPrefixMapping.prefix); case StartElement startElement -> - startElement_deferred(startElement.namespaceURI, startElement.localName, startElement.qname, startElement.attributes); + startElementDeferred(startElement.namespaceURI, startElement.localName, startElement.qname, startElement.attributes); case EndElement endElement -> - endElement_deferred(endElement.namespaceURI, endElement.localName, endElement.qname); - case Characters characters -> characters_deferred(characters.ch, 0, characters.ch.length); + endElementDeferred(endElement.namespaceURI, endElement.localName, endElement.qname); + case Characters characters -> charactersDeferred(characters.ch, 0, characters.ch.length); case IgnorableWhitespace ignorableWhitespace -> - ignorableWhitespace_deferred(ignorableWhitespace.ch, 0, ignorableWhitespace.ch.length); + ignorableWhitespaceDeferred(ignorableWhitespace.ch, 0, ignorableWhitespace.ch.length); case ProcessingInstruction processingInstruction -> - processingInstruction_deferred(processingInstruction.target, processingInstruction.data); - case SkippedEntity skippedEntity -> skippedEntity_deferred(skippedEntity.name); - case StartDTD startDTD -> startDTD_deferred(startDTD.name, startDTD.publicId, startDTD.systemId); - case EndDTD endDTD -> endDTD_deferred(); - case StartEntity startEntity -> startEntity_deferred(startEntity.name); - case EndEntity endEntity -> endEntity_deferred(endEntity.name); - case StartCDATA startCDATA -> startCDATA_deferred(); - case EndCDATA endCDATA -> endCDATA_deferred(); - case Comment comment -> comment_deferred(comment.ch, 0, comment.ch.length); + processingInstructionDeferred(processingInstruction.target, processingInstruction.data); + case SkippedEntity skippedEntity -> skippedEntityDeferred(skippedEntity.name); + case StartDTD startDTD -> startDTDDeferred(startDTD.name, startDTD.publicId, startDTD.systemId); + case EndDTD endDTD -> endDTDDeferred(); + case StartEntity startEntity -> startEntityDeferred(startEntity.name); + case EndEntity endEntity -> endEntityDeferred(endEntity.name); + case StartCDATA startCDATA -> startCDATADeferred(); + case EndCDATA endCDATA -> endCDATADeferred(); + case Comment comment -> commentDeferred(comment.ch, 0, comment.ch.length); default -> { } } @@ -272,77 +272,77 @@ protected void applyDeferredEvents() throws SAXException { } // - protected void setDocumentLocator_deferred(final Locator locator) { + protected void setDocumentLocatorDeferred(final Locator locator) { super.setDocumentLocator(locator); } - protected void startDocument_deferred() throws SAXException { + protected void startDocumentDeferred() throws SAXException { super.startDocument(); } - protected void endDocument_deferred() throws SAXException { + protected void endDocumentDeferred() throws SAXException { super.endDocument(); } - protected void startPrefixMapping_deferred(final String prefix, final String uri) throws SAXException { + protected void startPrefixMappingDeferred(final String prefix, final String uri) throws SAXException { super.startPrefixMapping(prefix, uri); } - protected void endPrefixMapping_deferred(final String prefix) throws SAXException { + protected void endPrefixMappingDeferred(final String prefix) throws SAXException { super.endPrefixMapping(prefix); } - protected void startElement_deferred(final String namespaceUri, final String localName, final String qName, final Attributes attrs) throws SAXException { + protected void startElementDeferred(final String namespaceUri, final String localName, final String qName, final Attributes attrs) throws SAXException { super.startElement(namespaceUri, localName, qName, attrs); } - protected void endElement_deferred(final String namespaceUri, final String localName, final String qName) throws SAXException { + protected void endElementDeferred(final String namespaceUri, final String localName, final String qName) throws SAXException { super.endElement(namespaceUri, localName, qName); } - protected void characters_deferred(final char[] ch, final int start, final int length) throws SAXException { + protected void charactersDeferred(final char[] ch, final int start, final int length) throws SAXException { super.characters(ch, start, length); } - protected void ignorableWhitespace_deferred(final char[] ch, final int start, final int length) throws SAXException { + protected void ignorableWhitespaceDeferred(final char[] ch, final int start, final int length) throws SAXException { super.ignorableWhitespace(ch, start, length); } - protected void processingInstruction_deferred(final String target, final String data) throws SAXException { + protected void processingInstructionDeferred(final String target, final String data) throws SAXException { super.processingInstruction(target, data); } - protected void skippedEntity_deferred(final String name) throws SAXException { + protected void skippedEntityDeferred(final String name) throws SAXException { super.skippedEntity(name); } // // - protected void startDTD_deferred(final String name, final String publicId, final String systemId) throws SAXException { + protected void startDTDDeferred(final String name, final String publicId, final String systemId) throws SAXException { super.startDTD(name, publicId, systemId); } - protected void endDTD_deferred() throws SAXException { + protected void endDTDDeferred() throws SAXException { super.endDTD(); } - protected void startEntity_deferred(final String name) throws SAXException { + protected void startEntityDeferred(final String name) throws SAXException { super.startEntity(name); } - protected void endEntity_deferred(final String name) throws SAXException { + protected void endEntityDeferred(final String name) throws SAXException { super.endEntity(name); } - protected void startCDATA_deferred() throws SAXException { + protected void startCDATADeferred() throws SAXException { super.startCDATA(); } - protected void endCDATA_deferred() throws SAXException { + protected void endCDATADeferred() throws SAXException { super.endCDATA(); } - protected void comment_deferred(final char[] ch, final int start, final int length) throws SAXException { + protected void commentDeferred(final char[] ch, final int start, final int length) throws SAXException { super.comment(ch, start, length); } // diff --git a/exist-core/src/main/java/org/exist/collections/triggers/DocumentTriggers.java b/exist-core/src/main/java/org/exist/collections/triggers/DocumentTriggers.java index 6a9e3a9a779..904055bd2ae 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/DocumentTriggers.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/DocumentTriggers.java @@ -21,10 +21,6 @@ */ package org.exist.collections.triggers; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - import org.exist.Indexer; import org.exist.collections.Collection; import org.exist.collections.CollectionConfiguration; @@ -32,15 +28,13 @@ import org.exist.storage.DBBroker; import org.exist.storage.txn.Txn; import org.exist.xmldb.XmldbURI; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.ErrorHandler; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; +import org.xml.sax.*; import org.xml.sax.ext.LexicalHandler; import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; /** * @author Dmitriy Shabanov @@ -54,7 +48,7 @@ public class DocumentTriggers implements DocumentTrigger, ContentHandler, Lexica private LexicalHandler lexicalHandler; private ErrorHandler errorHandler; - private SAXTrigger last = null; + private SAXTrigger last; private final List triggers; @@ -353,19 +347,22 @@ public void setValidating(boolean validating) { @Override public void warning(SAXParseException exception) throws SAXException { - if (errorHandler != null) + if (errorHandler != null) { errorHandler.warning(exception); + } } @Override public void error(SAXParseException exception) throws SAXException { - if (errorHandler != null) + if (errorHandler != null) { errorHandler.error(exception); + } } @Override public void fatalError(SAXParseException exception) throws SAXException { - if (errorHandler != null) + if (errorHandler != null) { errorHandler.fatalError(exception); + } } } diff --git a/exist-core/src/main/java/org/exist/collections/triggers/Dumper.java b/exist-core/src/main/java/org/exist/collections/triggers/Dumper.java index 537d19a23bb..c1b3d32a2df 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/Dumper.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/Dumper.java @@ -21,10 +21,10 @@ */ package org.exist.collections.triggers; -import java.util.Map.Entry; import org.exist.collections.Collection; import org.exist.dom.persistent.DefaultDocumentSet; import org.exist.dom.persistent.DocumentImpl; +import org.exist.security.PermissionDeniedException; import org.exist.storage.DBBroker; import org.exist.storage.txn.Txn; import org.exist.util.LockException; @@ -33,7 +33,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.exist.security.PermissionDeniedException; +import java.util.Map.Entry; /** * @author wolf @@ -125,4 +125,4 @@ public void beforeUpdateDocumentMetadata(DBBroker broker, Txn txn, DocumentImpl @Override public void afterUpdateDocumentMetadata(DBBroker broker, Txn txn, DocumentImpl document) throws TriggerException { } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/collections/triggers/HistoryTrigger.java b/exist-core/src/main/java/org/exist/collections/triggers/HistoryTrigger.java index 108bb567839..8b7c4a9b80a 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/HistoryTrigger.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/HistoryTrigger.java @@ -21,12 +21,6 @@ */ package org.exist.collections.triggers; -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.Date; -import java.util.List; -import java.util.Map; - import org.exist.EXistException; import org.exist.collections.Collection; import org.exist.dom.persistent.DocumentImpl; @@ -38,6 +32,12 @@ import org.exist.xquery.XPathException; import org.exist.xquery.value.DateTimeValue; +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Date; +import java.util.List; +import java.util.Map; + /** * This collection trigger will save all old versions of documents before * they are overwritten or removed. The old versions are kept in the diff --git a/exist-core/src/main/java/org/exist/collections/triggers/SAXTrigger.java b/exist-core/src/main/java/org/exist/collections/triggers/SAXTrigger.java index 4815bcc6ac3..7ab24ef70d0 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/SAXTrigger.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/SAXTrigger.java @@ -21,22 +21,16 @@ */ package org.exist.collections.triggers; -import java.util.List; -import java.util.Map; - import org.exist.Indexer; import org.exist.collections.Collection; import org.exist.storage.DBBroker; import org.exist.storage.txn.Txn; -import org.xml.sax.Attributes; -import org.xml.sax.ContentHandler; -import org.xml.sax.ErrorHandler; -import org.xml.sax.Locator; -import org.xml.sax.SAXException; -import org.xml.sax.SAXParseException; +import org.xml.sax.*; import org.xml.sax.ext.LexicalHandler; import javax.annotation.Nullable; +import java.util.List; +import java.util.Map; /** * Abstract default implementation of a Trigger. This implementation just @@ -47,11 +41,11 @@ public abstract class SAXTrigger implements DocumentTrigger, ContentHandler, LexicalHandler, ErrorHandler { // The output handlers to which SAX events should be forwarded - private ContentHandler nextContentHandler = null; - private LexicalHandler nextLexicalHandler = null; - private ErrorHandler nextErrorHandler = null; + private ContentHandler nextContentHandler; + private LexicalHandler nextLexicalHandler; + private ErrorHandler nextErrorHandler; - private Collection collection = null; + private Collection collection; private boolean validating = true; protected Collection getCollection() { @@ -81,14 +75,16 @@ public boolean isValidating() { @Override public void setDocumentLocator(Locator locator) { - if (nextContentHandler != null) + if (nextContentHandler != null) { nextContentHandler.setDocumentLocator(locator); + } } @Override public void startDocument() throws SAXException { - if (nextContentHandler != null) + if (nextContentHandler != null) { nextContentHandler.startDocument(); + } } @Override @@ -100,113 +96,132 @@ public void declaration(@Nullable final String version, @Nullable final String e @Override public void endDocument() throws SAXException { - if (nextContentHandler != null) + if (nextContentHandler != null) { nextContentHandler.endDocument(); + } } @Override public void startPrefixMapping(String prefix, String namespaceURI) throws SAXException { - if (nextContentHandler != null) + if (nextContentHandler != null) { nextContentHandler.startPrefixMapping(prefix, namespaceURI); + } } @Override public void endPrefixMapping(String prefix) throws SAXException { - if (nextContentHandler != null) + if (nextContentHandler != null) { nextContentHandler.endPrefixMapping(prefix); + } } @Override public void startElement(String namespaceURI, String localName, String qname, Attributes attributes) throws SAXException { - if (nextContentHandler != null) + if (nextContentHandler != null) { nextContentHandler.startElement(namespaceURI, localName, qname, attributes); + } } @Override public void endElement(String namespaceURI, String localName, String qname) throws SAXException { - if (nextContentHandler != null) + if (nextContentHandler != null) { nextContentHandler.endElement(namespaceURI, localName, qname); + } } @Override public void characters(char[] ch, int start, int length) throws SAXException { - if (nextContentHandler != null) + if (nextContentHandler != null) { nextContentHandler.characters(ch, start, length); + } } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { - if (nextContentHandler != null) + if (nextContentHandler != null) { nextContentHandler.ignorableWhitespace(ch, start, length); + } } @Override public void processingInstruction(String target, String data) throws SAXException { - if (nextContentHandler != null) + if (nextContentHandler != null) { nextContentHandler.processingInstruction(target, data); + } } @Override public void skippedEntity(String arg0) throws SAXException { - if (nextContentHandler != null) + if (nextContentHandler != null) { nextContentHandler.skippedEntity(arg0); + } } @Override public void startDTD(String name, String publicId, String systemId) throws SAXException { - if (nextLexicalHandler != null) + if (nextLexicalHandler != null) { nextLexicalHandler.startDTD(name, publicId, systemId); + } } @Override public void endDTD() throws SAXException { - if (nextLexicalHandler != null) + if (nextLexicalHandler != null) { nextLexicalHandler.endDTD(); + } } @Override public void startEntity(String arg0) throws SAXException { - if (nextLexicalHandler != null) + if (nextLexicalHandler != null) { nextLexicalHandler.startEntity(arg0); + } } @Override public void endEntity(String arg0) throws SAXException { - if (nextLexicalHandler != null) + if (nextLexicalHandler != null) { nextLexicalHandler.endEntity(arg0); + } } @Override public void startCDATA() throws SAXException { - if (nextLexicalHandler != null) + if (nextLexicalHandler != null) { nextLexicalHandler.startCDATA(); + } } @Override public void endCDATA() throws SAXException { - if (nextLexicalHandler != null) + if (nextLexicalHandler != null) { nextLexicalHandler.endCDATA(); + } } @Override public void comment(char[] ch, int start, int length) throws SAXException { - if (nextLexicalHandler != null) + if (nextLexicalHandler != null) { nextLexicalHandler.comment(ch, start, length); + } } public void warning(SAXParseException exception) throws SAXException { - if (nextErrorHandler != null) + if (nextErrorHandler != null) { nextErrorHandler.warning(exception); + } } public void error(SAXParseException exception) throws SAXException { - if (nextErrorHandler != null) + if (nextErrorHandler != null) { nextErrorHandler.error(exception); + } } public void fatalError(SAXParseException exception) throws SAXException { - if (nextErrorHandler != null) + if (nextErrorHandler != null) { nextErrorHandler.fatalError(exception); + } } protected void next(SAXTrigger nextTrigger) { @@ -220,4 +235,4 @@ protected void next(Indexer indexer) { nextLexicalHandler = indexer; nextErrorHandler = indexer; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/collections/triggers/STXTemplatesCache.java b/exist-core/src/main/java/org/exist/collections/triggers/STXTemplatesCache.java index 16a1486a9cf..0e2a61ed028 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/STXTemplatesCache.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/STXTemplatesCache.java @@ -21,12 +21,6 @@ */ package org.exist.collections.triggers; -import javax.xml.transform.Templates; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TemplatesHandler; - import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import net.jcip.annotations.ThreadSafe; @@ -40,6 +34,12 @@ import org.exist.xmldb.XmldbURI; import org.xml.sax.SAXException; +import javax.xml.transform.Templates; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TemplatesHandler; + /** * Cache for STX Templates. * @@ -49,7 +49,7 @@ * @author Adam Retter */ @ThreadSafe -public class STXTemplatesCache { +public final class STXTemplatesCache { private static final Logger LOG = LogManager.getLogger(STXTemplatesCache.class); private static final STXTemplatesCache INSTANCE = new STXTemplatesCache(); @@ -138,4 +138,4 @@ private Templates getTemplate() { return templates; } } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/collections/triggers/STXTransformerTrigger.java b/exist-core/src/main/java/org/exist/collections/triggers/STXTransformerTrigger.java index cde3f9e5d7e..6e5ee9ba395 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/STXTransformerTrigger.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/STXTransformerTrigger.java @@ -21,17 +21,6 @@ */ package org.exist.collections.triggers; -import java.net.URISyntaxException; -import java.util.List; -import java.util.Map; - -import javax.xml.transform.Templates; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.sax.SAXTransformerFactory; -import javax.xml.transform.sax.TransformerHandler; -import javax.xml.transform.stream.StreamSource; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.collections.Collection; @@ -45,6 +34,16 @@ import org.exist.xquery.Constants; import org.xml.sax.SAXException; +import javax.xml.transform.Templates; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.sax.SAXTransformerFactory; +import javax.xml.transform.sax.TransformerHandler; +import javax.xml.transform.stream.StreamSource; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Map; + /** * STXTransformerTrigger applies an STX stylesheet to the input SAX stream, * using Joost. The stylesheet location @@ -58,7 +57,7 @@ public class STXTransformerTrigger extends SAXTrigger implements DocumentTrigger protected Logger LOG = LogManager.getLogger(getClass()); private final SAXTransformerFactory factory = (SAXTransformerFactory)TransformerFactory.newInstance("net.sf.joost.trax.TransformerFactoryImpl", getClass().getClassLoader()); - private TransformerHandler handler = null; + private TransformerHandler handler; @Override public void configure(DBBroker broker, Txn transaction, Collection parent, Map> parameters) throws TriggerException { diff --git a/exist-core/src/main/java/org/exist/collections/triggers/Trigger.java b/exist-core/src/main/java/org/exist/collections/triggers/Trigger.java index db9bec7bbe4..7114c38b99c 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/Trigger.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/Trigger.java @@ -21,15 +21,15 @@ */ package org.exist.collections.triggers; -import java.util.List; -import java.util.Map; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.collections.Collection; import org.exist.storage.DBBroker; import org.exist.storage.txn.Txn; +import java.util.List; +import java.util.Map; + /** * Defines the base interface for collection triggers. Triggers are registered through the * collection configuration file, called "collection.xconf", which should be diff --git a/exist-core/src/main/java/org/exist/collections/triggers/TriggerProxy.java b/exist-core/src/main/java/org/exist/collections/triggers/TriggerProxy.java index b4c52fcea95..12535ecdfb1 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/TriggerProxy.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/TriggerProxy.java @@ -21,13 +21,13 @@ */ package org.exist.collections.triggers; -import java.util.List; -import java.util.Map; - import org.exist.collections.Collection; import org.exist.storage.DBBroker; import org.exist.storage.txn.Txn; +import java.util.List; +import java.util.Map; + /** * * @author aretter diff --git a/exist-core/src/main/java/org/exist/collections/triggers/TriggerStatePerThread.java b/exist-core/src/main/java/org/exist/collections/triggers/TriggerStatePerThread.java index d566c74414d..aa5bc5fe55c 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/TriggerStatePerThread.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/TriggerStatePerThread.java @@ -37,7 +37,7 @@ */ public class TriggerStatePerThread { - private final static ThreadLocal> THREAD_LOCAL_STATES = ThreadLocal.withInitial(ArrayDeque::new); + private static final ThreadLocal> THREAD_LOCAL_STATES = ThreadLocal.withInitial(ArrayDeque::new); public static void setAndTest(final Trigger trigger, final TriggerPhase triggerPhase, final TriggerEvent triggerEvent, final XmldbURI src, final @Nullable XmldbURI dst) throws CyclicTriggerException { final Deque states = THREAD_LOCAL_STATES.get(); diff --git a/exist-core/src/main/java/org/exist/collections/triggers/XQueryStartupTrigger.java b/exist-core/src/main/java/org/exist/collections/triggers/XQueryStartupTrigger.java index 15e16e53d45..9d8d1e44516 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/XQueryStartupTrigger.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/XQueryStartupTrigger.java @@ -21,8 +21,6 @@ */ package org.exist.collections.triggers; -import java.util.*; - import org.apache.commons.lang3.StringUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -45,6 +43,8 @@ import org.exist.xquery.XQueryContext; import org.exist.xquery.value.Sequence; +import java.util.*; + /** * Startup Trigger to fire XQuery scripts during database startup. * @@ -73,7 +73,7 @@ */ public class XQueryStartupTrigger implements StartupTrigger { - protected final static Logger LOG = LogManager.getLogger(XQueryStartupTrigger.class); + protected static final Logger LOG = LogManager.getLogger(XQueryStartupTrigger.class); private static final String XQUERY = "xquery"; private static final String AUTOSTART_COLLECTION = "/db/system/autostart"; @@ -164,9 +164,9 @@ private boolean isPermissionsOK(Collection collection) { Permission perms = collection.getPermissions(); - return (perms.getOwner().getName().equals(SecurityManager.SYSTEM) - && perms.getGroup().getName().equals(SecurityManager.DBA_GROUP) - && perms.getMode() == Permission.DEFAULT_SYSTEM_SECURITY_COLLECTION_PERM); + return SecurityManager.SYSTEM.equals(perms.getOwner().getName()) + && SecurityManager.DBA_GROUP.equals(perms.getGroup().getName()) + && perms.getMode() == Permission.DEFAULT_SYSTEM_SECURITY_COLLECTION_PERM; } @@ -179,10 +179,10 @@ private boolean isPermissionsOK(Collection collection) { */ private boolean isPermissionsOK(final DocumentImpl document) { final Permission perms = document.getPermissions(); - return (perms.getOwner().hasDbaRole() - && perms.getGroup().getName().equals(SecurityManager.DBA_GROUP) + return perms.getOwner().hasDbaRole() + && SecurityManager.DBA_GROUP.equals(perms.getGroup().getName()) && perms.getMode() == Permission.DEFAULT_SYSTEM_SECURITY_COLLECTION_PERM - && document.getMimeType().equals(REQUIRED_MIMETYPE)); + && REQUIRED_MIMETYPE.equals(document.getMimeType()); } diff --git a/exist-core/src/main/java/org/exist/collections/triggers/XQueryTrigger.java b/exist-core/src/main/java/org/exist/collections/triggers/XQueryTrigger.java index d272cd416c1..f06f80df035 100644 --- a/exist-core/src/main/java/org/exist/collections/triggers/XQueryTrigger.java +++ b/exist-core/src/main/java/org/exist/collections/triggers/XQueryTrigger.java @@ -21,15 +21,12 @@ */ package org.exist.collections.triggers; -import java.io.IOException; -import java.util.*; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.collections.Collection; +import org.exist.dom.QName; import org.exist.dom.persistent.DocumentImpl; import org.exist.dom.persistent.NodeSet; -import org.exist.dom.QName; import org.exist.security.PermissionDeniedException; import org.exist.source.DBSource; import org.exist.source.Source; @@ -43,6 +40,9 @@ import org.exist.xquery.value.Sequence; import org.exist.xquery.value.StringValue; +import java.io.IOException; +import java.util.*; + import static com.evolvedbinary.j8fu.tuple.Tuple.Tuple; /** @@ -64,7 +64,7 @@ * @author Pierrick Brihaye * @author Adam Retter * @author Evgeny Gazdovsky -*/ + */ public class XQueryTrigger extends SAXTrigger implements DocumentTrigger, CollectionTrigger { private static final Logger LOG = LogManager.getLogger(XQueryTrigger.class); @@ -103,17 +103,17 @@ public class XQueryTrigger extends SAXTrigger implements DocumentTrigger, Collec public static final QName beforeDeleteDocument = new QName("before-delete-document", NAMESPACE); public static final QName afterDeleteDocument = new QName("after-delete-document", NAMESPACE); - private Set events = null; - private Collection collection = null; - private String strQuery = null; - private String urlQuery = null; - private Properties userDefinedVariables = null; + private Set events; + private Collection collection; + private String strQuery; + private String urlQuery; + private Properties userDefinedVariables; /** Namespace prefix associated to trigger */ - private String bindingPrefix = null; + private String bindingPrefix; private XQuery service; - public final static String PREPARE_EXCEPTION_MESSAGE = "Error during trigger prepare"; + public static final String PREPARE_EXCEPTION_MESSAGE = "Error during trigger prepare"; @Override public void configure(final DBBroker broker, final Txn transaction, final Collection parent, final Map> parameters) throws TriggerException { diff --git a/exist-core/src/main/java/org/exist/config/Configuration.java b/exist-core/src/main/java/org/exist/config/Configuration.java index 372b2f52c95..c6abece1f84 100644 --- a/exist-core/src/main/java/org/exist/config/Configuration.java +++ b/exist-core/src/main/java/org/exist/config/Configuration.java @@ -21,15 +21,15 @@ */ package org.exist.config; +import org.exist.security.PermissionDeniedException; +import org.exist.storage.DBBroker; +import org.w3c.dom.Element; + import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; -import org.exist.security.PermissionDeniedException; -import org.exist.storage.DBBroker; -import org.w3c.dom.Element; - /** * Configuration interface provide methods to read settings. * @@ -187,4 +187,4 @@ public interface Configuration { * Free up memory allocated for cache. */ void clearCache(); -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/config/ConfigurationDocumentTrigger.java b/exist-core/src/main/java/org/exist/config/ConfigurationDocumentTrigger.java index e9ac7b9595d..5a69a84caa4 100644 --- a/exist-core/src/main/java/org/exist/config/ConfigurationDocumentTrigger.java +++ b/exist-core/src/main/java/org/exist/config/ConfigurationDocumentTrigger.java @@ -21,8 +21,6 @@ */ package org.exist.config; -import java.util.*; - import com.evolvedbinary.j8fu.tuple.Tuple2; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -46,6 +44,8 @@ import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; +import java.util.*; + import static com.evolvedbinary.j8fu.tuple.Tuple.Tuple; /** @@ -61,11 +61,11 @@ */ public class ConfigurationDocumentTrigger extends DeferrableFilteringTrigger { - private final static String ID_ATTR = "id"; + private static final String ID_ATTR = "id"; protected Logger LOG = LogManager.getLogger(getClass()); - private DBBroker broker = null; + private DBBroker broker; /* Used for holding a pre-allocated id for either an account or group @@ -75,40 +75,37 @@ public class ConfigurationDocumentTrigger extends DeferrableFilteringTrigger { /* Are we creating or updating a document? */ - private boolean createOrUpdate = false; + private boolean createOrUpdate; /* Guard used to prevent processing group elements within account elements as though they were standalone group elements */ - private boolean processingAccount = false; + private boolean processingAccount; /* When processing an account this will be set to true if the account has one or more group elements */ - private boolean accountHasPrimaryGroup = false; + private boolean accountHasPrimaryGroup; @Deprecated public void finish(final int event, final DBBroker broker, final Txn txn, final XmldbURI documentPath, final DocumentImpl document) { Configuration conf; - switch (event) { - case REMOVE_DOCUMENT_EVENT: + if (event == REMOVE_DOCUMENT_EVENT) { conf = Configurator.getConfigurtion(broker.getBrokerPool(), documentPath); if (conf != null) { Configurator.unregister(conf); //XXX: inform object that configuration was deleted } - break; - default: + } else { conf = Configurator.getConfigurtion(broker.getBrokerPool(), documentPath); if (conf != null) { conf.checkForUpdates(document.getDocumentElement()); } - break; } } @@ -240,13 +237,13 @@ public void configure(final DBBroker broker, final Txn transaction, final Collec @Override public void startElement(final String namespaceURI, final String localName, final String qname, final Attributes attributes) throws SAXException { - if(createOrUpdate && namespaceURI != null && namespaceURI.equals(Configuration.NS) && ( (localName.equals(PrincipalType.ACCOUNT.getElementName()) && attributes.getValue("id") != null )|| (localName.equals(PrincipalType.GROUP.getElementName()) && !processingAccount))) { + if(createOrUpdate && namespaceURI != null && Configuration.NS.equals(namespaceURI) && ( (localName.equals(PrincipalType.ACCOUNT.getElementName()) && attributes.getValue("id") != null )|| (localName.equals(PrincipalType.GROUP.getElementName()) && !processingAccount))) { processingAccount = localName.equals(PrincipalType.ACCOUNT.getElementName()); //set group account/group guard defer(true); } // check that account has a group element - if (processingAccount && namespaceURI != null && namespaceURI.equals(Configuration.NS) && localName.equals(PrincipalType.GROUP.getElementName())) { + if (processingAccount && namespaceURI != null && Configuration.NS.equals(namespaceURI) && localName.equals(PrincipalType.GROUP.getElementName())) { accountHasPrimaryGroup = true; } @@ -258,7 +255,7 @@ public void endElement(final String namespaceURI, final String localName, final super.endElement(namespaceURI, localName, qname); - if(createOrUpdate && namespaceURI != null && namespaceURI.equals(Configuration.NS) && (localName.equals(PrincipalType.ACCOUNT.getElementName()) || (localName.equals(PrincipalType.GROUP.getElementName()) && !processingAccount))) { + if(createOrUpdate && namespaceURI != null && Configuration.NS.equals(namespaceURI) && (localName.equals(PrincipalType.ACCOUNT.getElementName()) || (localName.equals(PrincipalType.GROUP.getElementName()) && !processingAccount))) { //we have now captured the entire account or group in our deferred queue, //so we can now process it in it's entirety @@ -288,7 +285,7 @@ private void setAccountPrimaryGroupToNoGroup() throws SAXException { throw new SAXException("Unbalanced SAX Events"); } - if(start.namespaceURI == null || !start.namespaceURI.equals(Configuration.NS) || !start.localName.equals(PrincipalType.ACCOUNT.getElementName())) { + if(start.namespaceURI == null || !Configuration.NS.equals(start.namespaceURI) || !start.localName.equals(PrincipalType.ACCOUNT.getElementName())) { throw new SAXException("First element does not match ending '" + PrincipalType.ACCOUNT.getElementName() + "' element"); } @@ -321,7 +318,7 @@ private void processPrincipal(final PrincipalType principalType) throws SAXExcep throw new SAXException("Unbalanced SAX Events"); } - if(start.namespaceURI == null || !start.namespaceURI.equals(Configuration.NS) || !start.localName.equals(principalType.getElementName())) { + if(start.namespaceURI == null || !Configuration.NS.equals(start.namespaceURI) || !start.localName.equals(principalType.getElementName())) { throw new SAXException("First element does not match ending '" + principalType.getElementName() + "' element"); } @@ -422,7 +419,7 @@ private String findName() { final StringBuilder name = new StringBuilder(); for (final SAXEvent event : deferred) { if (event instanceof Element element) { - if (element.namespaceURI != null && element.namespaceURI.equals(Configuration.NS) && "name".equals(element.localName)) { + if (Configuration.NS.equals(element.namespaceURI) && "name".equals(element.localName)) { inName = !inName; } } @@ -554,14 +551,10 @@ public boolean hasPrincipal(final SecurityManager sm, final int id) { } public void preAllocateId(final SecurityManager sm, final PreAllocatedIdReceiver receiver) throws PermissionDeniedException, EXistException { - switch(this) { - case ACCOUNT: - sm.preAllocateAccountId(receiver); - break; - - case GROUP: - sm.preAllocateGroupId(receiver); - break; + if (this == ConfigurationDocumentTrigger.PrincipalType.ACCOUNT) { + sm.preAllocateAccountId(receiver); + } else if (this == ConfigurationDocumentTrigger.PrincipalType.GROUP) { + sm.preAllocateGroupId(receiver); } } @@ -584,7 +577,7 @@ public static PrincipalType fromElementName(final String elementName) { } private static class PreAllocatedIdReceiver implements SecurityManager.PrincipalIdReceiver { - Integer id = null; + Integer id; @Override public void allocate(final int id) { diff --git a/exist-core/src/main/java/org/exist/config/ConfigurationImpl.java b/exist-core/src/main/java/org/exist/config/ConfigurationImpl.java index c8b8ec1fe96..6f43d224452 100644 --- a/exist-core/src/main/java/org/exist/config/ConfigurationImpl.java +++ b/exist-core/src/main/java/org/exist/config/ConfigurationImpl.java @@ -21,9 +21,6 @@ */ package org.exist.config; -import java.lang.ref.WeakReference; -import java.util.*; - import org.exist.dom.persistent.DocumentImpl; import org.exist.security.PermissionDeniedException; import org.exist.storage.DBBroker; @@ -33,6 +30,8 @@ import org.w3c.dom.NodeList; import javax.xml.XMLConstants; +import java.lang.ref.WeakReference; +import java.util.*; /** * configuration -> element @@ -45,7 +44,7 @@ public class ConfigurationImpl implements Configuration { private Map runtimeProperties = new HashMap<>(); - protected WeakReference configuredObjectReference = null; + protected WeakReference configuredObjectReference; private Element element; @@ -109,12 +108,13 @@ public List getConfigurations(String name) { return list; } - private Map props = null; + private Map props; private void cache() { - - if (props != null) + + if (props != null) { return; + } props = new HashMap<>(); Set names = new HashSet<>(); @@ -125,7 +125,7 @@ private void cache() { if (child.getNodeType() == Node.ELEMENT_NODE) { final String ns = child.getNamespaceURI(); - if (ns != null && NS.equals(ns)) { + if (NS.equals(ns)) { String name = child.getLocalName(); @@ -178,8 +178,10 @@ public String getProperty(String name) { public String getProperty(String name, String default_property) { final String property = getProperty(name); - - if (property == null) return default_property; + + if (property == null) { + return default_property; + } return property; } @@ -214,9 +216,10 @@ public Map getPropertyMap(String name) { } Node attr = attrs.getNamedItem("key"); - - if (attr == null) + + if (attr == null) { continue; + } final String key = attr.getNodeValue(); final String value = el.getTextContent(); @@ -293,7 +296,9 @@ public Boolean getPropertyBoolean(final String name) { public Boolean getPropertyBoolean(String name, boolean defaultValue) { Boolean value = getPropertyBoolean(name); - if(value == null) return defaultValue; + if (value == null) { + return defaultValue; + } return value; } @@ -313,7 +318,7 @@ public Integer getPropertyInteger(final String name, final Integer defaultValue, return defaultValue; } final int result = Integer.parseInt(value); - if ((positive) && (result < 0)) { + if (positive && (result < 0)) { return defaultValue; } return result; @@ -334,7 +339,7 @@ public Long getPropertyLong(final String name, final Long defaultValue, final bo return defaultValue; } final long result = Long.parseLong(value); - if ((positive) && (result < 0)) { + if (positive && (result < 0)) { return defaultValue; } return result; @@ -379,25 +384,27 @@ public Set getProperties() { } //related objects - Map objects = null; + Map objects; @Override public synchronized Object putObject(String name, Object object) { - if (objects == null) + if (objects == null) { objects = new HashMap<>(); + } return objects.put(name, object); } @Override public synchronized Object getObject(String name) { - if (objects == null) + if (objects == null) { return null; + } return objects.get(name); } - private boolean saving = false; + private boolean saving; @Override public void checkForUpdates(Element element) { @@ -464,7 +471,7 @@ public boolean equals(final Object obj) { @Override public boolean equals(final Object obj, final Optional property) { if (obj instanceof ConfigurationImpl conf) { - if (!(getName().equals(conf.getName()))) { + if (!getName().equals(conf.getName())) { return false; } diff --git a/exist-core/src/main/java/org/exist/config/Configurator.java b/exist-core/src/main/java/org/exist/config/Configurator.java index 1d33f7a168e..639b4ebe758 100644 --- a/exist-core/src/main/java/org/exist/config/Configurator.java +++ b/exist-core/src/main/java/org/exist/config/Configurator.java @@ -21,32 +21,8 @@ */ package org.exist.config; -import java.io.*; -import java.lang.annotation.Annotation; -import java.lang.invoke.LambdaMetafactory; -import java.lang.invoke.MethodHandle; -import java.lang.invoke.MethodHandles; -import java.lang.ref.WeakReference; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.ConcurrentSkipListSet; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.xml.XMLConstants; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.parsers.SAXParser; -import javax.xml.parsers.SAXParserFactory; - +import com.evolvedbinary.j8fu.function.ConsumerE; +import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.Database; @@ -56,9 +32,9 @@ import org.exist.collections.Collection; import org.exist.config.annotation.*; import org.exist.config.annotation.ConfigurationFieldSettings.SettingKey; -import org.exist.dom.persistent.DocumentImpl; import org.exist.dom.QName; import org.exist.dom.memtree.SAXAdapter; +import org.exist.dom.persistent.DocumentImpl; import org.exist.security.*; import org.exist.security.SecurityManager; import org.exist.storage.BrokerPool; @@ -69,8 +45,6 @@ import org.exist.util.ExistSAXParserFactory; import org.exist.util.LockException; import org.exist.util.MimeType; -import com.evolvedbinary.j8fu.function.ConsumerE; -import org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream; import org.exist.util.StringInputSource; import org.exist.util.serializer.SAXSerializer; import org.exist.xmldb.FullXmldbURI; @@ -81,6 +55,28 @@ import org.xml.sax.SAXException; import org.xml.sax.XMLReader; +import javax.xml.XMLConstants; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; +import java.io.*; +import java.lang.annotation.Annotation; +import java.lang.invoke.LambdaMetafactory; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.MethodHandles; +import java.lang.ref.WeakReference; +import java.lang.reflect.*; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.ConcurrentSkipListSet; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + import static java.lang.invoke.MethodType.methodType; import static javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING; @@ -93,8 +89,8 @@ */ public class Configurator { - public final static Logger LOG = LogManager.getLogger(Configurator.class); - private final static String EOL = System.getProperty("line.separator", "\n"); + public static final Logger LOG = LogManager.getLogger(Configurator.class); + private static final String EOL = System.getProperty("line.separator", "\n"); protected static final ConcurrentMap hotConfigs = new ConcurrentHashMap<>(); protected static AFields getConfigurationAnnotatedFields(Class clazz) { @@ -332,25 +328,26 @@ private static Configuration configureByCurrent(final Configurable instance, fin //skip contents, they will be processed as structure in the next loop on ConfigurationFieldAsElement value = configuration.getPropertyMap(property); - } else if(List.class == fieldType) { + } else if(List.class != fieldType) { + if (XmldbURI.class == fieldType) { + //use annotation ConfigurationFieldClassMask + value = org.exist.xmldb.XmldbURI.create(configuration.getProperty(property)); + + } else { + Configuration conf = configuration.getConfiguration(property); + if (conf == null) { + conf = configuration; + } + + value = create(conf, instance, fieldType); + if (value == null) { + value = configuration.getProperty(property); + } + } //List //skip, will be processed as structure in the next loop on ConfigurationFieldAsElement //TODO what about simple generic types? - } else if (XmldbURI.class == fieldType) { - //use annotation ConfigurationFieldClassMask - value = org.exist.xmldb.XmldbURI.create(configuration.getProperty(property)); - - } else { - Configuration conf = configuration.getConfiguration(property); - if (conf == null) { - conf = configuration; - } - - value = create(conf, instance, fieldType); - if (value == null) { - value = configuration.getProperty(property); - } } if (value != null && !value.equals(field.get(instance))) { @@ -496,7 +493,7 @@ private static Configuration configureByCurrent(final Configurable instance, fin if(applicableConfs.size() == confs.size()) { LOG.debug("Configuration was removed, will attempt to replace [{}].", obj); if(list.size() > i) { - Configurable old = ((Configurable) list.remove(i)); + Configurable old = (Configurable) list.remove(i); String key = old.getConfiguration().getProperty(referenceBy.orElse(Configuration.ID)); if (key != null) { @@ -1069,7 +1066,7 @@ private static void serializeList(final Configurable instance, //determine the list entries type from its generic type final Type fieldGenericType = field.getGenericType(); if (fieldGenericType instanceof ParameterizedType type) { - final Type genericTypeArgs[] = type.getActualTypeArguments(); + final Type[] genericTypeArgs = type.getActualTypeArguments(); if (genericTypeArgs != null && genericTypeArgs.length == 1) { final Type genericListType = genericTypeArgs[0]; if (genericListType.equals(String.class)) { diff --git a/exist-core/src/main/java/org/exist/config/ReferenceImpl.java b/exist-core/src/main/java/org/exist/config/ReferenceImpl.java index 439b15bdbbd..fafff5df4e6 100644 --- a/exist-core/src/main/java/org/exist/config/ReferenceImpl.java +++ b/exist-core/src/main/java/org/exist/config/ReferenceImpl.java @@ -91,7 +91,9 @@ public boolean isConfigured() { @Override public Configuration getConfiguration() { final O obj = resolve(); - if (obj == null) return null; + if (obj == null) { + return null; + } return obj.getConfiguration(); } diff --git a/exist-core/src/main/java/org/exist/config/mapper/CallMethod.java b/exist-core/src/main/java/org/exist/config/mapper/CallMethod.java index ad70c6bf79e..10021473c26 100644 --- a/exist-core/src/main/java/org/exist/config/mapper/CallMethod.java +++ b/exist-core/src/main/java/org/exist/config/mapper/CallMethod.java @@ -21,23 +21,23 @@ */ package org.exist.config.mapper; -import java.lang.reflect.Method; - import org.exist.config.Configuration; import org.exist.config.Configurator; +import java.lang.reflect.Method; + /** * @author Dmitriy Shabanov */ public class CallMethod { - private Object obj = null; - private Configuration conf = null; - private Object value = null; + private final Object obj; + private final Configuration conf; + private Object value; - private String name = null; - private String attribute = null; - private String element = null; + private String name; + private String attribute; + private String element; public CallMethod(Object obj, Configuration conf) { this.obj = obj; @@ -97,7 +97,9 @@ public void setValue(Object value) { } public Configuration getConfiguration() { - if (element != null) return conf.getConfiguration(element); + if (element != null) { + return conf.getConfiguration(element); + } return conf; } } \ No newline at end of file diff --git a/exist-core/src/main/java/org/exist/config/mapper/Constructor.java b/exist-core/src/main/java/org/exist/config/mapper/Constructor.java index 8bef316ced6..a592e1a2b6f 100644 --- a/exist-core/src/main/java/org/exist/config/mapper/Constructor.java +++ b/exist-core/src/main/java/org/exist/config/mapper/Constructor.java @@ -21,6 +21,14 @@ */ package org.exist.config.mapper; +import org.exist.config.Configurable; +import org.exist.config.Configuration; +import org.exist.config.Configurator; +import org.exist.config.annotation.NewClass; + +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.events.XMLEvent; import java.io.IOException; import java.io.InputStream; import java.lang.invoke.LambdaMetafactory; @@ -29,15 +37,6 @@ import java.util.*; import java.util.function.Supplier; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamReader; -import javax.xml.stream.events.XMLEvent; - -import org.exist.config.Configurable; -import org.exist.config.Configuration; -import org.exist.config.Configurator; -import org.exist.config.annotation.NewClass; - import static java.lang.invoke.MethodType.methodType; /** @@ -45,7 +44,7 @@ */ public class Constructor { - private static Map configurations = new HashMap<>(); + private static final Map configurations = new HashMap<>(); public static Configuration getConfiguration(final Object obj) { return configurations.get(obj); @@ -85,15 +84,14 @@ public static Object load(final NewClass newClazz, while (reader.hasNext()) { eventType = reader.next(); - switch (eventType) { - case XMLEvent.START_ELEMENT: - String localName = reader.getLocalName(); + if (eventType == XMLEvent.START_ELEMENT) { + String localName = reader.getLocalName(); - if ("class".equals(localName)) { - if (!"name".equals(reader.getAttributeLocalName(0))) { - Configurator.LOG.error("class element first attribute must be 'name', skip instance creation."); - return null; - } + if ("class".equals(localName)) { + if (!"name".equals(reader.getAttributeLocalName(0))) { + Configurator.LOG.error("class element first attribute must be 'name', skip instance creation."); + return null; + } final String clazzName = reader.getAttributeValue(0); final Class clazz = Class.forName(clazzName); @@ -115,34 +113,31 @@ public static Object load(final NewClass newClazz, instructions.peek().setValue(newInstance); } - } else if ("callMethod".equals(localName)) { + } else if ("callMethod".equals(localName)) { Configuration _conf_ = conf; if (!instructions.isEmpty()) { _conf_ = instructions.peek().getConfiguration(); } - final CallMethod call = new CallMethod(objs.peek(), _conf_); + final CallMethod call = new CallMethod(objs.peek(), _conf_); - for (int i = 0; i < reader.getAttributeCount(); i++) { - call.set(reader.getAttributeLocalName(i), reader.getAttributeValue(i)); - } + for (int i = 0; i < reader.getAttributeCount(); i++) { + call.set(reader.getAttributeLocalName(i), reader.getAttributeValue(i)); + } instructions.push(call); } - break; - case XMLEvent.END_ELEMENT: - localName = reader.getLocalName(); + } else if (eventType == XMLEvent.END_ELEMENT) { + final String localName = reader.getLocalName(); //System.out.println("END_ELEMENT "+localName); - if ("class".equals(localName)) { - objs.pop(); - } else if ("callMethod".equals(localName)) { - final CallMethod call = instructions.pop(); - call.eval(); - } - - break; + if ("class".equals(localName)) { + objs.pop(); + } else if ("callMethod".equals(localName)) { + final CallMethod call = instructions.pop(); + call.eval(); + } } } diff --git a/exist-core/src/main/java/org/exist/debuggee/DebuggeeFactory.java b/exist-core/src/main/java/org/exist/debuggee/DebuggeeFactory.java index 3ebc01aeb27..df8fdd60ad8 100644 --- a/exist-core/src/main/java/org/exist/debuggee/DebuggeeFactory.java +++ b/exist-core/src/main/java/org/exist/debuggee/DebuggeeFactory.java @@ -23,7 +23,6 @@ import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; - import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.xquery.XPathException; @@ -35,9 +34,9 @@ */ public class DebuggeeFactory { - private final static Logger LOG = LogManager.getLogger(DebuggeeFactory.class); + private static final Logger LOG = LogManager.getLogger(DebuggeeFactory.class); - private static Debuggee instance = null; + private static Debuggee instance; public static Debuggee getInstance() { if (instance == null) { diff --git a/exist-core/src/main/java/org/exist/debuggee/DebuggeeJoint.java b/exist-core/src/main/java/org/exist/debuggee/DebuggeeJoint.java index 1141fb30f6b..507dd1f2248 100644 --- a/exist-core/src/main/java/org/exist/debuggee/DebuggeeJoint.java +++ b/exist-core/src/main/java/org/exist/debuggee/DebuggeeJoint.java @@ -21,9 +21,6 @@ */ package org.exist.debuggee; -import java.util.List; -import java.util.Map; - import org.exist.debugger.model.Breakpoint; import org.exist.dom.QName; import org.exist.xquery.Expression; @@ -31,6 +28,9 @@ import org.exist.xquery.Variable; import org.exist.xquery.XQueryContext; +import java.util.List; +import java.util.Map; + /** * @author Dmitriy Shabanov * diff --git a/exist-core/src/main/java/org/exist/debugger/Debugger.java b/exist-core/src/main/java/org/exist/debugger/Debugger.java index 317ac7d46e1..ad5777456f3 100644 --- a/exist-core/src/main/java/org/exist/debugger/Debugger.java +++ b/exist-core/src/main/java/org/exist/debugger/Debugger.java @@ -21,12 +21,12 @@ */ package org.exist.debugger; -import java.io.IOException; -import java.util.List; - import org.exist.debugger.model.Location; import org.exist.debugger.model.Variable; +import java.io.IOException; +import java.util.List; + /** * @author Dmitriy Shabanov * diff --git a/exist-core/src/main/java/org/exist/debugger/DebuggingSource.java b/exist-core/src/main/java/org/exist/debugger/DebuggingSource.java index 89e1c9ba986..a509830ed10 100644 --- a/exist-core/src/main/java/org/exist/debugger/DebuggingSource.java +++ b/exist-core/src/main/java/org/exist/debugger/DebuggingSource.java @@ -21,13 +21,13 @@ */ package org.exist.debugger; -import java.io.IOException; -import java.util.List; - import org.exist.debugger.model.Breakpoint; import org.exist.debugger.model.Location; import org.exist.debugger.model.Variable; +import java.io.IOException; +import java.util.List; + /** * @author Dmitriy Shabanov * diff --git a/exist-core/src/main/java/org/exist/dom/QName.java b/exist-core/src/main/java/org/exist/dom/QName.java index 6604057f218..dd5c61c5e84 100644 --- a/exist-core/src/main/java/org/exist/dom/QName.java +++ b/exist-core/src/main/java/org/exist/dom/QName.java @@ -21,10 +21,10 @@ */ package org.exist.dom; -import org.exist.xquery.Context; import org.exist.storage.ElementValue; import org.exist.util.XMLNames; import org.exist.xquery.Constants; +import org.exist.xquery.Context; import javax.xml.XMLConstants; import java.util.regex.Matcher; @@ -115,7 +115,7 @@ public String getNamespaceURI() { * @return true if there is a non-default namespace. */ public boolean hasNamespace() { - return !namespaceURI.equals(XMLConstants.NULL_NS_URI); + return !XMLConstants.NULL_NS_URI.equals(namespaceURI); } public String getPrefix() { @@ -237,23 +237,22 @@ public boolean matches(final QName qnOther) { if (this == WildcardQName.instance || qnOther == WildcardQName.instance) { return true; } - if ((localPart.equals(WILDCARD) || qnOther.localPart.equals(WILDCARD)) + if ((WILDCARD.equals(localPart) || WILDCARD.equals(qnOther.localPart)) && namespaceURI.equals(qnOther.namespaceURI)) { return true; } - if ((namespaceURI.equals(WILDCARD) || qnOther.namespaceURI.equals(WILDCARD)) + if ((WILDCARD.equals(namespaceURI) || WILDCARD.equals(qnOther.namespaceURI)) && localPart.equals(qnOther.localPart)) { return true; } - return (namespaceURI.equals(WILDCARD) && localPart.equals(WILDCARD)) - || (qnOther.namespaceURI.equals(WILDCARD) || qnOther.localPart.equals(WILDCARD)); + return (WILDCARD.equals(namespaceURI) && WILDCARD.equals(localPart)) + || (WILDCARD.equals(qnOther.namespaceURI) || WILDCARD.equals(qnOther.localPart)); } @Override public int hashCode() { int result = namespaceURI.hashCode(); - result = 31 * result + localPart.hashCode(); - return result; + return 31 * result + localPart.hashCode(); } public javax.xml.namespace.QName toJavaQName() { @@ -454,8 +453,8 @@ public static QName fromJavaQName(final javax.xml.namespace.QName jQn) { public interface PartialQName { } - public static class WildcardQName extends QName implements PartialQName { - private final static WildcardQName instance = new WildcardQName(); + public static final class WildcardQName extends QName implements PartialQName { + private static final WildcardQName instance = new WildcardQName(); public static WildcardQName getInstance() { return instance; diff --git a/exist-core/src/main/java/org/exist/dom/memtree/AbstractCharacterData.java b/exist-core/src/main/java/org/exist/dom/memtree/AbstractCharacterData.java index cfd202ee0e1..a3eb211581d 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/AbstractCharacterData.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/AbstractCharacterData.java @@ -32,11 +32,11 @@ public abstract class AbstractCharacterData extends NodeImpl implements CharacterData { - public AbstractCharacterData(final DocumentImpl doc, final int nodeNumber) { + protected AbstractCharacterData(final DocumentImpl doc, final int nodeNumber) { this(null, doc, nodeNumber); } - public AbstractCharacterData(final Expression expression, final DocumentImpl doc, final int nodeNumber) { + protected AbstractCharacterData(final Expression expression, final DocumentImpl doc, final int nodeNumber) { super(expression, doc, nodeNumber); } @@ -92,7 +92,7 @@ public void replaceData(final int offset, int count, final String arg) throws DO // 1) create a new array of the correct size for the data final int change = len - count; final int newCharactersLength = existingCharactersLen + change; - final char newCharacters[] = new char[newCharactersLength]; + final char[] newCharacters = new char[newCharactersLength]; // 2) copy everything from document.characters to newCharacters that is before our offset System.arraycopy(document.characters, 0, newCharacters, 0, existingDataOffset + offset); @@ -143,7 +143,7 @@ public void insertData(final int offset, final String arg) throws DOMException { final int existingCharactersLen = document.characters.length; final int extraRequired = len; final int newCharactersLen = existingCharactersLen + extraRequired; - final char newCharacters[] = new char[newCharactersLen]; + final char[] newCharacters = new char[newCharactersLen]; // 2) copy everything from data to newData that is upto the end of our offset + provided offset System.arraycopy(document.characters, 0, newCharacters, 0, existingDataOffset + offset); @@ -181,7 +181,7 @@ public void appendData(final String arg) throws DOMException { final int existingCharactersLen = document.characters.length; final int extraRequired = len; final int newCharactersLen = existingCharactersLen + extraRequired; - final char newCharacters[] = new char[newCharactersLen]; + final char[] newCharacters = new char[newCharactersLen]; // 2) copy everything from data to newData that is upto the end of our offset + len System.arraycopy(document.characters, 0, newCharacters, 0, existingDataOffset + existingDataLen); @@ -226,7 +226,7 @@ public void setData(String data) throws DOMException { final int existingCharactersLen = document.characters.length; final int extraRequired = len - existingDataLen; final int newCharactersLen = existingCharactersLen + extraRequired; - final char newCharacters[] = new char[newCharactersLen]; + final char[] newCharacters = new char[newCharactersLen]; // 2) copy everything from data to newData that is before our offset System.arraycopy(document.characters, 0, newCharacters, 0, existingDataOffset); diff --git a/exist-core/src/main/java/org/exist/dom/memtree/AttrImpl.java b/exist-core/src/main/java/org/exist/dom/memtree/AttrImpl.java index 019a03737f2..8bb3f8e2e86 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/AttrImpl.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/AttrImpl.java @@ -170,7 +170,7 @@ public TypeInfo getSchemaTypeInfo() { @Override public boolean isId() { - return (document.attrType[nodeNumber] == ATTR_ID_TYPE); + return document.attrType[nodeNumber] == ATTR_ID_TYPE; } @Override diff --git a/exist-core/src/main/java/org/exist/dom/memtree/DOMIndexer.java b/exist-core/src/main/java/org/exist/dom/memtree/DOMIndexer.java index 03fe4bfb11d..3293c27c1f3 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/DOMIndexer.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/DOMIndexer.java @@ -27,11 +27,6 @@ import org.exist.Namespaces; import org.exist.collections.CollectionConfiguration; import org.exist.dom.QName; -import org.exist.dom.persistent.AttrImpl; -import org.exist.dom.persistent.CommentImpl; -import org.exist.dom.persistent.ElementImpl; -import org.exist.dom.persistent.ProcessingInstructionImpl; -import org.exist.dom.persistent.TextImpl; import org.exist.dom.persistent.*; import org.exist.numbering.NodeId; import org.exist.storage.DBBroker; @@ -71,12 +66,12 @@ public class DOMIndexer { private final org.exist.dom.persistent.DocumentImpl targetDoc; private final IndexSpec indexSpec; - private final Deque stack = new ArrayDeque<>(); - private StoredNode prevNode = null; + private final Deque stack = new ArrayDeque<>(); + private StoredNode prevNode; - private final TextImpl text = new TextImpl((Expression) null); - private final CommentImpl comment = new CommentImpl((Expression) null); - private final ProcessingInstructionImpl pi = new ProcessingInstructionImpl(null); + private final org.exist.dom.persistent.TextImpl text = new org.exist.dom.persistent.TextImpl((Expression) null); + private final org.exist.dom.persistent.CommentImpl comment = new org.exist.dom.persistent.CommentImpl((Expression) null); + private final org.exist.dom.persistent.ProcessingInstructionImpl pi = new org.exist.dom.persistent.ProcessingInstructionImpl((Expression) null); public DOMIndexer(final DBBroker broker, final Txn transaction, final DocumentImpl doc, final org.exist.dom.persistent.DocumentImpl targetDoc) { @@ -99,7 +94,7 @@ public DOMIndexer(final DBBroker broker, final Txn transaction, final DocumentIm */ public void scan() throws EXistException { //Creates a dummy DOCTYPE - final DocumentTypeImpl dt = new DocumentTypeImpl((doc != null) ? doc.getExpression() : null, "temp", null, ""); + final DocumentTypeImpl dt = new DocumentTypeImpl(doc != null ? doc.getExpression() : null, "temp", null, ""); targetDoc.setDocumentType(dt); } @@ -108,7 +103,7 @@ public void scan() throws EXistException { */ public void store() { //Create a wrapper element as root node - final ElementImpl elem = new ElementImpl(null, ROOT_QNAME, broker.getBrokerPool().getSymbols()); + final org.exist.dom.persistent.ElementImpl elem = new org.exist.dom.persistent.ElementImpl(null, ROOT_QNAME, broker.getBrokerPool().getSymbols()); elem.setNodeId(broker.getBrokerPool().getNodeFactory().createInstance()); elem.setOwnerDocument(targetDoc); elem.setChildCount(doc.getChildCount()); @@ -120,7 +115,7 @@ public void store() { targetDoc.appendChild((NodeHandle) elem); elem.setChildCount(0); // store the document nodes - int top = (doc.size > 1) ? 1 : -1; + int top = doc.size > 1 ? 1 : -1; while(top > 0) { store(top, path); top = doc.getNextSiblingFor(top); @@ -170,7 +165,7 @@ private void startNode(final int nodeNr, final NodePath currentPath) { switch(doc.nodeKind[nodeNr]) { case Node.ELEMENT_NODE: { - final ElementImpl elem = (ElementImpl) NodePool.getInstance().borrowNode(Node.ELEMENT_NODE); + final org.exist.dom.persistent.ElementImpl elem = (org.exist.dom.persistent.ElementImpl) NodePool.getInstance().borrowNode(Node.ELEMENT_NODE); if(stack.isEmpty()) { elem.setNodeId(broker.getBrokerPool().getNodeFactory().createInstance()); initElement(nodeNr, elem); @@ -179,7 +174,7 @@ private void startNode(final int nodeNr, final NodePath currentPath) { targetDoc.appendChild((NodeHandle) elem); elem.setChildCount(0); } else { - final ElementImpl last = stack.peek(); + final org.exist.dom.persistent.ElementImpl last = stack.peek(); initElement(nodeNr, elem); last.appendChildInternal(prevNode, elem); stack.push(elem); @@ -196,7 +191,7 @@ private void startNode(final int nodeNr, final NodePath currentPath) { if((prevNode != null) && ((prevNode.getNodeType() == Node.TEXT_NODE) || (prevNode.getNodeType() == Node.CDATA_SECTION_NODE))) { break; } - final ElementImpl last = stack.peek(); + final org.exist.dom.persistent.ElementImpl last = stack.peek(); text.setData(new String(doc.characters, doc.alpha[nodeNr], doc.alphaLen[nodeNr])); text.setOwnerDocument(targetDoc); last.appendChildInternal(prevNode, text); @@ -206,7 +201,7 @@ private void startNode(final int nodeNr, final NodePath currentPath) { } case Node.CDATA_SECTION_NODE: { - final ElementImpl last = stack.peek(); + final org.exist.dom.persistent.ElementImpl last = stack.peek(); final org.exist.dom.persistent.CDATASectionImpl cdata = (org.exist.dom.persistent.CDATASectionImpl) NodePool.getInstance().borrowNode(Node.CDATA_SECTION_NODE); cdata.setData(doc.characters, doc.alpha[nodeNr], doc.alphaLen[nodeNr]); cdata.setOwnerDocument(targetDoc); @@ -224,7 +219,7 @@ private void startNode(final int nodeNr, final NodePath currentPath) { targetDoc.appendChild((NodeHandle) comment); broker.storeNode(transaction, comment, null, indexSpec); } else { - final ElementImpl last = stack.peek(); + final org.exist.dom.persistent.ElementImpl last = stack.peek(); last.appendChildInternal(prevNode, comment); broker.storeNode(transaction, comment, null, indexSpec); setPrevious(comment); @@ -241,7 +236,7 @@ private void startNode(final int nodeNr, final NodePath currentPath) { pi.setNodeId(NodeId.DOCUMENT_NODE); targetDoc.appendChild((NodeHandle) pi); } else { - final ElementImpl last = stack.peek(); + final org.exist.dom.persistent.ElementImpl last = stack.peek(); last.appendChildInternal(prevNode, pi); setPrevious(pi); } @@ -261,7 +256,7 @@ private void startNode(final int nodeNr, final NodePath currentPath) { * @param nodeNr * @param elem */ - private void initElement(final int nodeNr, final ElementImpl elem) { + private void initElement(final int nodeNr, final org.exist.dom.persistent.ElementImpl elem) { final short attribs = (short) doc.getAttributesCountFor(nodeNr); elem.setOwnerDocument(targetDoc); elem.setAttributes(attribs); @@ -304,12 +299,12 @@ private Map getNamespaces(final int nodeNr) { * @param path DOCUMENT ME! * @throws DOMException */ - private void storeAttributes(final int nodeNr, final ElementImpl elem, final NodePath path) throws DOMException { + private void storeAttributes(final int nodeNr, final org.exist.dom.persistent.ElementImpl elem, final NodePath path) throws DOMException { int attr = doc.alpha[nodeNr]; if(attr > -1) { while((attr < doc.nextAttr) && (doc.attrParent[attr] == nodeNr)) { final QName qn = doc.attrName[attr]; - final AttrImpl attrib = (AttrImpl) NodePool.getInstance().borrowNode(Node.ATTRIBUTE_NODE); + final org.exist.dom.persistent.AttrImpl attrib = (org.exist.dom.persistent.AttrImpl) NodePool.getInstance().borrowNode(Node.ATTRIBUTE_NODE); attrib.setNodeName(qn, broker.getBrokerPool().getSymbols()); attrib.setValue(doc.attrValue[attr]); attrib.setOwnerDocument(targetDoc); @@ -329,7 +324,7 @@ private void storeAttributes(final int nodeNr, final ElementImpl elem, final Nod */ private void endNode(final int nodeNr, final NodePath currentPath) { if(doc.nodeKind[nodeNr] == Node.ELEMENT_NODE) { - final ElementImpl last = stack.pop(); + final org.exist.dom.persistent.ElementImpl last = stack.pop(); broker.endElement(last, currentPath, null); currentPath.removeLastComponent(); setPrevious(last); diff --git a/exist-core/src/main/java/org/exist/dom/memtree/DocumentBuilderReceiver.java b/exist-core/src/main/java/org/exist/dom/memtree/DocumentBuilderReceiver.java index 38884a1fa50..88357dbac80 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/DocumentBuilderReceiver.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/DocumentBuilderReceiver.java @@ -48,11 +48,11 @@ */ public class DocumentBuilderReceiver implements ContentHandler, LexicalHandler, Receiver { - private MemTreeBuilder builder = null; + private MemTreeBuilder builder; private final boolean explicitNSDecl; - private Map namespaces = null; - private boolean checkNS = false; + private Map namespaces; + private boolean checkNS; private boolean suppressWhitespace = true; @@ -322,4 +322,4 @@ private String generatePrefix(final XQueryContext context, String prefix) { } return prefix; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/dom/memtree/DocumentImpl.java b/exist-core/src/main/java/org/exist/dom/memtree/DocumentImpl.java index ea7685a17c5..9858dcfe261 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/DocumentImpl.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/DocumentImpl.java @@ -99,7 +99,7 @@ public class DocumentImpl extends NodeImpl implements Document { private static final int REF_SIZE = 8; // holds the node type of a node - protected short[] nodeKind = null; + protected short[] nodeKind; // the tree level of a node protected short[] treeLevel; @@ -115,8 +115,8 @@ public class DocumentImpl extends NodeImpl implements Document { //alphanumeric content protected int[] alpha; protected int[] alphaLen; - protected char[] characters = null; - protected int nextChar = 0; + protected char[] characters; + protected int nextChar; // attributes protected QName[] attrName; @@ -124,33 +124,33 @@ public class DocumentImpl extends NodeImpl implements Document { protected NodeId[] attrNodeId; protected int[] attrParent; protected String[] attrValue; - protected int nextAttr = 0; + protected int nextAttr; // namespaces - protected int[] namespaceParent = null; - protected QName[] namespaceCode = null; - protected int nextNamespace = 0; + protected int[] namespaceParent; + protected QName[] namespaceCode; + protected int nextNamespace; // the current number of nodes in the doc protected int size = 1; protected int documentRootNode = -1; - protected String documentURI = null; + protected String documentURI; // reference nodes (link to an external, persistent document fragment) - protected NodeProxy[] references = null; - protected int nextReferenceIdx = 0; + protected NodeProxy[] references; + protected int nextReferenceIdx; // end reference nodes protected XQueryContext context; protected final boolean explicitlyCreated; protected final long docId; - private Database db = null; + private Database db; protected NamePool namePool; - boolean replaceAttribute = false; + boolean replaceAttribute; public DocumentImpl(final XQueryContext context, final boolean explicitlyCreated) { @@ -234,7 +234,7 @@ public int addNode(final short kind, final short level, final QName qname) { nodeName[size] = qname != null ? namePool.getSharedName(qname) : null; alpha[size] = -1; // undefined next[size] = -1; - return (size++); + return size++; } public void addChars(final int nodeNum, final char[] ch, final int start, final int len) { @@ -262,9 +262,9 @@ public void addChars(final int nodeNum, final CharSequence s) { if(nodeKind == null) { init(); } - int len = (s == null) ? 0 : s.length(); + int len = s == null ? 0 : s.length(); if(characters == null) { - characters = new char[(len > CHAR_BUF_SIZE) ? len : CHAR_BUF_SIZE]; + characters = new char[len > CHAR_BUF_SIZE ? len : CHAR_BUF_SIZE]; } else if((nextChar + len) >= characters.length) { int newLen = (characters.length * 3) / 2; if(newLen < (nextChar + len)) { @@ -283,7 +283,7 @@ public void addChars(final int nodeNum, final CharSequence s) { public void appendChars(final int nodeNum, final char[] ch, final int start, final int len) { if(characters == null) { - characters = new char[(len > CHAR_BUF_SIZE) ? len : CHAR_BUF_SIZE]; + characters = new char[len > CHAR_BUF_SIZE ? len : CHAR_BUF_SIZE]; } else if((nextChar + len) >= characters.length) { int newLen = (characters.length * 3) / 2; if(newLen < (nextChar + len)) { @@ -301,7 +301,7 @@ public void appendChars(final int nodeNum, final char[] ch, final int start, fin public void appendChars(final int nodeNum, final CharSequence s) { final int len = s.length(); if(characters == null) { - characters = new char[(len > CHAR_BUF_SIZE) ? len : CHAR_BUF_SIZE]; + characters = new char[len > CHAR_BUF_SIZE ? len : CHAR_BUF_SIZE]; } else if((nextChar + len) >= characters.length) { int newLen = (characters.length * 3) / 2; if(newLen < (nextChar + len)) { @@ -374,7 +374,7 @@ public int addAttribute(final int nodeNum, final QName qname, final String value if(alpha[nodeNum] < 0) { alpha[nodeNum] = nextAttr; } - return (nextAttr++); + return nextAttr++; } public int addNamespace(final int nodeNum, final QName qname) { @@ -519,7 +519,7 @@ public NodeImpl getNode(final int nodeNum) throws DOMException { if(nodeNum >= size) { throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "node not found"); } - final NodeImpl node = switch (nodeKind[nodeNum]) { + return switch (nodeKind[nodeNum]) { case Node.ELEMENT_NODE -> new ElementImpl(getExpression(), this, nodeNum); case Node.TEXT_NODE -> new TextImpl(getExpression(), this, nodeNum); case Node.COMMENT_NODE -> new CommentImpl(getExpression(), this, nodeNum); @@ -528,7 +528,6 @@ public NodeImpl getNode(final int nodeNum) throws DOMException { case NodeImpl.REFERENCE_NODE -> new ReferenceNode(getExpression(), this, nodeNum); default -> throw new DOMException(DOMException.NOT_FOUND_ERR, "node not found"); }; - return node; } public NodeImpl getLastAttr() { @@ -1003,7 +1002,7 @@ public EntityReference createEntityReference(final String name) throws DOMExcept @Override public NodeList getElementsByTagName(final String tagname) { - if(tagname != null && tagname.equals(QName.WILDCARD)) { + if(QName.WILDCARD.equals(tagname)) { return getElementsByTagName(new QName.WildcardLocalPartQName(XMLConstants.DEFAULT_NS_PREFIX)); } else { final QName qname; @@ -1023,8 +1022,8 @@ public NodeList getElementsByTagName(final String tagname) { @Override public NodeList getElementsByTagNameNS(final String namespaceURI, final String localName) { - final boolean wildcardNS = namespaceURI != null && namespaceURI.equals(QName.WILDCARD); - final boolean wildcardLocalPart = localName != null && localName.equals(QName.WILDCARD); + final boolean wildcardNS = QName.WILDCARD.equals(namespaceURI); + final boolean wildcardLocalPart = QName.WILDCARD.equals(localName); if(wildcardNS && wildcardLocalPart) { return getElementsByTagName(QName.WildcardQName.getInstance()); @@ -1222,7 +1221,7 @@ public DocumentImpl expandRefs(final NodeImpl rootNode) throws DOMException { final DocumentBuilderReceiver receiver = new DocumentBuilderReceiver(getExpression(), builder); try { builder.startDocument(); - NodeImpl node = (rootNode == null) ? (NodeImpl) getFirstChild() : rootNode; + NodeImpl node = rootNode == null ? (NodeImpl) getFirstChild() : rootNode; while(node != null) { copyTo(node, receiver, true); node = (NodeImpl) node.getNextSibling(); @@ -1449,7 +1448,7 @@ public org.exist.dom.persistent.DocumentImpl makePersistent() throws XPathExcept // this is DOM specific public int getChildCount() { int count = 0; - int top = (size > 1) ? 1 : -1; + int top = size > 1 ? 1 : -1; while(top > 0) { ++count; top = getNextSiblingFor(top); diff --git a/exist-core/src/main/java/org/exist/dom/memtree/ElementImpl.java b/exist-core/src/main/java/org/exist/dom/memtree/ElementImpl.java index 02100e4261a..b19e7c83c86 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/ElementImpl.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/ElementImpl.java @@ -36,8 +36,8 @@ import org.exist.xquery.value.ValueSequence; import org.w3c.dom.*; -import javax.xml.XMLConstants; import javax.annotation.Nonnull; +import javax.xml.XMLConstants; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -213,7 +213,7 @@ public NamedNodeMap getAttributes() { // add namespace declarations attached to this element int ns = document.alphaLen[nodeNumber]; if(ns < 0) { - return (map); + return map; } while(ns < document.nextNamespace && document.namespaceParent[ns] == nodeNumber) { final NamespaceNode node = new NamespaceNode(getExpression(), document, ns); @@ -354,7 +354,7 @@ public void selectDescendants(final boolean includeSelf, final NodeTest test, fi @Override @Nonnull public NodeList getElementsByTagName(final String name) { - if(name != null && name.equals(QName.WILDCARD)) { + if(QName.WILDCARD.equals(name)) { return getElementsByTagName(new QName.WildcardLocalPartQName(XMLConstants.DEFAULT_NS_PREFIX)); } else { final QName qname; @@ -374,8 +374,8 @@ public NodeList getElementsByTagName(final String name) { @Override @Nonnull public NodeList getElementsByTagNameNS(final String namespaceURI, final String localName) { - final boolean wildcardNS = namespaceURI != null && namespaceURI.equals(QName.WILDCARD); - final boolean wildcardLocalPart = localName != null && localName.equals(QName.WILDCARD); + final boolean wildcardNS = QName.WILDCARD.equals(namespaceURI); + final boolean wildcardLocalPart = QName.WILDCARD.equals(localName); if(wildcardNS && wildcardLocalPart) { return getElementsByTagName(QName.WildcardQName.getInstance()); @@ -452,7 +452,7 @@ public Attr getAttributeNodeNS(final String namespaceURI, final String localName while((attr < document.nextAttr) && (document.attrParent[attr] == nodeNumber)) { final QName name = document.attrName[attr]; if(name.getLocalPart().equals(localName) && name.getNamespaceURI().equals(namespaceURI)) { - return (new AttrImpl(getExpression(), document, attr)); + return new AttrImpl(getExpression(), document, attr); } ++attr; } @@ -463,7 +463,7 @@ public Attr getAttributeNodeNS(final String namespaceURI, final String localName while((ns < document.nextNamespace) && (document.namespaceParent[ns] == nodeNumber)) { final QName nsQName = document.namespaceCode[ns]; if(nsQName.getLocalPart().equals(localName)) { - return (new NamespaceNode(getExpression(), document, ns)); + return new NamespaceNode(getExpression(), document, ns); } ++ns; } @@ -641,9 +641,7 @@ private XmldbURI calculateBaseURI() { } else { if(nodeBaseURI == null) { return XmldbURI.create(getOwnerDocument().getBaseURI(), false); - } else if(nodeNumber == 1) { - //nothing to do - } else { + } else if(nodeNumber != 1) { final String docBaseURI = getOwnerDocument().getBaseURI(); if(docBaseURI.endsWith("/")) { baseURI = XmldbURI.create(getOwnerDocument().getBaseURI(), false); @@ -653,6 +651,7 @@ private XmldbURI calculateBaseURI() { baseURI = baseURI.removeLastSegment(); baseURI.append(baseURI); } + //nothing to do } } return baseURI; diff --git a/exist-core/src/main/java/org/exist/dom/memtree/InMemoryXMLStreamReader.java b/exist-core/src/main/java/org/exist/dom/memtree/InMemoryXMLStreamReader.java index c02764c5cab..3d2aae87041 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/InMemoryXMLStreamReader.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/InMemoryXMLStreamReader.java @@ -60,7 +60,7 @@ public InMemoryXMLStreamReader(final DocumentImpl doc, final NodeImpl node) { @Override public Object getProperty(final String name) throws IllegalArgumentException { - if(name.equals(PROPERTY_NODE_ID)) { + if(PROPERTY_NODE_ID.equals(name)) { if(currentNode < 0 || currentNode >= doc.size) { return null; diff --git a/exist-core/src/main/java/org/exist/dom/memtree/MemTreeBuilder.java b/exist-core/src/main/java/org/exist/dom/memtree/MemTreeBuilder.java index bf0424dc5d8..14936fe6bd5 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/MemTreeBuilder.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/MemTreeBuilder.java @@ -148,7 +148,7 @@ public int startElement(final String namespaceURI, String localName, final Strin } if (prefix == null) { - prefix = (prefixIdx != Constants.STRING_NOT_FOUND) ? qname.substring(0, prefixIdx) : null; + prefix = prefixIdx != Constants.STRING_NOT_FOUND ? qname.substring(0, prefixIdx) : null; } if (localName.isEmpty()) { @@ -181,10 +181,10 @@ public int startElement(final QName qname, final Attributes attributes) { final String attrQName = attributes.getQName(i); // skip xmlns-attributes - if(!(attrQName.startsWith(XMLConstants.XMLNS_ATTRIBUTE))) { + if(!attrQName.startsWith(XMLConstants.XMLNS_ATTRIBUTE)) { final int p = attrQName.indexOf(':'); final String attrNS = attributes.getURI(i); - final String attrPrefix = (p != Constants.STRING_NOT_FOUND) ? attrQName.substring(0, p) : null; + final String attrPrefix = p != Constants.STRING_NOT_FOUND ? attrQName.substring(0, p) : null; String attrLocalName = attributes.getLocalName(i); if (p == Constants.STRING_NOT_FOUND && attrLocalName.isEmpty()) { @@ -218,12 +218,12 @@ public int startElement(final QName qname, final Attributes attributes) { private int getAttribType(final QName qname, final String type) { - if(qname.equals(Namespaces.XML_ID_QNAME) || type.equals(Indexer.ATTR_ID_TYPE)) { + if(qname.equals(Namespaces.XML_ID_QNAME) || Indexer.ATTR_ID_TYPE.equals(type)) { // an xml:id attribute. return AttrImpl.ATTR_ID_TYPE; - } else if(type.equals(Indexer.ATTR_IDREF_TYPE)) { + } else if(Indexer.ATTR_IDREF_TYPE.equals(type)) { return AttrImpl.ATTR_IDREF_TYPE; - } else if(type.equals(Indexer.ATTR_IDREFS_TYPE)) { + } else if(Indexer.ATTR_IDREFS_TYPE.equals(type)) { return AttrImpl.ATTR_IDREFS_TYPE; } else { return AttrImpl.ATTR_CDATA_TYPE; @@ -285,12 +285,10 @@ public int addAttribute(final QName qname, final String value) { //} else { //lastNode = doc.addAttribute(lastNode, qname, value); //} - final int nodeNr = doc.addAttribute(lastNode, qname, value, getAttribType(qname, Indexer.ATTR_CDATA_TYPE)); - //TODO : //1) call linkNode(nodeNr); ? //2) is there a relationship between lastNode and nodeNr ? - return nodeNr; + return doc.addAttribute(lastNode, qname, value, getAttribType(qname, Indexer.ATTR_CDATA_TYPE)); } @@ -438,7 +436,7 @@ public int cdataSection(final CharSequence data) { public int processingInstruction(final String target, final String data) { final QName qname = new QName(target, null, null); final int nodeNr = doc.addNode(Node.PROCESSING_INSTRUCTION_NODE, level, qname); - doc.addChars(nodeNr, (data == null) ? "" : data); + doc.addChars(nodeNr, data == null ? "" : data); linkNode(nodeNr); return nodeNr; } @@ -463,9 +461,9 @@ public int namespaceNode(final QName qname, final boolean checkNS) { if(doc.nodeName != null) { final QName elemQN = doc.nodeName[lastNode]; if(elemQN != null) { - final String elemPrefix = (elemQN.getPrefix() == null) ? XMLConstants.DEFAULT_NS_PREFIX : elemQN.getPrefix(); - final String elemNs = (elemQN.getNamespaceURI() == null) ? XMLConstants.NULL_NS_URI : elemQN.getNamespaceURI(); - final String qnPrefix = (qname.getPrefix() == null) ? XMLConstants.DEFAULT_NS_PREFIX : qname.getPrefix(); + final String elemPrefix = elemQN.getPrefix() == null ? XMLConstants.DEFAULT_NS_PREFIX : elemQN.getPrefix(); + final String elemNs = elemQN.getNamespaceURI() == null ? XMLConstants.NULL_NS_URI : elemQN.getNamespaceURI(); + final String qnPrefix = qname.getPrefix() == null ? XMLConstants.DEFAULT_NS_PREFIX : qname.getPrefix(); if (checkNS && XMLConstants.DEFAULT_NS_PREFIX.equals(elemPrefix) && XMLConstants.NULL_NS_URI.equals(elemNs) @@ -482,7 +480,7 @@ public int namespaceNode(final QName qname, final boolean checkNS) { } } } - return (addNode ? doc.addNamespace(lastNode, qname) : -1); + return addNode ? doc.addNamespace(lastNode, qname) : -1; } diff --git a/exist-core/src/main/java/org/exist/dom/memtree/NamespaceNode.java b/exist-core/src/main/java/org/exist/dom/memtree/NamespaceNode.java index 55402f9a0eb..6d6341c4f64 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/NamespaceNode.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/NamespaceNode.java @@ -95,7 +95,7 @@ public String getNodeValue() throws DOMException { @Override public Element getOwnerElement() { - return ((Element) document.getNode(document.namespaceParent[nodeNumber])); + return (Element) document.getNode(document.namespaceParent[nodeNumber]); } @Override diff --git a/exist-core/src/main/java/org/exist/dom/memtree/NodeImpl.java b/exist-core/src/main/java/org/exist/dom/memtree/NodeImpl.java index 92463ba41e5..7e953f46b27 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/NodeImpl.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/NodeImpl.java @@ -57,11 +57,11 @@ public abstract class NodeImpl> implements INode { final String nsUri = getQName().getNamespaceURI(); - if (nsUri.equals(XMLConstants.NULL_NS_URI)) { + if (XMLConstants.NULL_NS_URI.equals(nsUri)) { yield null; } else { yield nsUri; @@ -164,16 +164,15 @@ public final String getPrefix() { @Override public void setPrefix(final String prefix) throws DOMException { if(prefix == null || getNodeType() == Node.DOCUMENT_NODE) { - return; } else if("1.0".equals(getOwnerDocument().getXmlVersion()) && !XMLChar.isValidNCName(prefix)) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, "Prefix '" + prefix + "' in XML 1.0 contains invalid characters"); } else if("1.1".equals(getOwnerDocument().getXmlVersion()) && !XML11Char.isXML11ValidNCName(prefix)) { throw new DOMException(DOMException.INVALID_CHARACTER_ERR, "Prefix '" + prefix + "' in XML 1.1 contains invalid characters"); } else if(getNamespaceURI() == null) { throw new DOMException(DOMException.NAMESPACE_ERR, "Cannot set prefix when namespace is null"); - } else if(prefix.equals(XMLConstants.XML_NS_PREFIX) && !getNamespaceURI().equals(XMLConstants.XML_NS_URI)) { + } else if(XMLConstants.XML_NS_PREFIX.equals(prefix) && !XMLConstants.XML_NS_URI.equals(getNamespaceURI())) { throw new DOMException(DOMException.NAMESPACE_ERR, "Prefix '" + XMLConstants.XML_NS_PREFIX + "' is invalid for namespace '" + getNamespaceURI() + "'"); - } else if(getNodeType() == Node.ATTRIBUTE_NODE && prefix.equals(XMLConstants.XMLNS_ATTRIBUTE) && !getNamespaceURI().equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) { + } else if(getNodeType() == Node.ATTRIBUTE_NODE && XMLConstants.XMLNS_ATTRIBUTE.equals(prefix) && !XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(getNamespaceURI())) { throw new DOMException(DOMException.NAMESPACE_ERR, "Prefix '" + XMLConstants.XMLNS_ATTRIBUTE + "' is invalid for namespace '" + getNamespaceURI() + "'"); } else if(getNodeType() == Node.ELEMENT_NODE || getNodeType() == Node.ATTRIBUTE_NODE) { final QName qname = getQName(); @@ -490,7 +489,7 @@ private String getStringValueSlow() { } ++next; } - return ((buf == null) ? "" : buf.toString()); + return buf == null ? "" : buf.toString(); } @Override @@ -923,7 +922,7 @@ protected DOMException unsupported() { return new DOMException(DOMException.NOT_SUPPORTED_ERR, "not implemented on class: " + getClass().getName()); } - private final static class SingleNodeIterator implements SequenceIterator { + private static final class SingleNodeIterator implements SequenceIterator { private NodeImpl node; public SingleNodeIterator(final NodeImpl node) { diff --git a/exist-core/src/main/java/org/exist/dom/memtree/ProcessingInstructionImpl.java b/exist-core/src/main/java/org/exist/dom/memtree/ProcessingInstructionImpl.java index ad2c3a79ecd..b5bc62c2419 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/ProcessingInstructionImpl.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/ProcessingInstructionImpl.java @@ -99,7 +99,7 @@ public String getBaseURI() { test = document.getParentNodeFor(parent); if(document.nodeKind[test] == Node.DOCUMENT_NODE) { - return (baseURI); + return baseURI; } else { parent = test; } @@ -108,7 +108,7 @@ public String getBaseURI() { if(baseURI.isEmpty()) { baseURI = getOwnerDocument().getBaseURI(); } - return (baseURI); + return baseURI; } @Override diff --git a/exist-core/src/main/java/org/exist/dom/memtree/SAXAdapter.java b/exist-core/src/main/java/org/exist/dom/memtree/SAXAdapter.java index 1f455d621fb..4db9f46aff9 100644 --- a/exist-core/src/main/java/org/exist/dom/memtree/SAXAdapter.java +++ b/exist-core/src/main/java/org/exist/dom/memtree/SAXAdapter.java @@ -41,9 +41,9 @@ */ public class SAXAdapter implements ContentHandler, LexicalHandler { private MemTreeBuilder builder; - private Map namespaces = null; - private boolean replaceAttributeFlag = false; - private boolean cdataFlag = false; + private Map namespaces; + private boolean replaceAttributeFlag; + private boolean cdataFlag; private final StringBuilder cdataBuf = new StringBuilder(); public SAXAdapter() { diff --git a/exist-core/src/main/java/org/exist/dom/persistent/AVLTreeNodeSet.java b/exist-core/src/main/java/org/exist/dom/persistent/AVLTreeNodeSet.java index afd9c393efa..219c7921f35 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/AVLTreeNodeSet.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/AVLTreeNodeSet.java @@ -33,8 +33,8 @@ public class AVLTreeNodeSet extends AbstractNodeSet { private Node root; - private int size = 0; - private int state = 0; + private int size; + private int state; @Override public SequenceIterator iterate() { @@ -183,10 +183,9 @@ private void balance(final Node node) { } if(currentParent.leftHeight() - currentParent.rightHeight() == 2) { - Node nodeA = currentParent, - nodeB = nodeA.getLeftChild(), - //nodeC = nodeB.getLeftChild(), - nodeD = nodeB.getRightChild(); + Node nodeA = currentParent; + Node nodeB = nodeA.getLeftChild(); + Node nodeD = nodeB.getRightChild(); if(nodeB.leftHeight() > nodeB.rightHeight()) { // right rotation for Case 2 nodeA.addLeftChild(nodeD); @@ -455,7 +454,7 @@ public boolean isCacheable() { } private void setHasChanged() { - state = (state == Integer.MAX_VALUE ? 0 : state + 1); + state = state == Integer.MAX_VALUE ? 0 : state + 1; } private static class InorderTraversal implements NodeSetIterator, SequenceIterator { @@ -563,11 +562,11 @@ public NodeProxy getData() { } public boolean hasLeftChild() { - return (leftChild != null); + return leftChild != null; } public boolean hasRightChild() { - return (rightChild != null); + return rightChild != null; } public Node getLeftChild() { @@ -579,7 +578,7 @@ public Node getRightChild() { } public boolean balanced() { - return (Math.abs(leftHeight() - rightHeight()) <= 1); + return Math.abs(leftHeight() - rightHeight()) <= 1; } public Node addLeft(final NodeProxy data) { @@ -640,23 +639,23 @@ public void setHeight() { } public boolean isLeftChild() { - return (this == parent.leftChild); + return this == parent.leftChild; } public boolean isRightChild() { - return (this == parent.rightChild); + return this == parent.rightChild; } public int leftHeight() { if(hasLeftChild()) { - return (1 + leftChild.height); + return 1 + leftChild.height; } return 0; } public int rightHeight() { if(hasRightChild()) { - return (1 + rightChild.height); + return 1 + rightChild.height; } return 0; } diff --git a/exist-core/src/main/java/org/exist/dom/persistent/AbstractArrayNodeSet.java b/exist-core/src/main/java/org/exist/dom/persistent/AbstractArrayNodeSet.java index 634edb1c706..7927654c65f 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/AbstractArrayNodeSet.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/AbstractArrayNodeSet.java @@ -36,14 +36,14 @@ public abstract class AbstractArrayNodeSet extends AbstractNodeSet implements Do protected static final int INITIAL_SIZE = 64; - protected int size = 0; + protected int size; - protected boolean isSorted = false; - protected boolean hasOne = false; + protected boolean isSorted; + protected boolean hasOne; - protected int state = 0; + protected int state; - private NodeProxy lastAdded = null; + private NodeProxy lastAdded; // used to keep track of the type of added items. protected int itemType = Type.ANY_TYPE; @@ -110,7 +110,6 @@ public void add(final NodeProxy proxy, final int sizeHint) { @Override public void addAll(final NodeSet other) { if(other.isEmpty()) { - return; } else if(other.hasOne()) { add((NodeProxy) other.itemAt(0)); } else { @@ -143,7 +142,7 @@ private void checkItemType(final int type) { } private void setHasChanged() { - this.state = (state == Integer.MAX_VALUE ? 0 : state + 1); + this.state = state == Integer.MAX_VALUE ? 0 : state + 1; } @Override diff --git a/exist-core/src/main/java/org/exist/dom/persistent/AbstractCharacterData.java b/exist-core/src/main/java/org/exist/dom/persistent/AbstractCharacterData.java index b23d6f2c8d9..80a44a19855 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/AbstractCharacterData.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/AbstractCharacterData.java @@ -32,7 +32,7 @@ public abstract class AbstractCharacterData extends StoredNode implements CharacterData { - protected XMLString cdata = null; + protected XMLString cdata; protected AbstractCharacterData(final short nodeType) { this(null, nodeType); @@ -264,4 +264,4 @@ public static int getStringLength(final NodeId nodeId, final Value value) { final int nodeIdLen = nodeId.size(); return value.getLength() - 3 - nodeIdLen; } -} \ No newline at end of file +} diff --git a/exist-core/src/main/java/org/exist/dom/persistent/AbstractNodeSet.java b/exist-core/src/main/java/org/exist/dom/persistent/AbstractNodeSet.java index 250070ecfcd..e1e1aeea84b 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/AbstractNodeSet.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/AbstractNodeSet.java @@ -50,8 +50,8 @@ public abstract class AbstractNodeSet extends AbstractSequence implements NodeSe // been defined on the nodes in this set. protected int indexType = Type.ANY_TYPE; - private boolean isCached = false; - private boolean processInReverseOrder = false; + private boolean isCached; + private boolean processInReverseOrder; private boolean trackMatches = true; protected AbstractNodeSet() { @@ -670,7 +670,7 @@ public String toString() { private final class CollectionIterator implements Iterator { - private Collection nextCollection = null; + private Collection nextCollection; private final NodeSetIterator nodeIterator = iterator(); private CollectionIterator() { diff --git a/exist-core/src/main/java/org/exist/dom/persistent/AttrImpl.java b/exist-core/src/main/java/org/exist/dom/persistent/AttrImpl.java index 2d8ac03955d..d547454db8e 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/AttrImpl.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/AttrImpl.java @@ -54,7 +54,7 @@ public class AttrImpl extends NamedNode implements Attr { private int attributeType = DEFAULT_ATTRIBUTE_TYPE; private int indexType = RangeIndexSpec.NO_INDEX; - private XMLString value = null; + private XMLString value; public AttrImpl() { this((Expression) null); diff --git a/exist-core/src/main/java/org/exist/dom/persistent/BinaryDocument.java b/exist-core/src/main/java/org/exist/dom/persistent/BinaryDocument.java index f9c12b36661..5b6a47e04b7 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/BinaryDocument.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/BinaryDocument.java @@ -45,7 +45,7 @@ */ public class BinaryDocument extends DocumentImpl { private BlobId blobId; - private long realSize = 0L; + private long realSize; /** * Creates a new persistent binary Document instance. diff --git a/exist-core/src/main/java/org/exist/dom/persistent/ContextItem.java b/exist-core/src/main/java/org/exist/dom/persistent/ContextItem.java index 778ff532979..f106d083796 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/ContextItem.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/ContextItem.java @@ -48,7 +48,7 @@ public int getContextId() { } public boolean hasNextDirect() { - return (nextDirect != null); + return nextDirect != null; } public ContextItem getNextDirect() { diff --git a/exist-core/src/main/java/org/exist/dom/persistent/DefaultDocumentSet.java b/exist-core/src/main/java/org/exist/dom/persistent/DefaultDocumentSet.java index 22eae794a83..35100861e4f 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/DefaultDocumentSet.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/DefaultDocumentSet.java @@ -48,7 +48,7 @@ public class DefaultDocumentSet implements MutableDocumentSet { private static final int DEFAULT_SIZE = 29; - private static final float DEFAULT_GROWTH = 1.75f; + private static final float DEFAULT_GROWTH = 1.75F; private final BitSet docIds = new BitSet(); private final Map docs; diff --git a/exist-core/src/main/java/org/exist/dom/persistent/DocumentImpl.java b/exist-core/src/main/java/org/exist/dom/persistent/DocumentImpl.java index 1529b92e744..a37da5518d7 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/DocumentImpl.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/DocumentImpl.java @@ -31,8 +31,8 @@ import org.exist.dom.QName.IllegalQNameException; import org.exist.dom.memtree.DocumentFragmentImpl; import org.exist.numbering.NodeId; -import org.exist.security.SecurityManager; import org.exist.security.*; +import org.exist.security.SecurityManager; import org.exist.storage.*; import org.exist.storage.io.VariableByteInput; import org.exist.storage.io.VariableByteOutputStream; @@ -91,13 +91,13 @@ public class DocumentImpl extends NodeImpl implements Resource, Do /** * number of child nodes */ - private int children = 0; - private long[] childAddress = null; + private int children; + private long[] childAddress; /** * the collection this document belongs to */ - private transient Collection collection = null; + private transient Collection collection; /** * the document's id @@ -107,16 +107,16 @@ public class DocumentImpl extends NodeImpl implements Resource, Do /** * Just the document's file name */ - private XmldbURI fileURI = null; + private XmldbURI fileURI; /** * Lazily computed. Needs to be recomputed if {@link #fileURI} or {@link #collection} change */ - private XmldbURI uri = null; + private XmldbURI uri; - private Permission permissions = null; + private Permission permissions; - private DocumentMetadata metadata = null; + private DocumentMetadata metadata; /** * The mimeType of the document @@ -126,41 +126,41 @@ public class DocumentImpl extends NodeImpl implements Resource, Do /** * The creation time of this document */ - protected long created = 0; + protected long created; /** * Time of the last modification */ - protected long lastModified = 0; + protected long lastModified; /** * The number of data pages occupied by this document */ - protected int pageCount = 0; + protected int pageCount; /** * Contains the user id if a user lock is held on this resource */ - protected int userLock = 0; + protected int userLock; /** * The document's XML Declaration - if specified. */ - @Nullable private XMLDeclarationImpl xmlDecl = null; + @Nullable private XMLDeclarationImpl xmlDecl; /** * The document's doctype declaration - if specified. */ - protected DocumentType docType = null; + protected DocumentType docType; /** * Associated lock token - if available */ - protected LockToken lockToken = null; + protected LockToken lockToken; - protected transient int splitCount = 0; + protected transient int splitCount; - private boolean isReferenced = false; + private boolean isReferenced; /** * Creates a new DocumentImpl instance. @@ -715,7 +715,7 @@ public void copyChildren(@EnsureLocked(mode=READ_LOCK) final DocumentImpl other) */ @EnsureContainerLocked(mode=WRITE_LOCK) public void setUserLock(final Account user) { - this.userLock = (user == null ? 0 : user.getId()); + this.userLock = user == null ? 0 : user.getId(); } /** @@ -743,7 +743,7 @@ public Account getUserLock() { @EnsureContainerLocked(mode=READ_LOCK) public long getContentLength() { final long length = pageCount * pool.getPageSize(); - return (length < 0) ? 0 : length; + return length < 0 ? 0 : length; } /** @@ -889,7 +889,7 @@ public static DocumentImpl read(final BrokerPool pool, final VariableByteInput i permissions.read(istream); final int children = istream.readInt(); - final long childAddress[] = new long[children]; + final long[] childAddress = new long[children]; for (int i = 0; i < children; i++) { childAddress[i] = StorageAddress.createPointer(istream.readInt(), istream.readShort()); } @@ -1367,7 +1367,7 @@ public Element getDocumentElement() { @Override public NodeList getElementsByTagName(final String tagname) { - if(tagname != null && tagname.equals(QName.WILDCARD)) { + if(QName.WILDCARD.equals(tagname)) { return getElementsByTagName(new QName.WildcardLocalPartQName(XMLConstants.DEFAULT_NS_PREFIX)); } else { try { @@ -1380,8 +1380,8 @@ public NodeList getElementsByTagName(final String tagname) { @Override public NodeList getElementsByTagNameNS(final String namespaceURI, final String localName) { - final boolean wildcardNS = namespaceURI != null && namespaceURI.equals(QName.WILDCARD); - final boolean wildcardLocalPart = localName != null && localName.equals(QName.WILDCARD); + final boolean wildcardNS = QName.WILDCARD.equals(namespaceURI); + final boolean wildcardLocalPart = QName.WILDCARD.equals(localName); if(wildcardNS && wildcardLocalPart) { return getElementsByTagName(QName.WildcardQName.getInstance()); @@ -1401,7 +1401,7 @@ private NodeList getElementsByTagName(final QName qname) { docs.add(this); final NewArrayNodeSet contextSet = new NewArrayNodeSet(); - final ElementImpl root = ((ElementImpl)getDocumentElement()); + final ElementImpl root = (ElementImpl)getDocumentElement(); contextSet.add(new NodeProxy(getExpression(), this, root.getNodeId(), root.getInternalAddress())); return broker.getStructuralIndex().scanByType(ElementValue.ELEMENT, Constants.DESCENDANT_SELF_AXIS, diff --git a/exist-core/src/main/java/org/exist/dom/persistent/ElementImpl.java b/exist-core/src/main/java/org/exist/dom/persistent/ElementImpl.java index 4cf5fd93107..130c9908c9f 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/ElementImpl.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/ElementImpl.java @@ -51,10 +51,10 @@ import org.exist.xquery.value.StringValue; import org.w3c.dom.*; +import javax.annotation.Nonnull; import javax.xml.XMLConstants; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; -import javax.annotation.Nonnull; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; @@ -76,14 +76,14 @@ public class ElementImpl extends NamedNode implements Element { public static final int LENGTH_NS_ID = 2; //sizeof short public static final int LENGTH_PREFIX_LENGTH = 2; //sizeof short - private short attributes = 0; // number of attributes - private int children = 0; // number of elements AND attributes + private short attributes; // number of attributes + private int children; // number of elements AND attributes - private int position = 0; - private Map namespaceMappings = null; + private int position; + private Map namespaceMappings; private int indexType = RangeIndexSpec.NO_INDEX; - private boolean preserveWS = false; - private boolean isDirty = false; + private boolean preserveWS; + private boolean isDirty; public ElementImpl() { this((Expression) null); @@ -637,7 +637,7 @@ private void appendChildren(final Txn transaction, private QName attrName(Attr attr) { final String ns = attr.getNamespaceURI(); - final String prefix = (Namespaces.XML_NS.equals(ns) ? XMLConstants.XML_NS_PREFIX : attr.getPrefix()); + final String prefix = Namespaces.XML_NS.equals(ns) ? XMLConstants.XML_NS_PREFIX : attr.getPrefix(); String name = attr.getLocalName(); if(name == null) { name = attr.getName(); @@ -1007,7 +1007,7 @@ private void getChildren(final boolean includeAttributes, final org.exist.dom.No @Override @Nonnull public NodeList getElementsByTagName(final String name) { - if(name != null && name.equals(QName.WILDCARD)) { + if(QName.WILDCARD.equals(name)) { return getElementsByTagName(new QName.WildcardLocalPartQName(XMLConstants.DEFAULT_NS_PREFIX)); } else { try { @@ -1021,8 +1021,8 @@ public NodeList getElementsByTagName(final String name) { @Override @Nonnull public NodeList getElementsByTagNameNS(final String namespaceURI, final String localName) { - final boolean wildcardNS = namespaceURI != null && namespaceURI.equals(QName.WILDCARD); - final boolean wildcardLocalPart = localName != null && localName.equals(QName.WILDCARD); + final boolean wildcardNS = QName.WILDCARD.equals(namespaceURI); + final boolean wildcardLocalPart = QName.WILDCARD.equals(localName); if(wildcardNS && wildcardLocalPart) { return getElementsByTagName(QName.WildcardQName.getInstance()); @@ -1143,7 +1143,6 @@ public void removeAttribute(final String name) throws DOMException { public void removeAttributeNS(final String namespaceURI, final String name) throws DOMException { final Attr attr = getAttributeNodeNS(namespaceURI, name); if(attr == null) { - return; } } @@ -1439,13 +1438,10 @@ private String toString(final boolean top, final Set namespaces) { final NodeList childNodes = getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { final Node child = childNodes.item(i); - switch (child.getNodeType()) { - case Node.ELEMENT_NODE: - children.append(((ElementImpl) child).toString(false, namespaces)); - break; - - default: - children.append(child); + if (child.getNodeType() == Node.ELEMENT_NODE) { + children.append(((ElementImpl)child).toString(false, namespaces)); + } else { + children.append(child); } } @@ -1825,8 +1821,8 @@ public void removeAppendAttributes(final Txn transaction, final NodeList removeL } private class AttribVisitor implements NodeVisitor { - private IStoredNode lastAttrib = null; - private IStoredNode firstChild = null; + private IStoredNode lastAttrib; + private IStoredNode firstChild; @Override public boolean visit(final IStoredNode node) { diff --git a/exist-core/src/main/java/org/exist/dom/persistent/ExtArrayNodeSet.java b/exist-core/src/main/java/org/exist/dom/persistent/ExtArrayNodeSet.java index 32c38324f6f..5af873a3b46 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/ExtArrayNodeSet.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/ExtArrayNodeSet.java @@ -75,14 +75,14 @@ public class ExtArrayNodeSet extends AbstractArrayNodeSet implements DocumentSet private final int initialSize; - private int documentIds[]; + private int[] documentIds; protected int lastDoc = -1; - private Part parts[]; - private int partCount = 0; - protected Part lastPart = null; + private Part[] parts; + private int partCount; + protected Part lastPart; - private boolean keepUnOrdered = false; + private boolean keepUnOrdered; public ExtArrayNodeSet() { @@ -144,10 +144,10 @@ private Part getPart(final DocumentImpl doc, final boolean create, final int siz private void insertPart(final int docId, final Part part, final int idx) { if(partCount == parts.length) { final int nsize = parts.length == 0 ? 1 : parts.length * 2; - int ndocs[] = new int[nsize]; + int[] ndocs = new int[nsize]; System.arraycopy(documentIds, 0, ndocs, 0, documentIds.length); Arrays.fill(documentIds, -1); - final Part nparts[] = new Part[nsize]; + final Part[] nparts = new Part[nsize]; System.arraycopy(parts, 0, nparts, 0, parts.length); documentIds = ndocs; parts = nparts; @@ -288,11 +288,9 @@ public NodeProxy hasDescendantsInSet(final DocumentImpl doc, final NodeId ancest @Override public void sort(final boolean mergeContexts) { if(isSorted || keepUnOrdered) { - return; } else if(hasOne) { isSorted = true; // shortcut: don't sort if there's just one item size = parts[0].removeDuplicates(mergeContexts); - return; } else { size = 0; for (int i = 0; i < partCount; i++) { @@ -532,7 +530,7 @@ public ManagedLocks lock(final DBBroker broker, final boole } private class DocumentIterator implements Iterator { - private int currentDoc = 0; + private int currentDoc; @Override public final boolean hasNext() { @@ -588,9 +586,9 @@ public final void remove() { private final class Part { - private boolean isSorted = false; - private NodeProxy array[]; - private int length = 0; + private boolean isSorted; + private NodeProxy[] array; + private int length; Part(final int initialSize) { this.array = new NodeProxy[initialSize]; @@ -700,7 +698,7 @@ void add(final NodeProxy p) { //} ljo's modification } else if(length == array.length) { final int newLength = length << 1; - final NodeProxy temp[] = new NodeProxy[newLength]; + final NodeProxy[] temp = new NodeProxy[newLength]; System.arraycopy(array, 0, temp, 0, length); array = temp; } @@ -888,31 +886,26 @@ NodeSet getDescendantsInSet(final NodeSet result, final NodeProxy parent, final add = array[i].getNodeId() != NodeId.DOCUMENT_NODE; } if(add) { - switch(mode) { - - case NodeSet.DESCENDANT: - if(Expression.NO_CONTEXT_ID != contextId) { - array[i].deepCopyContext(parent, contextId); - } else { - array[i].copyContext(parent); - } - if(copyMatches) { - array[i].addMatches(parent); - } - result.add(array[i]); - break; - - case NodeSet.ANCESTOR: - if(Expression.NO_CONTEXT_ID != contextId) { - parent.deepCopyContext(array[i], contextId); - } else { - parent.copyContext(array[i]); - } - if(copyMatches) { - parent.addMatches(array[i]); - } - result.add(parent, 1); - break; + if (mode == NodeSet.DESCENDANT) { + if (Expression.NO_CONTEXT_ID != contextId) { + array[i].deepCopyContext(parent, contextId); + } else { + array[i].copyContext(parent); + } + if (copyMatches) { + array[i].addMatches(parent); + } + result.add(array[i]); + } else if (mode == NodeSet.ANCESTOR) { + if (Expression.NO_CONTEXT_ID != contextId) { + parent.deepCopyContext(array[i], contextId); + } else { + parent.copyContext(array[i]); + } + if (copyMatches) { + parent.addMatches(array[i]); + } + result.add(parent, 1); } } } @@ -954,28 +947,23 @@ NodeSet getDescendantsInSet(final NodeSet result, final NodeProxy parent, final add = includeSelf; } if(add) { - switch(mode) { - - case NodeSet.DESCENDANT: - if(Expression.NO_CONTEXT_ID != contextId) { - array[i].deepCopyContext(parent, contextId); - } else { - array[i].copyContext(parent); - } - array[i].addMatches(parent); - result.add(array[i]); - break; - - case NodeSet.ANCESTOR: - if(Expression.NO_CONTEXT_ID != contextId) { - //parent.addContextNode(contextId, array[i]); - parent.deepCopyContext(array[i], contextId); - } else { - parent.copyContext(array[i]); - } - parent.addMatches(array[i]); - result.add(parent, 1); - break; + if (mode == NodeSet.DESCENDANT) { + if (Expression.NO_CONTEXT_ID != contextId) { + array[i].deepCopyContext(parent, contextId); + } else { + array[i].copyContext(parent); + } + array[i].addMatches(parent); + result.add(array[i]); + } else if (mode == NodeSet.ANCESTOR) { + if (Expression.NO_CONTEXT_ID != contextId) { + //parent.addContextNode(contextId, array[i]); + parent.deepCopyContext(array[i], contextId); + } else { + parent.copyContext(array[i]); + } + parent.addMatches(array[i]); + result.add(parent, 1); } } } else { @@ -1046,10 +1034,10 @@ void setSelfAsContext(final int contextId) { private class ExtArrayIterator implements NodeSetIterator, SequenceIterator { - Part currentPart = null; - int partPos = 0; - int pos = 0; - NodeProxy next = null; + Part currentPart; + int partPos; + int pos; + NodeProxy next; ExtArrayIterator() { if(partPos < partCount) { diff --git a/exist-core/src/main/java/org/exist/dom/persistent/LockToken.java b/exist-core/src/main/java/org/exist/dom/persistent/LockToken.java index d260a4eb7f7..15f766881e4 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/LockToken.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/LockToken.java @@ -53,7 +53,7 @@ public class LockToken { private final ResourceType resourceType; //= ResourceType.NOT_SPECIFIED; // Other - @Nullable private String owner = null; + @Nullable private String owner; private long timeout = -1L; @Nullable private String token; diff --git a/exist-core/src/main/java/org/exist/dom/persistent/Match.java b/exist-core/src/main/java/org/exist/dom/persistent/Match.java index f66f497dd1a..aaa0cd377c8 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/Match.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/Match.java @@ -84,9 +84,9 @@ public boolean overlaps(final Offset other) { private int[] offsets; private int[] lengths; - private int currentOffset = 0; + private int currentOffset; - private @Nullable Match nextMatch = null; + private @Nullable Match nextMatch; protected Match(final int contextId, final NodeId nodeId, @Nullable final String matchTerm) { this(contextId, nodeId, matchTerm, 1); diff --git a/exist-core/src/main/java/org/exist/dom/persistent/NamedNode.java b/exist-core/src/main/java/org/exist/dom/persistent/NamedNode.java index 9ae3111014c..8fa3d3f5161 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/NamedNode.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/NamedNode.java @@ -33,7 +33,7 @@ */ public abstract class NamedNode extends StoredNode { - protected QName nodeName = null; + protected QName nodeName; protected NamedNode(final short nodeType) { this(null, nodeType); diff --git a/exist-core/src/main/java/org/exist/dom/persistent/NewArrayNodeSet.java b/exist-core/src/main/java/org/exist/dom/persistent/NewArrayNodeSet.java index 766eacd68dd..8d022070acc 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/NewArrayNodeSet.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/NewArrayNodeSet.java @@ -67,27 +67,27 @@ */ public class NewArrayNodeSet extends AbstractArrayNodeSet implements ExtNodeSet, DocumentSet { - private Set cachedCollections = null; + private Set cachedCollections; - private int documentCount = 0; + private int documentCount; /** * An array of Document IDs of length {@link #documentCount} */ - private int documentIds[] = new int[16]; + private int[] documentIds = new int[16]; /** * An array of offsets into {@link #nodes}, * the index is the index from {@link #documentNodesOffset}. */ - private int documentNodesOffset[] = new int[16]; + private int[] documentNodesOffset = new int[16]; /** * An array of the node count for each document, * each value is a count of the nodes for a specific document, * the index is the index from {@link #documentNodesOffset}. */ - private int documentNodesCount[] = new int[16]; + private int[] documentNodesCount = new int[16]; /** * An array of nodes from documents, @@ -104,7 +104,7 @@ public class NewArrayNodeSet extends AbstractArrayNodeSet implements ExtNodeSet, * System.arraycopy(nodes, nodeStartIdx, docNodes, 0, nodeCount); * } */ - private NodeProxy nodes[]; + private NodeProxy[] nodes; public NewArrayNodeSet() { this(INITIAL_SIZE); @@ -133,7 +133,7 @@ public NewArrayNodeSet(final NewArrayNodeSet other) { private void ensureCapacity() { if(size == nodes.length) { final int nsize = size << 1; - final NodeProxy temp[] = new NodeProxy[nsize]; + final NodeProxy[] temp = new NodeProxy[nsize]; System.arraycopy(nodes, 0, temp, 0, size); nodes = temp; } @@ -318,29 +318,26 @@ private NodeSet getDescendantsInSet(final int docIdx, final NodeSet result, fina add = nodes[i].getNodeId() != NodeId.DOCUMENT_NODE; } if(add) { - switch(mode) { - case NodeSet.DESCENDANT: - if(Expression.NO_CONTEXT_ID != contextId) { - nodes[i].deepCopyContext(parent, contextId); - } else { - nodes[i].copyContext(parent); - } - if(copyMatches) { - nodes[i].addMatches(parent); - } - result.add(nodes[i]); - break; - case NodeSet.ANCESTOR: - if(Expression.NO_CONTEXT_ID != contextId) { - parent.deepCopyContext(nodes[i], contextId); - } else { - parent.copyContext(nodes[i]); - } - if(copyMatches) { - parent.addMatches(nodes[i]); - } - result.add(parent, 1); - break; + if (mode == NodeSet.DESCENDANT) { + if (Expression.NO_CONTEXT_ID != contextId) { + nodes[i].deepCopyContext(parent, contextId); + } else { + nodes[i].copyContext(parent); + } + if (copyMatches) { + nodes[i].addMatches(parent); + } + result.add(nodes[i]); + } else if (mode == NodeSet.ANCESTOR) { + if (Expression.NO_CONTEXT_ID != contextId) { + parent.deepCopyContext(nodes[i], contextId); + } else { + parent.copyContext(nodes[i]); + } + if (copyMatches) { + parent.addMatches(nodes[i]); + } + result.add(parent, 1); } } } @@ -383,29 +380,26 @@ private NodeSet getDescendantsInSet(final int docIdx, final NodeSet result, fina add = includeSelf; } if(add) { - switch(mode) { - case NodeSet.DESCENDANT: - if(Expression.NO_CONTEXT_ID != contextId) { - nodes[i].deepCopyContext(parent, contextId); - } else { - nodes[i].copyContext(parent); - } - if(copyMatches) { - nodes[i].addMatches(parent); - } - result.add(nodes[i]); - break; - case NodeSet.ANCESTOR: - if(Expression.NO_CONTEXT_ID != contextId) { - parent.deepCopyContext(nodes[i], contextId); - } else { - parent.copyContext(nodes[i]); - } - if(copyMatches) { - parent.addMatches(nodes[i]); - } - result.add(parent, 1); - break; + if (mode == NodeSet.DESCENDANT) { + if (Expression.NO_CONTEXT_ID != contextId) { + nodes[i].deepCopyContext(parent, contextId); + } else { + nodes[i].copyContext(parent); + } + if (copyMatches) { + nodes[i].addMatches(parent); + } + result.add(nodes[i]); + } else if (mode == NodeSet.ANCESTOR) { + if (Expression.NO_CONTEXT_ID != contextId) { + parent.deepCopyContext(nodes[i], contextId); + } else { + parent.copyContext(nodes[i]); + } + if (copyMatches) { + parent.addMatches(nodes[i]); + } + result.add(parent, 1); } } } else { @@ -496,12 +490,10 @@ private NodeProxy hasDescendantsInSet(final int docIdx, final NodeId ancestorId, @Override public void sort(final boolean mergeContexts) { if(isSorted) { - return; } else if(hasOne) { isSorted = true; // shortcut: don't sort if there's just one item removeDuplicates(mergeContexts); updateDocs(); - return; } else { if(size > 0) { FastQSort.sort(nodes, 0, size - 1); @@ -1211,7 +1203,7 @@ public ManagedLocks lock(final DBBroker broker, final boole private class DocumentIterator implements Iterator { - private int currentDoc = 0; + private int currentDoc; @Override public final boolean hasNext() { @@ -1241,7 +1233,7 @@ public void clearContext(final int contextId) throws XPathException { } protected class NewArrayIterator implements NodeSetIterator, SequenceIterator { - private int pos = 0; + private int pos; @Override public final boolean hasNext() { @@ -1301,7 +1293,8 @@ public void setPosition(final NodeProxy proxy) { if(docIdx > -1) { int low = documentNodesOffset[docIdx]; int high = low + (documentNodesCount[docIdx] - 1); - int mid, cmp; + int mid; + int cmp; NodeProxy p; while(low <= high) { mid = (low + high) / 2; diff --git a/exist-core/src/main/java/org/exist/dom/persistent/NodeImpl.java b/exist-core/src/main/java/org/exist/dom/persistent/NodeImpl.java index 893f88b5347..d2ecc943518 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/NodeImpl.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/NodeImpl.java @@ -270,7 +270,7 @@ public final String getNamespaceURI() { case Node.ELEMENT_NODE: case Node.ATTRIBUTE_NODE: final String nsUri = getQName().getNamespaceURI(); - if(nsUri.equals(XMLConstants.NULL_NS_URI)) { + if(XMLConstants.NULL_NS_URI.equals(nsUri)) { return null; } else { return nsUri; diff --git a/exist-core/src/main/java/org/exist/dom/persistent/NodeProxy.java b/exist-core/src/main/java/org/exist/dom/persistent/NodeProxy.java index 3bb531a4528..3ae5c83df4b 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/NodeProxy.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/NodeProxy.java @@ -79,7 +79,7 @@ public class NodeProxy implements NodeSet, NodeValue, NodeHandle, DocumentSet, C /** * The owner document of this node. */ - private DocumentImpl doc = null; + private DocumentImpl doc; private NodeId nodeId; @@ -104,11 +104,11 @@ public class NodeProxy implements NodeSet, NodeValue, NodeHandle, DocumentSet, C * * Matches are stored as a linked list. */ - private Match match = null; + private Match match; - private ContextItem context = null; + private ContextItem context; - private QName qname = null; + private QName qname; private final Expression expression; @@ -201,7 +201,7 @@ public NodeProxy(final DocumentImpl doc, final NodeId nodeId, final short nodeTy * @param address a long value */ public NodeProxy(final Expression expression, final DocumentImpl doc, final NodeId nodeId, final short nodeType, final long address) { - this.expression = (expression == null && doc != null) ? doc.getExpression() : expression; + this.expression = expression == null && doc != null ? doc.getExpression() : expression; this.doc = doc; this.nodeType = nodeType; this.internalAddress = address; @@ -233,7 +233,7 @@ public NodeProxy(final NodeHandle n) { * @param n a NodeHandle value */ public NodeProxy(final Expression expression, final NodeHandle n) { - this((expression == null && n instanceof NodeProxy np) ? np.getExpression() : expression, n.getOwnerDocument(), n.getNodeId(), n.getNodeType(), n.getInternalAddress()); + this(expression == null && n instanceof NodeProxy np ? np.getExpression() : expression, n.getOwnerDocument(), n.getNodeId(), n.getNodeType(), n.getInternalAddress()); if(n instanceof NodeProxy proxy) { this.match = proxy.match; this.context = proxy.context; @@ -772,7 +772,7 @@ public void copyTo(final DBBroker broker, final DocumentBuilderReceiver receiver node = (NodeImpl) getNode(); } if(nodeType == Node.ATTRIBUTE_NODE) { - final AttrImpl attr = (node == null ? (AttrImpl) getNode() : (AttrImpl) node); + final AttrImpl attr = node == null ? (AttrImpl) getNode() : (AttrImpl) node; receiver.attribute(attr.getQName(), attr.getValue()); } else { receiver.addReferenceNode(this); diff --git a/exist-core/src/main/java/org/exist/dom/persistent/NodeSetHelper.java b/exist-core/src/main/java/org/exist/dom/persistent/NodeSetHelper.java index 4d1a6caf3c7..7760595794b 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/NodeSetHelper.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/NodeSetHelper.java @@ -672,7 +672,7 @@ public static boolean directMatchAttributes(final DBBroker broker, final NodeSet return false; } - public static final void copyChildren(final Document newDoc, final Node node, final Node newNode) { + public static void copyChildren(final Document newDoc, final Node node, final Node newNode) { final NodeList children = node.getChildNodes(); Node newChild; for(int i = 0; i < children.getLength(); i++) { @@ -696,7 +696,7 @@ public static final void copyChildren(final Document newDoc, final Node node, fi } } - public static final Node copyNode(final Document newDoc, final Node node) { + public static Node copyNode(final Document newDoc, final Node node) { final Node newNode; switch(node.getNodeType()) { diff --git a/exist-core/src/main/java/org/exist/dom/persistent/ProcessingInstructionImpl.java b/exist-core/src/main/java/org/exist/dom/persistent/ProcessingInstructionImpl.java index eae1cbeb51e..79cd535264f 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/ProcessingInstructionImpl.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/ProcessingInstructionImpl.java @@ -41,8 +41,8 @@ public class ProcessingInstructionImpl extends StoredNode implements ProcessingI public static final int LENGTH_TARGET_DATA = 4; //Sizeof int; - protected String target = null; - protected String data = null; + protected String target; + protected String data; public ProcessingInstructionImpl() { this(null); diff --git a/exist-core/src/main/java/org/exist/dom/persistent/SortedNodeSet.java b/exist-core/src/main/java/org/exist/dom/persistent/SortedNodeSet.java index 88ecfb38641..b0f6279565b 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/SortedNodeSet.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/SortedNodeSet.java @@ -269,7 +269,7 @@ public final void setPosition(final NodeProxy proxy) { private static final class IteratorItem extends OrderedLinkedList.Node { private final NodeProxy proxy; - private String value = null; + private String value; public IteratorItem(final NodeProxy proxy, final PathExpr expr) { this.proxy = proxy; @@ -283,7 +283,7 @@ public IteratorItem(final NodeProxy proxy, final PathExpr expr) { strings.add(new OrderedLinkedList.SimpleNode(item.getStringValue().toUpperCase())); } for(final Iterator j = strings.iterator(); j.hasNext(); ) { - buf.append((j.next()).getData()); + buf.append(j.next().getData()); } value = buf.toString(); } catch(final XPathException e) { diff --git a/exist-core/src/main/java/org/exist/dom/persistent/StoredNode.java b/exist-core/src/main/java/org/exist/dom/persistent/StoredNode.java index 23907d188bc..ff4735be7a5 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/StoredNode.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/StoredNode.java @@ -52,9 +52,9 @@ public abstract class StoredNode extends NodeImpl imple public static final int LENGTH_SIGNATURE_LENGTH = 1; //sizeof byte public static final long UNKNOWN_NODE_IMPL_ADDRESS = -1; - protected NodeId nodeId = null; + protected NodeId nodeId; - protected DocumentImpl ownerDocument = null; + protected DocumentImpl ownerDocument; private long internalAddress = UNKNOWN_NODE_IMPL_ADDRESS; @@ -545,8 +545,8 @@ public int compareTo(final StoredNode other) { public boolean isSameNode(final Node other) { // This function is used by Saxon in some circumstances, and is required for proper Saxon operation. if(other instanceof IStoredNode node) { - return (this.nodeId.equals(node.getNodeId()) && - this.ownerDocument.getDocId() == ((IStoredNode) other).getOwnerDocument().getDocId()); + return this.nodeId.equals(node.getNodeId()) && + this.ownerDocument.getDocId() == ((IStoredNode) other).getOwnerDocument().getDocId(); } else { return false; } diff --git a/exist-core/src/main/java/org/exist/dom/persistent/SymbolTable.java b/exist-core/src/main/java/org/exist/dom/persistent/SymbolTable.java index 94d1ddf33c9..39d340409c5 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/SymbolTable.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/SymbolTable.java @@ -105,14 +105,14 @@ public static SymbolType valueOf(final byte typeId) { /** * set to true if the symbol table needs to be saved */ - private boolean changed = false; + private boolean changed; /** * the underlying symbols.dbx file */ private Path file; private final VariableByteOutputStream outBuffer = new VariableByteOutputStream(256); - private OutputStream os = null; + private OutputStream os; @Override public void configure(final Configuration configuration) { @@ -142,7 +142,7 @@ public void stopSystem(final DBBroker systemBroker) throws BrokerPoolServiceExce } } - public static final String getFileName() { + public static String getFileName() { return FILE_NAME; } @@ -458,7 +458,7 @@ protected class SymbolCollection { /** * contains the offset of the last symbol */ - protected short offset = 0; + protected short offset; public SymbolCollection(final SymbolType symbolType, final int initialSize) { this.symbolType = symbolType; diff --git a/exist-core/src/main/java/org/exist/dom/persistent/VirtualNodeSet.java b/exist-core/src/main/java/org/exist/dom/persistent/VirtualNodeSet.java index 2103c68efe0..3cccb05f59e 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/VirtualNodeSet.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/VirtualNodeSet.java @@ -67,21 +67,21 @@ public class VirtualNodeSet extends AbstractNodeSet { protected int axis = Constants.UNKNOWN_AXIS; protected NodeTest test; protected NodeSet context; - protected NodeSet realSet = null; - protected boolean realSetIsComplete = false; - protected boolean inPredicate = false; - protected boolean useSelfAsContext = false; + protected NodeSet realSet; + protected boolean realSetIsComplete; + protected boolean inPredicate; + protected boolean useSelfAsContext; protected int contextId = Expression.NO_CONTEXT_ID; - private DocumentSet realDocumentSet = null; + private DocumentSet realDocumentSet; - private boolean knownIsEmptyCardinality = false; - private boolean knownHasOneCardinality = false; - private boolean knownHasManyCardinality = false; + private boolean knownIsEmptyCardinality; + private boolean knownHasOneCardinality; + private boolean knownHasManyCardinality; - protected boolean hasMany = false; + protected boolean hasMany; - private DBBroker broker; + private final DBBroker broker; /** * Creates a new VirtualNodeSet instance. @@ -105,12 +105,7 @@ public VirtualNodeSet(final DBBroker broker, final int axis, final NodeTest test @Override public boolean contains(final NodeProxy p) { final NodeProxy firstParent = getFirstParent(p, null, axis == Constants.SELF_AXIS, 0); - // Timo Boehme: getFirstParent returns now only real parents - // therefore test if node is child of context - if(firstParent != null) { - return true; - } - return false; + return firstParent != null; } @Override diff --git a/exist-core/src/main/java/org/exist/dom/persistent/XMLUtil.java b/exist-core/src/main/java/org/exist/dom/persistent/XMLUtil.java index f6cfa5a8d3f..c6eea4287c0 100644 --- a/exist-core/src/main/java/org/exist/dom/persistent/XMLUtil.java +++ b/exist-core/src/main/java/org/exist/dom/persistent/XMLUtil.java @@ -51,7 +51,7 @@ private XMLUtil() { //Utility class of static methods } - public static final String dump(final DocumentFragment fragment) { + public static String dump(final DocumentFragment fragment) { final StringWriter writer = new StringWriter(); final DOMSerializer serializer = new DOMSerializer(writer, null); try { @@ -62,7 +62,7 @@ public static final String dump(final DocumentFragment fragment) { return writer.toString(); } - public static final String encodeAttrMarkup(final String str) { + public static String encodeAttrMarkup(final String str) { final StringBuilder buf = new StringBuilder(); char ch; for(int i = 0; i < str.length(); i++) { @@ -100,7 +100,7 @@ public static final String encodeAttrMarkup(final String str) { return buf.toString(); } - public static final String decodeAttrMarkup(final String str) { + public static String decodeAttrMarkup(final String str) { final StringBuilder out = new StringBuilder(str.length()); char ch; String ent; @@ -134,7 +134,7 @@ public static final String decodeAttrMarkup(final String str) { return out.toString(); } - public static final Optional getEncoding(final String xmlDecl) { + public static Optional getEncoding(final String xmlDecl) { if(xmlDecl == null) { return Optional.empty(); } @@ -159,7 +159,7 @@ public static final Optional getEncoding(final String xmlDecl) { return Optional.empty(); } - public static final String getXMLDecl(final byte[] data) { + public static String getXMLDecl(final byte[] data) { boolean foundTag = false; for(int i = 0; i < data.length && !foundTag; i++) { if(data[i] == '<') { @@ -173,7 +173,7 @@ public static final String getXMLDecl(final byte[] data) { boolean foundQuestionMark = false; int placeInDeclString = 0; final byte[] declString = new byte[4]; - int x = (i + 1); + int x = i + 1; for(; x < data.length; x++) { if(data[x] == 0) { @@ -207,7 +207,7 @@ public static final String getXMLDecl(final byte[] data) { out.write('<'); out.write(declString, 0, 4); - for(int j = (x + 1); j < data.length; j++) { + for(int j = x + 1; j < data.length; j++) { if(data[j] != 0) { out.write(data[j]); } @@ -240,7 +240,7 @@ public static final String getXMLDecl(final byte[] data) { } @Deprecated - public static final String readFile(final Path file) throws IOException { + public static String readFile(final Path file) throws IOException { return readFile(file, UTF_8); } @@ -282,6 +282,7 @@ public static String parseValue(final String value, final String key) { public static String parseValue(final String value, int p) { while((p < value.length()) && (value.charAt(++p) != '"')) { + continue; // Do nothing } if(p == value.length()) { @@ -289,6 +290,7 @@ public static String parseValue(final String value, int p) { } int e = ++p; while((e < value.length()) && (value.charAt(++e) != '"')) { + continue; // Do nothing } if(e == value.length()) { diff --git a/exist-core/src/main/java/org/exist/http/AuditTrailSessionListener.java b/exist-core/src/main/java/org/exist/http/AuditTrailSessionListener.java index f3d19e9e4ea..62f765cccce 100644 --- a/exist-core/src/main/java/org/exist/http/AuditTrailSessionListener.java +++ b/exist-core/src/main/java/org/exist/http/AuditTrailSessionListener.java @@ -21,6 +21,9 @@ */ package org.exist.http; +import jakarta.servlet.http.HttpSession; +import jakarta.servlet.http.HttpSessionEvent; +import jakarta.servlet.http.HttpSessionListener; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.dom.persistent.BinaryDocument; @@ -39,9 +42,6 @@ import org.exist.xquery.value.AnyURIValue; import org.exist.xquery.value.Sequence; -import jakarta.servlet.http.HttpSession; -import jakarta.servlet.http.HttpSessionEvent; -import jakarta.servlet.http.HttpSessionListener; import java.util.Optional; import java.util.Properties; @@ -75,7 +75,7 @@ public void sessionCreated(final HttpSessionEvent sessionEvent) { @Override public void sessionDestroyed(final HttpSessionEvent sessionEvent) { - final HttpSession session = (sessionEvent != null) ? sessionEvent.getSession() : null; + final HttpSession session = sessionEvent != null ? sessionEvent.getSession() : null; if (session != null) { LOG.info("Destroyed session {}", session.getId()); } else { diff --git a/exist-core/src/main/java/org/exist/http/Descriptor.java b/exist-core/src/main/java/org/exist/http/Descriptor.java index 571aa558276..7d2bc8af3be 100644 --- a/exist-core/src/main/java/org/exist/http/Descriptor.java +++ b/exist-core/src/main/java/org/exist/http/Descriptor.java @@ -22,6 +22,7 @@ package org.exist.http; +import jakarta.servlet.http.HttpServletRequest; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.Namespaces; @@ -35,7 +36,6 @@ import org.w3c.dom.NodeList; import org.xml.sax.*; -import jakarta.servlet.http.HttpServletRequest; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; @@ -65,21 +65,21 @@ // TODO: doLogRequestInReplayLog() - add the facility to log HTTP PUT requests, may need changes to HttpServletRequestWrapper // TODO: doLogRequestInReplayLog() - add the facility to log HTTP POST form file uploads, may need changes to HttpServletRequestWrapper -public class Descriptor implements ErrorHandler { +public final class Descriptor implements ErrorHandler { private static final String SYSTEM_LINE_SEPARATOR = System.getProperty("line.separator"); //References private static Descriptor singletonRef; - private final static Logger LOG = LogManager.getLogger(Descriptor.class); //Logger + private static final Logger LOG = LogManager.getLogger(Descriptor.class); //Logger /** * descriptor file (descriptor.xml) */ - private final static String file = "descriptor.xml"; + private static final String file = "descriptor.xml"; //Data - private BufferedWriter bufWriteReplayLog = null; //Should a replay log of requests be created - private boolean requestsFiltered = false; - private String allowSourceList[] = null; //Array of xql files to allow source to be viewed - private String mapList[][] = null; //Array of Mappings + private BufferedWriter bufWriteReplayLog; //Should a replay log of requests be created + private boolean requestsFiltered; + private String[] allowSourceList; //Array of xql files to allow source to be viewed + private String[][] mapList; //Array of Mappings /** * Descriptor Constructor. @@ -183,7 +183,7 @@ public static synchronized Descriptor getDescriptorSingleton() { singletonRef = new Descriptor(); } - return (singletonRef); + return singletonRef; } /** @@ -292,11 +292,11 @@ public boolean allowSource(String path) { //does the path match the path if ((s.equals(path)) || (path.contains(s))) { //yes, return true - return (true); + return true; } } } - return (false); + return false; } /** @@ -310,7 +310,7 @@ public boolean allowSource(String path) { public String mapPath(String path) { if (mapList == null) //has a list of mappings been specified? { - return (path); + return path; } //Iterate through the mappings @@ -318,12 +318,12 @@ public String mapPath(String path) { //does the path or the path/ match the map path if (strings[0].equals(path) || (strings[0] + "/").equals(path)) { //return the view - return (strings[1]); + return strings[1]; } } //no match return the original path - return (path); + return path; } public boolean requestsFiltered() { diff --git a/exist-core/src/main/java/org/exist/http/RESTServer.java b/exist-core/src/main/java/org/exist/http/RESTServer.java index 0d2164f8d9f..b113f76d1c2 100644 --- a/exist-core/src/main/java/org/exist/http/RESTServer.java +++ b/exist-core/src/main/java/org/exist/http/RESTServer.java @@ -21,6 +21,8 @@ */ package org.exist.http; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.exist.EXistException; @@ -84,8 +86,6 @@ import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.XMLFilterImpl; -import jakarta.servlet.http.HttpServletRequest; -import jakarta.servlet.http.HttpServletResponse; import javax.xml.XMLConstants; import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLStreamException; @@ -96,8 +96,8 @@ import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.reflect.Field; -import java.util.Properties; import java.util.*; +import java.util.Properties; import java.util.function.BiFunction; import static java.lang.invoke.MethodType.methodType; @@ -113,10 +113,10 @@ */ public class RESTServer { - protected final static Logger LOG = LogManager.getLogger(RESTServer.class); - public final static String SERIALIZATION_METHOD_PROPERTY = "output-as"; + protected static final Logger LOG = LogManager.getLogger(RESTServer.class); + public static final String SERIALIZATION_METHOD_PROPERTY = "output-as"; // Should we not obey the instance's defaults? /ljo - protected final static Properties defaultProperties = new Properties(); + protected static final Properties defaultProperties = new Properties(); static { defaultProperties.setProperty(OutputKeys.INDENT, "yes"); @@ -125,7 +125,8 @@ public class RESTServer { defaultProperties.setProperty(EXistOutputKeys.HIGHLIGHT_MATCHES, "elements"); defaultProperties.setProperty(EXistOutputKeys.PROCESS_XSL_PI, "yes"); } - public final static Properties defaultOutputKeysProperties = new Properties(); + + public static final Properties defaultOutputKeysProperties = new Properties(); static { defaultOutputKeysProperties.setProperty(EXistOutputKeys.OMIT_ORIGINAL_XML_DECLARATION, "no"); @@ -134,7 +135,8 @@ public class RESTServer { defaultOutputKeysProperties.setProperty(OutputKeys.MEDIA_TYPE, MimeType.XML_TYPE.getName()); } - private final static String QUERY_ERROR_HEAD = "" + "" + + private static final String QUERY_ERROR_HEAD = "" + "" + "Query Error" + "