From c1f2de4266da8ed1ba77091c827a43d213284daa Mon Sep 17 00:00:00 2001 From: thevpc Date: Mon, 1 Nov 2021 14:46:37 +0100 Subject: [PATCH 1/2] [WIP] Nuts API Refactoring to better address evolution of the API #105 --- .../runtime/bundles/collections/ClassMap.java | 11 + .../bundles/collections/EvictingIntQueue.java | 66 ++ .../bundles/collections/EvictingQueue.java | 61 +- .../bundles/common/JavascriptHelper.java | 362 ++++---- .../bundles/http/SimpleHttpClient.java | 2 +- .../bundles/io/FolderNutIdIterator.java | 8 +- .../bundles/io/FolderObjectIterator.java | 6 +- .../runtime/bundles/io/NutsStreamOrPath.java | 29 +- .../nuts/runtime/bundles/io/PipeThread.java | 10 +- .../runtime/bundles/io/ProcessBuilder2.java | 12 +- .../nuts/runtime/bundles/io/ZipUtils.java | 15 +- .../bundles/mvn/DirtyLuceneIndexParser.java | 6 +- .../bundles/mvn/MavenMetadataParser.java | 2 +- .../runtime/bundles/mvn/NutsPomLogger.java | 7 +- .../runtime/bundles/mvn/PomXmlParser.java | 9 +- .../bundles/parsers/StreamTokenizerExt.java | 4 +- .../runtime/bundles/string/GlobUtils.java | 82 +- .../runtime/core/AbstractNutsWorkspace.java | 17 +- .../runtime/core/DefaultNutsClassLoader.java | 6 +- .../nuts/runtime/core/DefaultNutsSession.java | 76 +- .../nuts/runtime/core/NutsWorkspaceExt.java | 2 + .../runtime/core/NutsWorkspaceFactory.java | 9 +- .../nuts/runtime/core/NutsWorkspaceModel.java | 49 + .../core/app/ArchitectureNonOption.java | 11 +- .../core/app/CoreNutsArgumentsParser.java | 2 +- ...DefaultDefaultNutsApplicationContexts.java | 31 + .../runtime/core/app/DefaultNonOption.java | 2 +- .../app/DefaultNutsApplicationContext.java | 11 +- .../DefaultNutsArgumentCandidateBuilder.java | 44 - .../core/app/DefaultNutsCommandLine.java | 38 +- .../app/DefaultNutsCommandLineFormat.java | 14 +- ...ager.java => DefaultNutsCommandLines.java} | 47 +- .../DefaultNutsWorkspaceLocationManager.java | 2 +- .../DefaultNutsWorkspaceLocationModel.java | 10 +- .../runtime/core/app/ExtensionNonOption.java | 3 +- .../nuts/runtime/core/app/GroupNonOption.java | 7 +- .../app/NutsCommandHistoryBuilderImpl.java | 63 -- .../core/app/NutsCommandHistoryImpl.java | 74 +- .../runtime/core/app/PackagingNonOption.java | 19 +- .../runtime/core/app/PermissionNonOption.java | 3 +- .../runtime/core/app/RepositoryNonOption.java | 5 +- .../core/app/RepositoryTypeNonOption.java | 3 +- .../nuts/runtime/core/app/UserNonOption.java | 5 +- .../core/commands/ws/AbstractNutsStream.java | 4 +- .../ws/DefaultNutsQueryBaseOptions.java | 4 +- .../runtime/core/eval/DefaultFctNode.java | 58 ++ .../runtime/core/eval/DefaultLiteralNode.java | 68 ++ .../runtime/core/eval/DefaultNutsExpr.java | 838 ++++++++++++++++++ .../nuts/runtime/core/eval/DefaultOpNode.java | 86 ++ .../runtime/core/eval/DefaultVarNode.java | 37 + .../nuts/runtime/core}/eval/EvalUtils.java | 61 +- .../runtime/core/eval/NutsExprWithCache.java | 70 ++ .../nuts/runtime/core/eval/NutsToken.java | 30 +- .../thevpc/nuts/runtime/core/eval/OpImpl.java | 47 + .../nuts/runtime/core/eval/SyntaxParser.java | 210 +++++ .../nuts/runtime/core/eval/TokenIterator.java | 113 +++ .../core/filters/AbstractNutsFilter.java | 15 +- .../runtime/core/filters/CoreFilterUtils.java | 20 +- .../core/filters/DefaultNutsFilterModel.java | 57 +- ...erManager.java => DefaultNutsFilters.java} | 57 +- .../filters/DefaultNutsIdMultiFilter.java | 187 ---- .../core/filters/DefaultNutsTokenFilter.java | 39 - .../filters/InternalNutsTypedFilters.java | 13 +- .../NutsIdAndNutsDependencyFilterItem.java | 42 - ...ava => InternalNutsDependencyFilters.java} | 62 +- .../dependency/JsNutsDependencyFilter.java | 84 +- .../dependency/NutsDependencyArchFilter.java | 2 +- .../NutsDependencyFilterParser.java | 4 +- .../NutsDependencyJavascriptFilter.java | 216 ++--- .../dependency/NutsDependencyOsFilter.java | 2 +- .../dependency/NutsDependencyScopeFilter.java | 2 +- ...ava => InternalNutsDescriptorFilters.java} | 67 +- .../descriptor/JsNutsDescriptorFilter.java | 84 +- .../descriptor/NutsDescriptorFilterAnd.java | 31 +- .../descriptor/NutsDescriptorFilterArch.java | 12 +- .../descriptor/NutsDescriptorFilterById.java | 13 +- ...utsDescriptorFilterDesktopEnvironment.java | 7 +- .../descriptor/NutsDescriptorFilterFalse.java | 7 +- .../descriptor/NutsDescriptorFilterNone.java | 32 +- .../descriptor/NutsDescriptorFilterOr.java | 32 +- .../descriptor/NutsDescriptorFilterOs.java | 31 +- .../NutsDescriptorFilterOsDist.java | 7 +- .../NutsDescriptorFilterPackaging.java | 21 +- .../NutsDescriptorFilterParser.java | 4 +- .../NutsDescriptorFilterPlatform.java | 7 +- .../descriptor/NutsDescriptorFilterTrue.java | 11 +- .../NutsDescriptorJavascriptFilter.java | 103 --- ...anager.java => InternalNutsIdFilters.java} | 58 +- .../filters/id/NutsDescriptorIdFilter.java | 2 +- .../core/filters/id/NutsIdFilterParser.java | 4 +- .../core/filters/id/NutsIdIdFilter.java | 2 +- .../filters/id/NutsJavascriptIdFilter.java | 220 ++--- ... => InternalNutsInstallStatusFilters.java} | 60 +- .../NutsInstallStatusFilterParser.java | 7 +- ...ava => InternalNutsRepositoryFilters.java} | 22 +- .../NutsRepositoryFilterParser.java | 4 +- .../version/DefaultNutsVersionFilter.java | 4 +- ...r.java => InternalNutsVersionFilters.java} | 57 +- .../filters/version/JsNutsVersionFilter.java | 84 +- .../version/NutsVersionFilterParser.java | 4 +- .../version/NutsVersionJavascriptFilter.java | 214 ++--- .../CoreNutsWorkspaceOptionsFormat.java | 4 +- .../core/format/DefaultFormatBase.java | 17 +- .../core/format/DefaultFormatBase0.java | 5 + .../format/DefaultNutsDependencyFormat.java | 12 +- .../format/DefaultNutsDescriptorFormat.java | 18 +- .../format/DefaultNutsExecCommandFormat.java | 10 +- .../core/format/DefaultNutsIdFormat.java | 18 +- .../core/format/DefaultNutsInfoFormat.java | 66 +- .../core/format/DefaultNutsObjectFormat.java | 24 +- ...mat.java => DefaultNutsVersionFormat.java} | 16 +- .../core/format/NutsFetchDisplayOptions.java | 4 +- .../core/format/NutsIdFormatHelper.java | 12 +- .../core/format/NutsObjectFormatBase.java | 5 +- .../core/format/NutsPrintIterator.java | 7 +- .../elem/DefaultNutsArrayElementBuilder.java | 6 +- .../elem/DefaultNutsElementEntryBuilder.java | 6 +- .../DefaultNutsElementFactoryContext.java | 15 +- ...ntFormat.java => DefaultNutsElements.java} | 32 +- .../format/elem/DefaultNutsObjectElement.java | 6 +- .../elem/DefaultNutsObjectElementBuilder.java | 4 +- .../format/elem/NutsElementPathFilter.java | 6 +- .../mappers/NutsElementMapperCommandLine.java | 8 +- .../elem/mappers/NutsElementMapperFile.java | 6 +- .../NutsElementMapperNutsDependency.java | 16 +- .../NutsElementMapperNutsDescriptor.java | 14 +- ...tsElementMapperNutsDescriptorProperty.java | 14 +- ...ntMapperNutsDescriptorPropertyBuilder.java | 16 +- .../NutsElementMapperNutsEnvCondition.java | 14 +- ...sElementMapperNutsEnvConditionBuilder.java | 14 +- .../elem/mappers/NutsElementMapperNutsId.java | 9 +- .../NutsElementMapperNutsIdLocation.java | 14 +- .../mappers/NutsElementMapperNutsPath.java | 2 +- ...NutsElementMapperNutsPlatformLocation.java | 2 +- .../mappers/NutsElementMapperNutsString.java | 7 +- .../mappers/NutsElementMapperNutsText.java | 9 +- .../mappers/NutsElementMapperNutsVersion.java | 9 +- .../mappers/NutsElementMapperObjReflect.java | 2 +- .../elem/mappers/NutsElementMapperPath.java | 10 +- ...son.java => DefaultJsonElementFormat.java} | 11 +- .../format/json/DefaultSearchFormatJson.java | 10 +- .../format/plain/NutsObjectFormatPlain.java | 25 +- ....java => DefaultNutsPropertiesFormat.java} | 28 +- .../props/DefaultSearchFormatProps.java | 2 +- .../format/props/NutsObjectFormatProps.java | 2 +- .../table/DefaultSearchFormatTable.java | 2 +- .../core/format/table/DefaultTableFormat.java | 71 +- .../table/DefaultTableHeaderFormat.java | 7 +- .../format/table/NutsObjectFormatTable.java | 4 +- .../format/text/AnsiPrintStreamSupport.java | 8 - .../text/DefaultNutsTextManagerModel.java | 4 +- .../text/DefaultNutsTextNodeBuilder.java | 34 +- ...TextManager.java => DefaultNutsTexts.java} | 33 +- .../text/ExtendedFormatAwarePrintWriter.java | 4 +- .../core/format/text/NutsImmutableString.java | 6 +- .../format/text/NutsTextNodeCollector.java | 9 +- .../format/text/NutsTextNodeWriterRaw.java | 12 +- .../text/NutsTextNodeWriterRenderer.java | 12 +- .../text/NutsTextNodeWriterStringer.java | 6 +- .../core/format/text/PrintStreamExt.java | 2 +- .../format/text/UnescapeOutputStream.java | 2 +- .../highlighters/BashCodeHighlighter.java | 12 +- .../CustomStyleCodeHighlighter.java | 11 +- .../highlighters/FishCodeHighlighter.java | 12 +- .../highlighters/HadraCodeHighlighter.java | 4 +- .../highlighters/JavaCodeHighlighter.java | 4 +- .../highlighters/JsonCodeHighlighter.java | 4 +- .../text/highlighters/NtfCodeHighlighter.java | 5 +- .../highlighters/PlainCodeHighlighter.java | 11 +- .../highlighters/StringReaderExtUtils.java | 16 +- .../WinCmdBlocTextHighlighter.java | 12 +- .../text/highlighters/XmlCodeHighlighter.java | 79 +- .../format/text/parser/AbstractNutsText.java | 4 +- .../text/parser/DefaultNutsTextCode.java | 10 +- ...faultNutsTextNodeResourceParserHelper.java | 8 +- .../parser/steps/AntiQuote3ParserStep.java | 5 +- .../text/parser/steps/NewLineParserStep.java | 9 +- .../text/parser/steps/PlainParserStep.java | 3 +- .../text/parser/steps/RootParserStep.java | 3 +- .../text/parser/steps/StyledParserStep.java | 4 +- .../steps/StyledParserStepCommandParser.java | 2 +- .../text/parser/steps/TitleParserStep.java | 9 +- .../DefaultNutsTextFormatTheme.java | 4 +- .../NutsTextFormatPropertiesTheme.java | 279 +----- .../NutsTextFormatThemeWrapper.java | 8 +- ...efaultNutsFormatDestructTypePredicate.java | 25 - ...Format.java => DefaultNutsTreeFormat.java} | 39 +- .../format/tree/DefaultSearchFormatTree.java | 2 +- .../nuts/runtime/core/format/tree/XNode.java | 18 +- .../format/xml/DefaultSearchFormatXml.java | 8 +- .../DefaultXmlNutsElementStreamFormat.java | 4 +- .../xml/NutsElementFactoryXmlElement.java | 17 +- .../core/format/xml/NutsObjectFormatXml.java | 4 +- .../runtime/core/format/xml/NutsXmlUtils.java | 8 +- .../runtime/core/format/yaml/SimpleYaml.java | 6 +- .../runtime/core/io/DefaultPathBuilder.java | 44 +- .../thevpc/nuts/runtime/core/io/FilePath.java | 8 +- .../runtime/core/io/NutsCompressedPath.java | 12 +- .../nuts/runtime/core/io/NutsPathBase.java | 14 +- .../nuts/runtime/core/io/NutsPathFromSPI.java | 15 +- .../runtime/core/io/NutsResourcePath.java | 16 +- .../thevpc/nuts/runtime/core/io/URLPath.java | 16 +- .../core/log/DefaultNutsLogManager.java | 88 +- .../runtime/core/log/DefaultNutsLogModel.java | 12 +- .../runtime/core/log/DefaultNutsLogger.java | 14 +- .../core/log/NutsLogPlainFormatter.java | 2 +- .../nuts/runtime/core/log/NutsLogRecord.java | 2 +- .../core/log/NutsLogRichFormatter.java | 6 +- .../nuts/runtime/core/log/NutsLogUtils.java | 3 +- .../core/model/AbstractNutsDescriptor.java | 7 +- .../core/model/CoreNutsWorkspaceOptions.java | 7 +- .../core/model/DefaultNutsArtifactCall.java | 9 + .../model/DefaultNutsArtifactCallBuilder.java | 6 + .../core/model/DefaultNutsDependency.java | 6 +- .../model/DefaultNutsDependencyBuilder.java | 16 +- .../model/DefaultNutsDescriptorBuilder.java | 16 +- .../DefaultNutsDescriptorPropertyBuilder.java | 7 +- .../core/model/DefaultNutsEnvCondition.java | 2 +- .../model/DefaultNutsEnvConditionBuilder.java | 6 + .../runtime/core/model/DefaultNutsId.java | 10 +- .../core/model/DefaultNutsIdBuilder.java | 23 +- .../core/model/DefaultNutsVersion.java | 2 +- .../parser/DefaultNutsDependencyParser.java | 29 +- .../parser/DefaultNutsDescriptorParser.java | 98 +- .../core/parser/DefaultNutsIdParser.java | 7 +- .../core/parser/DefaultNutsVersionParser.java | 6 + .../repos/DefaultNutsRepositoryManager.java | 4 +- .../repos/DefaultNutsRepositoryModel.java | 40 +- .../core/repos/NutsRepositoryUtils.java | 2 +- .../NutsWorkspaceSessionAwareImpl.java | 87 +- .../shell/AbstractWinNutsShellHelper.java | 5 +- .../runtime/core/shell/ShNutsShellHelper.java | 2 +- .../AbstractSystemTerminalAdapter.java | 2 +- ...DefaultNutsSessionTerminalFromSession.java | 17 +- .../DefaultNutsSessionTerminalFromSystem.java | 12 +- .../DefaultNutsSystemTerminalBase.java | 23 +- .../DefaultNutsSystemTerminalBaseBoot.java | 18 +- .../UnmodifiableSessionTerminal.java | 2 +- .../runtime/core/util/CoreCommonUtils.java | 6 +- .../nuts/runtime/core/util/CoreIOUtils.java | 109 ++- .../core/util/CoreNutsDependencyUtils.java | 2 +- .../nuts/runtime/core/util/CoreNutsUtils.java | 92 +- .../runtime/core/util/CoreStringUtils.java | 11 +- .../runtime/core/util/ProcessExecHelper.java | 26 +- .../gson/GsonItemSerializeManager.java | 4 +- .../optional/mslink/OptionalMsLinkHelper.java | 7 +- .../runtime/remote/RemoteNutsExecCommand.java | 4 +- .../remote/RemoteNutsSearchCommand.java | 6 +- .../runtime/remote/RemoteNutsWorkspace.java | 10 +- .../DefaultNutsConcurrentManager.java | 42 - .../DefaultNutsConcurrentModel.java | 46 - .../standalone/DefaultNutsFormatManager.java | 38 +- .../standalone/DefaultNutsStreams.java | 72 ++ .../DefaultNutsTextStyleGenerator.java | 2 +- .../standalone/DefaultNutsUtilManager.java | 67 -- .../standalone/DefaultNutsUtilModel.java | 23 - .../runtime/standalone/DefaultNutsVals.java | 24 + .../standalone/DefaultNutsWorkspace.java | 437 ++++----- .../DefaultNutsWorkspaceAppsManager.java | 43 - .../DefaultNutsWorkspaceFactory.java | 425 ++++++--- .../DefaultNutsWorkspaceListManager.java | 23 +- ...efaultNutsWorkspaceArchetypeComponent.java | 14 +- ...inimalNutsWorkspaceArchetypeComponent.java | 13 +- ...ServerNutsWorkspaceArchetypeComponent.java | 13 +- .../boot/DefaultNutsBootManager.java | 19 +- .../standalone/boot/DefaultNutsBootModel.java | 3 + .../standalone/boot/NutsBootModel.java | 9 + .../maven/AbstractMavenRepositoryHelper.java | 2 +- .../bridges/maven/LuceneIndexImporter.java | 14 +- .../bridges/maven/MavenFolderRepository.java | 14 +- .../bridges/maven/MavenRemoteRepository.java | 58 +- .../MavenRepositoryFactoryComponent.java | 34 +- .../maven/MavenRepositoryFolderHelper.java | 4 +- .../standalone/bridges/maven/MavenUtils.java | 20 +- .../standalone/bridges/maven/MvnClient.java | 2 +- .../config/DefaultCustomCommandsModel.java | 12 +- .../config/DefaultNutsIdLocation.java | 89 -- .../config/DefaultNutsIdLocationBuilder.java | 135 --- .../config/DefaultNutsIndexStore.java | 8 +- .../config/DefaultNutsPlatformModel.java | 8 +- .../DefaultNutsWorkspaceConfigManager.java | 40 +- .../DefaultNutsWorkspaceConfigModel.java | 607 ++++++++++--- .../DefaultNutsWorkspaceCurrentConfig.java | 22 +- .../DefaultNutsWorkspaceEnvManagerModel.java | 14 +- .../NutsPlatformLocationSelectComparator.java | 4 +- .../config/NutsSdkLocationComparator.java | 4 +- .../compat/v502/NutsVersionCompat502.java | 10 +- .../compat/v506/NutsVersionCompat506.java | 10 +- .../compat/v507/NutsVersionCompat507.java | 18 +- .../AbstractSyncIProcessExecHelper.java | 2 +- .../executors/ClassloaderAwareRunnable.java | 2 +- .../executors/JavaExecutorComponent.java | 36 +- .../executors/JavaExecutorOptions.java | 11 +- .../JavaSourceExecutorComponent.java | 29 +- .../executors/ProcessExecutorComponent.java | 11 +- .../DefaultNutsWorkspaceExtensionManager.java | 17 +- .../DefaultNutsWorkspaceExtensionModel.java | 36 +- .../standalone/gui/CoreNutsUtilGui.java | 8 +- .../index/NanoDBNutsIdSerializer.java | 3 +- .../CommandForIdNutsInstallerComponent.java | 2 +- .../installers/ZipInstallerComponent.java | 6 +- ...LockAction.java => AbstractNutsLocks.java} | 20 +- ...ODeleteAction.java => AbstractNutsRm.java} | 17 +- .../io/DefaultHttpTransportComponent.java | 4 +- ...ssAction.java => DefaultNutsCompress.java} | 113 +-- ...tsIOCopyAction.java => DefaultNutsCp.java} | 118 +-- ....java => DefaultNutsExecutionEntries.java} | 17 +- ...IOHashAction.java => DefaultNutsHash.java} | 46 +- .../standalone/io/DefaultNutsIOManager.java | 270 ------ .../standalone/io/DefaultNutsIOModel.java | 350 -------- .../standalone/io/DefaultNutsInputAction.java | 4 +- ...ava => DefaultNutsInputStreamMonitor.java} | 52 +- .../io/DefaultNutsInputStreams.java | 42 + ...OLockAction.java => DefaultNutsLocks.java} | 10 +- .../standalone/io/DefaultNutsPaths.java | 95 ++ .../io/DefaultNutsPrintStreams.java | 159 ++++ ...OProcessAction.java => DefaultNutsPs.java} | 29 +- .../standalone/io/DefaultNutsQuestion.java | 8 +- ...IODeleteAction.java => DefaultNutsRm.java} | 13 +- .../io/DefaultNutsStreamProgressMonitor.java | 4 +- .../io/DefaultNutsTerminalManager.java | 143 --- .../io/DefaultNutsTerminalModel.java | 203 +---- .../standalone/io/DefaultNutsTerminals.java | 73 ++ ...ultTempAction.java => DefaultNutsTmp.java} | 20 +- ...Action.java => DefaultNutsUncompress.java} | 97 +- .../standalone/io/NutsPrintStreamBase.java | 6 +- .../io/NutsPrintStreamFormatted.java | 2 +- .../standalone/io/NutsPrintStreamSystem.java | 4 +- ...NutsInputStreamProgressMonitorAdapter.java | 2 +- .../standalone/io/progress/CProgressBar.java | 10 +- .../DefaultNutsCountProgressMonitor.java | 4 +- .../manager/DefaultNutsDependencyManager.java | 93 -- .../manager/DefaultNutsDescriptorManager.java | 92 -- .../manager/DefaultNutsIdManager.java | 91 -- .../manager/DefaultNutsIdResolver.java | 44 + .../manager/DefaultNutsVersionManager.java | 67 -- .../JarDescriptorContentParserComponent.java | 96 +- .../NshDescriptorContentParserComponent.java | 18 +- .../ZipDescriptorContentParserComponent.java | 27 +- .../repos/AbstractNutsRepositoryBase.java | 2 +- .../DefaultNutsDeployRepositoryCommand.java | 2 +- ...aultNutsFetchContentRepositoryCommand.java | 2 +- ...tNutsFetchDescriptorRepositoryCommand.java | 4 +- .../repos/DefaultNutsInstalledRepository.java | 49 +- .../DefaultNutsPushRepositoryCommand.java | 2 +- .../DefaultNutsRepoFactoryComponent.java | 23 +- .../DefaultNutsRepositoryConfigModel.java | 10 +- .../DefaultNutsRepositoryUndeployCommand.java | 2 +- .../DefaultNutsSearchRepositoryCommand.java | 2 +- ...ltNutsSearchVersionsRepositoryCommand.java | 2 +- .../standalone/repos/FilesFoldersApi.java | 30 +- .../repos/FilesFoldersApiIdIterator.java | 2 +- .../repos/NutsCachedRepository.java | 10 +- .../repos/NutsHttpFolderRepository.java | 28 +- .../repos/NutsHttpSrvRepository.java | 25 +- .../repos/NutsRepositoryFolderHelper.java | 34 +- .../repos/NutsRepositoryMirroringHelper.java | 6 +- .../DefaultNutsAuthenticationAgent.java | 5 +- .../DefaultNutsWorkspaceSecurityModel.java | 2 +- .../PlainNutsAuthenticationAgent.java | 6 +- .../solvers/DefaultNutsDependencySolvers.java | 41 + .../solvers/MavenNutsDependencySolver.java | 9 +- ...rs.java => NutsDependencySolverUtils.java} | 3 +- .../util/DefaultSourceControlHelper.java | 20 +- .../standalone/util/NutsClassLoaderUtils.java | 3 +- .../util/NutsConfigurableHelper.java | 2 +- .../standalone/util/NutsJavaSdkUtils.java | 26 +- .../standalone/util/NutsWorkspaceUtils.java | 18 +- .../wscommands/NutsWorkspaceCommandBase.java | 2 +- .../deploy/AbstractNutsDeployCommand.java | 17 +- .../deploy/DefaultNutsDeployCommand.java | 75 +- .../exec/AbstractNutsExecCommand.java | 15 +- .../DefaultInternalNutsExecutableCommand.java | 12 +- .../exec/DefaultNutsArtifactExecutable.java | 4 +- .../DefaultNutsArtifactPathExecutable.java | 43 +- .../exec/DefaultNutsExecCommand.java | 15 +- .../exec/DefaultNutsOpenExecutable.java | 8 +- .../exec/DefaultNutsSystemExecutable.java | 6 +- .../exec/DefaultUnknownExecutable.java | 2 +- .../fetch/AbstractNutsFetchCommand.java | 7 +- .../fetch/DefaultNutsFetchCommand.java | 34 +- .../DefaultNutsHelpInternalExecutable.java | 23 +- .../install/AbstractNutsInstallCommand.java | 5 +- .../install/DefaultNutsInstallCommand.java | 26 +- .../DefaultNutsLicenseInternalExecutable.java | 15 +- .../push/AbstractDefaultNutsPushCommand.java | 8 +- .../search/AbstractNutsSearchCommand.java | 30 +- .../search/DefaultNutsSearchCommand.java | 64 +- .../CommandNutsWorkspaceCommandFactory.java | 6 +- .../ConfigNutsWorkspaceCommandFactory.java | 8 +- .../settings/DefaultNutsAliasExecutable.java | 8 +- ...DefaultNutsSettingsInternalExecutable.java | 2 +- .../DefaultNutsUpdateStatisticsCommand.java | 6 +- .../DefaultNutsWorkspaceCustomCommand.java | 2 +- .../alias/NutsSettingsAliasSubCommand.java | 10 +- .../backup/NutsSettingsBackupSubCommand.java | 19 +- .../NutsSettingsConnectSubCommand.java | 3 +- .../NutsSettingsDeleteFoldersSubCommand.java | 6 +- .../imports/NutsSettingsImportSubCommand.java | 8 +- .../log/NutsSettingsLogSubCommand.java | 19 +- .../subcommands/ndi/NdiScriptOptions.java | 6 +- .../ndi/NutsSettingsNdiSubCommand.java | 11 +- .../subcommands/ndi/base/BaseSystemNdi.java | 44 +- .../ndi/script/FromTemplateScriptBuilder.java | 2 +- .../subcommands/ndi/unix/AnyNixNdi.java | 4 +- .../ndi/win/WindowFreeDesktopEntryWriter.java | 3 +- .../NutsSettingsRepositorySubCommand.java | 19 +- .../user/NutsSettingsUserSubCommand.java | 48 +- .../settings/util/SettingsRepoUtils.java | 2 +- .../undeploy/AbstractNutsUndeployCommand.java | 4 +- .../undeploy/DefaultNutsUndeployCommand.java | 2 +- .../AbstractNutsUninstallCommand.java | 4 +- .../DefaultNutsUninstallCommand.java | 6 +- .../update/AbstractNutsUpdateCommand.java | 8 +- .../update/DefaultNutsUpdateCommand.java | 26 +- .../DefaultNutsVersionInternalExecutable.java | 2 +- .../DefaultNutsWelcomeInternalExecutable.java | 10 +- .../DefaultNutsWhichInternalExecutable.java | 24 +- .../net.thevpc.nuts.spi.NutsComponent | 69 ++ .../nuts/runtime/highlighter-mappings.ini | 10 +- .../thevpc/nuts/NutsApplicationContext.java | 23 +- ...ager.java => NutsApplicationContexts.java} | 31 +- .../net/thevpc/nuts/NutsApplications.java | 8 +- .../java/net/thevpc/nuts/NutsArgument.java | 2 +- .../thevpc/nuts/NutsArgumentCandidate.java | 50 +- .../net/thevpc/nuts/NutsArgumentName.java | 6 + .../thevpc/nuts/NutsArrayElementBuilder.java | 2 +- .../thevpc/nuts/NutsArtifactCallBuilder.java | 7 +- .../java/net/thevpc/nuts/NutsBootManager.java | 2 + .../net/thevpc/nuts/NutsClassLoaderNode.java | 31 +- .../nuts/NutsClassLoaderNodeBuilder.java | 19 +- .../net/thevpc/nuts/NutsCommandHistory.java | 20 +- .../nuts/NutsCommandHistoryBuilder.java | 40 - .../java/net/thevpc/nuts/NutsCommandLine.java | 15 +- .../thevpc/nuts/NutsCommandLineFormat.java | 7 + ...LineManager.java => NutsCommandLines.java} | 31 +- ...OCompressAction.java => NutsCompress.java} | 59 +- .../thevpc/nuts/NutsConcurrentManager.java | 51 -- .../{NutsIOCopyAction.java => NutsCp.java} | 91 +- .../java/net/thevpc/nuts/NutsDependency.java | 5 +- .../thevpc/nuts/NutsDependencyBuilder.java | 5 +- ...anager.java => NutsDependencyFilters.java} | 14 +- .../net/thevpc/nuts/NutsDependencyFormat.java | 5 +- .../thevpc/nuts/NutsDependencyManager.java | 78 -- .../net/thevpc/nuts/NutsDependencyParser.java | 9 +- .../java/net/thevpc/nuts/NutsDescriptor.java | 1 + .../thevpc/nuts/NutsDescriptorBuilder.java | 5 +- ...anager.java => NutsDescriptorFilters.java} | 14 +- .../net/thevpc/nuts/NutsDescriptorFormat.java | 16 +- .../thevpc/nuts/NutsDescriptorManager.java | 74 -- .../net/thevpc/nuts/NutsDescriptorParser.java | 5 +- .../nuts/NutsDescriptorPropertyBuilder.java | 6 +- .../nuts/NutsElementFactoryContext.java | 2 +- ...tsElementFormat.java => NutsElements.java} | 40 +- .../thevpc/nuts/NutsEnvConditionBuilder.java | 5 +- .../java/net/thevpc/nuts/NutsException.java | 2 +- .../thevpc/nuts/NutsExecCommandFormat.java | 7 + ...yAction.java => NutsExecutionEntries.java} | 11 +- .../main/java/net/thevpc/nuts/NutsExpr.java | 217 +++++ .../nuts/NutsExtensionNotFoundException.java | 18 +- ...utsFilterManager.java => NutsFilters.java} | 30 +- .../main/java/net/thevpc/nuts/NutsFormat.java | 4 +- .../net/thevpc/nuts/NutsFormatManager.java | 10 - .../main/java/net/thevpc/nuts/NutsGlob.java | 19 + .../{NutsIOHashAction.java => NutsHash.java} | 61 +- .../java/net/thevpc/nuts/NutsIOManager.java | 169 ---- .../src/main/java/net/thevpc/nuts/NutsId.java | 24 +- .../java/net/thevpc/nuts/NutsIdBuilder.java | 5 +- ...dFilterManager.java => NutsIdFilters.java} | 14 +- .../java/net/thevpc/nuts/NutsIdFormat.java | 9 +- .../java/net/thevpc/nuts/NutsIdLocation.java | 61 +- .../thevpc/nuts/NutsIdLocationBuilder.java | 108 --- .../java/net/thevpc/nuts/NutsIdParser.java | 5 +- ...NutsIdManager.java => NutsIdResolver.java} | 56 +- .../java/net/thevpc/nuts/NutsInfoFormat.java | 7 + ...ction.java => NutsInputStreamMonitor.java} | 38 +- .../net/thevpc/nuts/NutsInputStreams.java | 23 + ...ger.java => NutsInstallStatusFilters.java} | 14 +- .../{NutsIOLockAction.java => NutsLocks.java} | 19 +- .../main/java/net/thevpc/nuts/NutsLogger.java | 132 ++- .../java/net/thevpc/nuts/NutsLoggerOp.java | 6 +- .../thevpc/nuts/NutsMemoryPrintStream.java | 4 + .../java/net/thevpc/nuts/NutsMessage.java | 2 +- .../nuts/NutsMissingSessionException.java | 89 ++ .../thevpc/nuts/NutsObjectElementBuilder.java | 2 +- .../net/thevpc/nuts/NutsObjectFormat.java | 7 + .../main/java/net/thevpc/nuts/NutsPath.java | 49 +- .../java/net/thevpc/nuts/NutsPathBuilder.java | 16 +- .../java/net/thevpc/nuts/NutsPrintStream.java | 28 +- .../net/thevpc/nuts/NutsPrintStreams.java | 45 + .../net/thevpc/nuts/NutsPropertiesFormat.java | 6 + .../{NutsIOProcessAction.java => NutsPs.java} | 22 +- .../thevpc/nuts/NutsReadOnlyException.java | 4 +- ...anager.java => NutsRepositoryFilters.java} | 13 +- .../thevpc/nuts/NutsRepositoryManager.java | 2 +- .../{NutsIODeleteAction.java => NutsRm.java} | 22 +- .../java/net/thevpc/nuts/NutsSession.java | 193 ---- .../net/thevpc/nuts/NutsSessionTerminal.java | 13 + .../main/java/net/thevpc/nuts/NutsStream.java | 30 + .../java/net/thevpc/nuts/NutsStreams.java | 23 + .../main/java/net/thevpc/nuts/NutsString.java | 6 +- .../java/net/thevpc/nuts/NutsSupportMode.java | 2 +- .../net/thevpc/nuts/NutsSystemTerminal.java | 6 + .../java/net/thevpc/nuts/NutsTableFormat.java | 6 + .../net/thevpc/nuts/NutsTerminalManager.java | 146 --- .../main/java/net/thevpc/nuts/NutsText.java | 2 +- .../java/net/thevpc/nuts/NutsTextBuilder.java | 2 +- .../java/net/thevpc/nuts/NutsTextParser.java | 2 +- .../java/net/thevpc/nuts/NutsTextStyle.java | 77 +- .../net/thevpc/nuts/NutsTextStyleType.java | 132 ++- .../java/net/thevpc/nuts/NutsTextStyled.java | 12 +- .../java/net/thevpc/nuts/NutsTextStyles.java | 106 ++- .../{NutsTextManager.java => NutsTexts.java} | 17 +- .../{NutsTempAction.java => NutsTmp.java} | 13 +- .../java/net/thevpc/nuts/NutsTreeFormat.java | 6 + .../net/thevpc/nuts/NutsTypedFilters.java | 11 +- ...ompressAction.java => NutsUncompress.java} | 70 +- .../java/net/thevpc/nuts/NutsUtilManager.java | 28 - .../main/java/net/thevpc/nuts/NutsVal.java | 3 +- .../main/java/net/thevpc/nuts/NutsVals.java | 14 + .../java/net/thevpc/nuts/NutsVersion.java | 7 +- ...erManager.java => NutsVersionFilters.java} | 15 +- .../net/thevpc/nuts/NutsVersionFormat.java | 10 +- .../net/thevpc/nuts/NutsVersionManager.java | 58 -- .../net/thevpc/nuts/NutsVersionParser.java | 8 +- .../java/net/thevpc/nuts/NutsWorkspace.java | 60 -- .../nuts/NutsWorkspaceConfigManager.java | 33 + .../nuts/NutsWorkspaceExtensionManager.java | 16 +- .../nuts/NutsWorkspaceLocationManager.java | 2 +- .../net/thevpc/nuts/boot/NutsApiUtils.java | 36 +- .../thevpc/nuts/boot/NutsBootWorkspace.java | 97 +- .../nuts/boot/PrivateNutsArgumentImpl.java | 4 +- .../nuts/boot/PrivateNutsUtilApplication.java | 22 +- .../nuts/boot/PrivateNutsUtilClassLoader.java | 33 +- .../NutsComponentScope.java} | 47 +- .../nuts/spi/NutsComponentScopeType.java | 129 +++ .../thevpc/nuts/spi/NutsDependencySolver.java | 12 + .../nuts/spi/NutsDependencySolvers.java | 19 + .../thevpc/nuts/{ => spi}/NutsLogManager.java | 40 +- .../java/net/thevpc/nuts/spi/NutsPaths.java | 38 + .../NutsTerminals.java} | 60 +- .../ext/term/NutsJLineCommandHistory.java | 56 +- .../nuts/ext/term/NutsJLineCompleter.java | 2 +- .../nuts/ext/term/NutsJLineTerminal.java | 40 +- .../thevpc/nuts/lib/ssh/SShConnection.java | 3 +- .../net/thevpc/nuts/lib/ssh/SshNutsPath.java | 18 +- .../lib/template/DefaultProjectTemplate.java | 8 +- .../net/thevpc/nuts/lib/template/IOUtils.java | 5 +- .../nuts/lib/template/ValidatorFactory.java | 3 +- .../core/test/blackbox/Test01_CreateTest.java | 283 +++++- .../Test03_CreateLayoutLinuxTest.java | 8 +- .../core/test/blackbox/Test06_UpdateTest.java | 9 +- .../test/blackbox/Test09_FindLinuxTest.java | 2 +- .../test/blackbox/Test10_ExecURLTest.java | 30 +- .../core/test/blackbox/Test11_LogTest.java | 3 +- .../core/test/blackbox/Test12_CopyTest.java | 11 +- .../nuts/core/test/blackbox/Test13_Color.java | 12 +- .../test/blackbox/Test14_Commandline.java | 2 +- .../nuts/core/test/blackbox/Test15_Yaml.java | 5 +- .../nuts/core/test/blackbox/Test17_Json.java | 18 +- .../nuts/core/test/blackbox/Test19_expr.java | 94 ++ .../bundles/ntf/Test07_ColorfulStream.java | 6 +- .../test/whitebox/Test01_TestInputSource.java | 8 +- .../core/test/whitebox/Test06_CacheURL.java | 6 +- .../whitebox/Test09_VersionIntervals.java | 7 +- .../test/whitebox/Test10_ElementPath.java | 320 +++---- .../core/test/whitebox/Test12_ParseNTF.java | 18 +- .../nuts/core/test/whitebox/TestDev.java | 7 +- .../thevpc/nuts/toolbox/ncode/FileLookup.java | 3 +- .../ncode/processors/JavaSourceFormatter.java | 11 +- .../ncode/processors/PathSourceFormatter.java | 3 +- .../nuts/toolbox/ndb/derby/DerbyService.java | 9 +- .../nuts/toolbox/ndb/derby/DerbyUtils.java | 8 +- .../nuts/toolbox/ndb/derby/NDerbyMain.java | 8 +- .../nuts/toolbox/ndb/derby/RunningDerby.java | 2 +- .../nuts/toolbox/ndb/nmysql/NMysqlMain.java | 6 +- .../nmysql/local/LocalMysqlConfigService.java | 10 +- .../LocalMysqlDatabaseConfigService.java | 10 +- .../ndb/nmysql/remote/CachedMapFile.java | 14 +- .../remote/RemoteMysqlConfigService.java | 11 +- .../RemoteMysqlDatabaseConfigService.java | 82 +- .../NutsIndexSubscriberListManager.java | 8 +- .../thevpc/nuts/indexer/NutsIndexerUtils.java | 10 +- .../nuts/indexer/services/DataService.java | 10 +- .../services/NutsComponentController.java | 20 +- .../indexer/services/RefreshDataService.java | 2 +- .../docusaurus/DocusaurusContentFile.java | 3 +- .../toolbox/docusaurus/DocusaurusCtrl.java | 34 +- .../toolbox/docusaurus/DocusaurusFolder.java | 9 +- .../toolbox/docusaurus/DocusaurusProject.java | 14 +- .../docusaurus/DocusaurusTreeTransform.java | 9 +- .../nuts/toolbox/njob/JobServiceCmd.java | 59 +- .../nuts/toolbox/njob/NJobConfigStore.java | 5 +- .../thevpc/nuts/toolbox/njob/NJobMain.java | 8 +- .../thevpc/nuts/toolbox/njob/NJobsSubCmd.java | 62 +- .../nuts/toolbox/njob/NProjectsSubCmd.java | 18 +- .../nuts/toolbox/njob/NTasksSubCmd.java | 20 +- .../thevpc/nuts/toolbox/mvn/NutsMvnMain.java | 2 +- .../nuts/toolbox/noapi/NOpenAPIService.java | 28 +- .../nutsserver/NutsServerComponent.java | 5 +- .../toolbox/nutsserver/NutsServerMain.java | 12 +- .../nutsserver/admin/AdminServerRunnable.java | 22 +- .../admin/NutsAdminServerComponent.java | 2 +- .../http/NutsHttpServerComponent.java | 2 +- .../http/commands/DeployFacadeCommand.java | 28 +- .../http/commands/ExecFacadeCommand.java | 3 +- .../http/commands/GetMavenFacadeCommand.java | 13 +- .../http/commands/VersionFacadeCommand.java | 8 +- .../nuts/toolbox/nsh/AbstractNshBuiltin.java | 5 +- .../java/net/thevpc/nuts/toolbox/nsh/Nsh.java | 4 +- .../thevpc/nuts/toolbox/nsh/NshEvaluator.java | 21 +- .../nuts/toolbox/nsh/NutsErrorHandler.java | 4 +- .../nuts/toolbox/nsh/SimpleNshBuiltin.java | 3 +- .../bundles/collections/EvictingQueue.java | 69 ++ .../bundles/jshell/AbstractJShellContext.java | 23 +- .../jshell/DefaultJShellExecutionContext.java | 2 +- .../jshell/DefaultJShellOptionsParser.java | 6 +- .../toolbox/nsh/bundles/jshell/JShell.java | 24 +- .../nsh/bundles/jshell/JShellContext.java | 4 - .../nsh/bundles/jshell/NshAutoCompleter.java | 4 +- .../nsh/bundles/jshell/parser/Yaccer.java | 4 +- .../nuts/toolbox/nsh/cmds/AliasCommand.java | 81 +- .../toolbox/nsh/cmds/AutocompleteCommand.java | 44 +- .../toolbox/nsh/cmds/BaseNameCommand.java | 50 +- .../nuts/toolbox/nsh/cmds/CatCommand.java | 165 +++- .../nuts/toolbox/nsh/cmds/CdCommand.java | 25 +- .../nuts/toolbox/nsh/cmds/ChmodCommand.java | 106 +-- .../nuts/toolbox/nsh/cmds/CommandCommand.java | 32 +- .../nuts/toolbox/nsh/cmds/CpCommand.java | 72 +- .../nuts/toolbox/nsh/cmds/DateCommand.java | 231 ++--- .../nuts/toolbox/nsh/cmds/DirNameCommand.java | 13 +- .../nuts/toolbox/nsh/cmds/EchoCommand.java | 10 +- .../nuts/toolbox/nsh/cmds/EnableCommand.java | 17 +- .../nuts/toolbox/nsh/cmds/EnvCommand.java | 68 +- .../nuts/toolbox/nsh/cmds/ExitCommand.java | 37 +- .../nuts/toolbox/nsh/cmds/FalseCommand.java | 27 +- .../nuts/toolbox/nsh/cmds/GrepCommand.java | 111 ++- .../nuts/toolbox/nsh/cmds/HeadCommand.java | 12 +- .../nuts/toolbox/nsh/cmds/HelpCommand.java | 4 +- .../nuts/toolbox/nsh/cmds/HistoryCommand.java | 74 +- .../nuts/toolbox/nsh/cmds/JpsCommand.java | 111 +-- .../nuts/toolbox/nsh/cmds/JsonCommand.java | 38 +- .../nuts/toolbox/nsh/cmds/LoginCommand.java | 24 +- .../nuts/toolbox/nsh/cmds/LogoutCommand.java | 13 +- .../nuts/toolbox/nsh/cmds/LsCommand.java | 37 +- .../nuts/toolbox/nsh/cmds/MkdirCommand.java | 34 +- .../nuts/toolbox/nsh/cmds/PropsCommand.java | 40 +- .../nuts/toolbox/nsh/cmds/PwdCommand.java | 33 +- .../nuts/toolbox/nsh/cmds/RmCommand.java | 8 +- .../nuts/toolbox/nsh/cmds/SetCommand.java | 40 +- .../nuts/toolbox/nsh/cmds/ShowerrCommand.java | 20 +- .../nuts/toolbox/nsh/cmds/SourceCommand.java | 11 +- .../nuts/toolbox/nsh/cmds/SshCommand.java | 2 +- .../nuts/toolbox/nsh/cmds/TailCommand.java | 5 +- .../nuts/toolbox/nsh/cmds/TestCommand.java | 4 +- .../nuts/toolbox/nsh/cmds/TrueCommand.java | 27 +- .../nuts/toolbox/nsh/cmds/TypeCommand.java | 78 +- .../nuts/toolbox/nsh/cmds/UnaliasCommand.java | 44 +- .../nuts/toolbox/nsh/cmds/UnameCommand.java | 11 +- .../nuts/toolbox/nsh/cmds/UnsetCommand.java | 40 +- .../nuts/toolbox/nsh/cmds/UnzipCommand.java | 78 +- .../nuts/toolbox/nsh/cmds/VersionCommand.java | 8 +- .../nuts/toolbox/nsh/cmds/WgetCommand.java | 37 +- .../nuts/toolbox/nsh/cmds/WhoamiCommand.java | 110 ++- .../nuts/toolbox/nsh/cmds/XmlCommand.java | 58 +- .../nuts/toolbox/nsh/cmds/ZipCommand.java | 5 +- .../toolbox/nsh/options/CommandNonOption.java | 5 +- .../nuts/toolbox/nsh/util/ColumnRuler.java | 31 + .../nuts/toolbox/nsh/util/RowFilter.java | 35 + .../nuts/toolbox/nsh/util/ShellHelper.java | 7 +- .../net/thevpc/nuts/toolbox/nsh/cmd/grep.ntf | 12 + .../nuts/toolbox/nsh/test/TestExportVar.java | 19 +- .../nuts/toolbox/ntemplate/NTemplateMain.java | 9 +- .../ntemplate/filetemplate/FileTemplater.java | 2 +- .../filetemplate/eval/FtexEvaluator.java | 3 +- .../toolbox/ntomcat/local/LocalTomcat.java | 15 +- .../local/LocalTomcatAppConfigService.java | 12 +- .../local/LocalTomcatConfigService.java | 145 +-- .../local/LocalTomcatDomainConfigService.java | 5 +- .../local/LocalTomcatLogLineVisitor.java | 3 +- .../toolbox/ntomcat/remote/RemoteTomcat.java | 11 +- .../remote/RemoteTomcatAppConfigService.java | 17 +- .../remote/RemoteTomcatConfigService.java | 11 +- .../util/ApacheTomcatRepositoryModel.java | 15 +- .../toolbox/ntomcat/util/RunningTomcat.java | 2 +- .../toolbox/ntomcat/util/TomcatUtils.java | 9 +- .../nversion/ExePathVersionResolver.java | 8 +- .../nversion/JarPathVersionResolver.java | 43 +- .../MavenFolderPathVersionResolver.java | 13 +- .../nuts/toolbox/nversion/NVersionMain.java | 35 +- .../nuts/toolbox/nwork/ProjectService.java | 53 +- .../nuts/toolbox/nwork/WorkspaceService.java | 79 +- .../nwork/filescanner/FileScanner.java | 121 ++- .../filescanner/eval/DefaultContext.java | 22 - .../nwork/filescanner/eval/Evaluator.java | 20 - .../filescanner/eval/SimpleEvaluator.java | 653 -------------- .../nwork/filescanner/eval/SyntaxParser.java | 234 ----- .../nwork/filescanner/eval/TokenIterator.java | 143 --- .../tags/BackupIgnoreTagScanner.java | 7 +- .../filescanner/tags/GitIgnoreTagScanner.java | 8 +- .../filescanner/tags/PathFilterList.java | 28 +- 701 files changed, 11622 insertions(+), 11419 deletions(-) create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/EvictingIntQueue.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceModel.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultDefaultNutsApplicationContexts.java delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsArgumentCandidateBuilder.java rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/{DefaultNutsCommandLineManager.java => DefaultNutsCommandLines.java} (72%) delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/NutsCommandHistoryBuilderImpl.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultFctNode.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultLiteralNode.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultNutsExpr.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultOpNode.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultVarNode.java rename {toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner => core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core}/eval/EvalUtils.java (67%) create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/NutsExprWithCache.java rename toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/Token.java => core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/NutsToken.java (68%) create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/OpImpl.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/SyntaxParser.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/TokenIterator.java rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/{DefaultNutsFilterManager.java => DefaultNutsFilters.java} (67%) delete mode 100755 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsIdMultiFilter.java delete mode 100755 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsTokenFilter.java delete mode 100755 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/NutsIdAndNutsDependencyFilterItem.java rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/{InternalNutsDependencyFilterManager.java => InternalNutsDependencyFilters.java} (78%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/{InternalNutsDescriptorFilterManager.java => InternalNutsDescriptorFilters.java} (75%) delete mode 100755 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorJavascriptFilter.java rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/{InternalNutsIdFilterManager.java => InternalNutsIdFilters.java} (69%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/installstatus/{InternalNutsInstallStatusFilterManager.java => InternalNutsInstallStatusFilters.java} (66%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/repository/{InternalNutsRepositoryFilterManager.java => InternalNutsRepositoryFilters.java} (88%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/{InternalNutsVersionFilterManager.java => InternalNutsVersionFilters.java} (63%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/{DefaultVersionFormat.java => DefaultNutsVersionFormat.java} (88%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/{DefaultNutsElementFormat.java => DefaultNutsElements.java} (94%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/json/{SimpleJson.java => DefaultJsonElementFormat.java} (98%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/{DefaultPropertiesFormat.java => DefaultNutsPropertiesFormat.java} (89%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/{DefaultNutsTextManager.java => DefaultNutsTexts.java} (94%) delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultNutsFormatDestructTypePredicate.java rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/{DefaultTreeFormat.java => DefaultNutsTreeFormat.java} (86%) delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsConcurrentManager.java delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsConcurrentModel.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsStreams.java delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsUtilManager.java delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsUtilModel.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsVals.java delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceAppsManager.java delete mode 100755 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIdLocation.java delete mode 100755 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIdLocationBuilder.java rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{AbstractNutsIOLockAction.java => AbstractNutsLocks.java} (70%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{AbstractNutsIODeleteAction.java => AbstractNutsRm.java} (76%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{DefaultNutsIOCompressAction.java => DefaultNutsCompress.java} (84%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{DefaultNutsIOCopyAction.java => DefaultNutsCp.java} (86%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{DefaultNutsExecutionEntryAction.java => DefaultNutsExecutionEntries.java} (81%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{DefaultNutsIOHashAction.java => DefaultNutsHash.java} (81%) delete mode 100755 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOManager.java delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOModel.java rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{DefaultNutsMonitorAction.java => DefaultNutsInputStreamMonitor.java} (80%) create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsInputStreams.java rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{DefaultNutsIOLockAction.java => DefaultNutsLocks.java} (94%) create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsPaths.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsPrintStreams.java rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{DefaultNutsIOProcessAction.java => DefaultNutsPs.java} (88%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{DefaultNutsIODeleteAction.java => DefaultNutsRm.java} (91%) delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminalManager.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminals.java rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{DefaultTempAction.java => DefaultNutsTmp.java} (85%) rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/{DefaultNutsIOUncompressAction.java => DefaultNutsUncompress.java} (86%) delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsDependencyManager.java delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsDescriptorManager.java delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsIdManager.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsIdResolver.java delete mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsVersionManager.java create mode 100644 core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/DefaultNutsDependencySolvers.java rename core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/{NutsDependencySolvers.java => NutsDependencySolverUtils.java} (86%) rename core/nuts/src/main/java/net/thevpc/nuts/{NutsWorkspaceAppsManager.java => NutsApplicationContexts.java} (68%) delete mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsCommandHistoryBuilder.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsCommandLineManager.java => NutsCommandLines.java} (79%) rename core/nuts/src/main/java/net/thevpc/nuts/{NutsIOCompressAction.java => NutsCompress.java} (81%) delete mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsConcurrentManager.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsIOCopyAction.java => NutsCp.java} (81%) rename core/nuts/src/main/java/net/thevpc/nuts/{NutsDependencyFilterManager.java => NutsDependencyFilters.java} (84%) delete mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyManager.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsDescriptorFilterManager.java => NutsDescriptorFilters.java} (83%) delete mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorManager.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsElementFormat.java => NutsElements.java} (88%) rename core/nuts/src/main/java/net/thevpc/nuts/{NutsExecutionEntryAction.java => NutsExecutionEntries.java} (84%) create mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsExpr.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsFilterManager.java => NutsFilters.java} (86%) create mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsGlob.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsIOHashAction.java => NutsHash.java} (75%) delete mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsIOManager.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsIdFilterManager.java => NutsIdFilters.java} (79%) delete mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsIdLocationBuilder.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsIdManager.java => NutsIdResolver.java} (54%) rename core/nuts/src/main/java/net/thevpc/nuts/{NutsMonitorAction.java => NutsInputStreamMonitor.java} (77%) create mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsInputStreams.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsInstallStatusFilterManager.java => NutsInstallStatusFilters.java} (75%) rename core/nuts/src/main/java/net/thevpc/nuts/{NutsIOLockAction.java => NutsLocks.java} (86%) create mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsMissingSessionException.java create mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsPrintStreams.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsIOProcessAction.java => NutsPs.java} (84%) rename core/nuts/src/main/java/net/thevpc/nuts/{NutsRepositoryFilterManager.java => NutsRepositoryFilters.java} (73%) rename core/nuts/src/main/java/net/thevpc/nuts/{NutsIODeleteAction.java => NutsRm.java} (82%) create mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsStreams.java delete mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsTerminalManager.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsTextManager.java => NutsTexts.java} (74%) rename core/nuts/src/main/java/net/thevpc/nuts/{NutsTempAction.java => NutsTmp.java} (83%) rename core/nuts/src/main/java/net/thevpc/nuts/{NutsIOUncompressAction.java => NutsUncompress.java} (78%) delete mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsUtilManager.java create mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsVals.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsVersionFilterManager.java => NutsVersionFilters.java} (74%) delete mode 100644 core/nuts/src/main/java/net/thevpc/nuts/NutsVersionManager.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsDefaultArgumentCandidate.java => spi/NutsComponentScope.java} (64%) mode change 100755 => 100644 create mode 100644 core/nuts/src/main/java/net/thevpc/nuts/spi/NutsComponentScopeType.java create mode 100644 core/nuts/src/main/java/net/thevpc/nuts/spi/NutsDependencySolvers.java rename core/nuts/src/main/java/net/thevpc/nuts/{ => spi}/NutsLogManager.java (69%) create mode 100644 core/nuts/src/main/java/net/thevpc/nuts/spi/NutsPaths.java rename core/nuts/src/main/java/net/thevpc/nuts/{NutsArgumentCandidateBuilder.java => spi/NutsTerminals.java} (58%) create mode 100644 test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test19_expr.java create mode 100644 toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/collections/EvictingQueue.java create mode 100644 toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/ColumnRuler.java create mode 100644 toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/RowFilter.java delete mode 100644 toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/DefaultContext.java delete mode 100644 toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/Evaluator.java delete mode 100644 toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/SimpleEvaluator.java delete mode 100644 toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/SyntaxParser.java delete mode 100644 toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/TokenIterator.java diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/ClassMap.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/ClassMap.java index 4edaabc65..992016604 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/ClassMap.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/ClassMap.java @@ -95,6 +95,14 @@ public static Class[] findClassHierarchy(Class clazz, Class baseType) { return result.toArray(new Class[result.size()]); } + public Set keySet() { + return new HashSet(values.keySet()); + } + + public Collection values() { + return values.values(); + } + public V put(Class classKey, V value) { cachedValues.clear(); return values.put(classKey, value); @@ -208,4 +216,7 @@ public void clear() { cachedHierarchy.clear(); } + public int size() { + return values.size(); + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/EvictingIntQueue.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/EvictingIntQueue.java new file mode 100644 index 000000000..06e23c71e --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/EvictingIntQueue.java @@ -0,0 +1,66 @@ +package net.thevpc.nuts.runtime.bundles.collections; + +import java.util.Arrays; + +public class EvictingIntQueue { + private int from=0; + private int len; + private int[] values; + + public EvictingIntQueue(int max) { + this.values=new int[max]; + } + + public void clear() { + from=0; + len=0; + } + + public int size() { + return len; + } + + public int get(int pos) { + if(pos>=0 && pos0){ + sb.append(","); + } + sb.append(get(i)); + } + sb.append("}"); + return sb.toString(); + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/EvictingQueue.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/EvictingQueue.java index d6b4c7247..ce469e2b4 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/EvictingQueue.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/collections/EvictingQueue.java @@ -1,32 +1,69 @@ package net.thevpc.nuts.runtime.bundles.collections; -import java.util.LinkedList; +import java.util.AbstractList; +import java.util.Arrays; -public class EvictingQueue { - int max; - LinkedList values = new LinkedList<>(); +public class EvictingQueue extends AbstractList{ + private int from=0; + private int len; + private Object[] values; public EvictingQueue(int max) { - this.max = max; + this.values=new Object[max]; } public void clear() { - values.clear(); + from=0; + len=0; } public int size() { - return values.size(); + return len; } public T get(int pos) { - return values.get(pos); + if(pos>=0 && pos= max) { - values.removeFirst(); + + public boolean add(T t) { + int pos=(from+len)%values.length; + values[pos]=t; + if(len0){ + sb.append(","); + } + sb.append(get(i)); + } + sb.append("}"); + return sb.toString(); + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/common/JavascriptHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/common/JavascriptHelper.java index 439a0c7b5..d9014bb62 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/common/JavascriptHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/common/JavascriptHelper.java @@ -1,181 +1,181 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
- *

- * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== - */ -package net.thevpc.nuts.runtime.bundles.common; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.bundles.string.GlobUtils; -import net.thevpc.nuts.runtime.core.model.DefaultNutsVersion; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; -import java.util.*; -import java.util.regex.Pattern; - -/** - * - * @author thevpc - */ -public class JavascriptHelper { - - public List blacklistClassNamePatterns = new ArrayList<>(); - private ScriptEngine engine; - private final NutsSession session; - - private final Set blacklistClassNames = new HashSet<>( - Arrays.asList( - "java.io.File", - "java.lang.Process", - "java.lang.System", - "java.lang.Thread" - ) - ); - - public JavascriptHelper(String code, String initExprs, Set blacklist, Object util, NutsSession session) { - this.session = session; - if (blacklist == null) { - blacklistClassNames.addAll(Arrays.asList( - "java.io.File", - "java.lang.Process", - "java.lang.System", - "java.lang.Thread" - )); - } else { - for (String s : blacklist) { - if (s.contains("*")) { - blacklistClassNamePatterns.add(GlobUtils.ofExact(s)); - } else { - blacklistClassNames.add(s); - } - } - } - if (code == null) { - throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("illegal js filter : empty content")); - } - if (!code.contains("return")) { - throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("js filter must contain a return clause")); - } - try { - engine = createScriptEngine(); - } catch (Exception ex) { - engine = createManagerJdk(); - } - try { - if (NutsBlankable.isBlank(initExprs)) { - initExprs = ""; - } - engine.eval("function accept(x) { " + initExprs + code + " }"); - if (util == null) { - util = new NutScriptUtil(session); - } - engine.put("util", util); - } catch (ScriptException e) { - throw new NutsParseException(session, NutsMessage.plain("javascript execution failed"), e); - } - } - - public void createEngine(String code, String initExprs) { - - } - - private ScriptEngine createScriptEngine() { - jdk.nashorn.api.scripting.NashornScriptEngineFactory f = new jdk.nashorn.api.scripting.NashornScriptEngineFactory(); - return f.getScriptEngine(new jdk.nashorn.api.scripting.ClassFilter() { - @Override - public boolean exposeToScripts(String s) { - if (blacklistClassNames.contains(s)) { - return false; - } - for (Pattern pattern : blacklistClassNamePatterns) { - if (pattern.matcher(s).matches()) { - return false; - } - } - return true; - } - }); - } - - private ScriptEngine createManagerJdk() { - ScriptEngineManager engineManager - = new ScriptEngineManager(); - return engineManager.getEngineByName("nashorn"); - } - - public boolean accept(Object id) { - engine.put("x", id); - try { - return Boolean.TRUE.equals(engine.eval("accept(x);")); - } catch (ScriptException e) { - throw new NutsParseException(session, NutsMessage.plain("javascript execution failed"), e); - } - } - - public static class NutScriptUtil { - - NutsSession session; - - public NutScriptUtil(NutsSession session) { - this.session = session; - } - - public boolean matches(Object value, String pattern) { - if (value == null) { - value = ""; - } - if (value instanceof String) { - if (pattern == null) { - pattern = ""; - } - return GlobUtils.ofContains(pattern).matcher(value.toString()).matches(); - } - if (NutsBlankable.isBlank(pattern)) { - return NutsBlankable.isBlank(value.toString()); - } - if (value instanceof NutsId) { - NutsIdFilter f = session.id().filter().byExpression(pattern); - return f.acceptId((NutsId) value, session); - } - if (value instanceof NutsDependency) { - NutsDependencyFilter f = session.dependency().filter().byExpression(pattern); - //TODO, how to pass parent Id for dependency? - NutsId from = null; - return f == null || f.acceptDependency(from, (NutsDependency) value, session); - } - if (value instanceof NutsVersion) { - NutsVersionFilter f = session.version().filter().byExpression(pattern); - return f == null || f.acceptVersion((NutsVersion) value, session); - } - return true; - } - - public int compareVersions(String v1, String v2) { - return DefaultNutsVersion.compareVersions(v1, v2); - } - - } -} +///** +// * ==================================================================== +// * Nuts : Network Updatable Things Service +// * (universal package manager) +// *
+// * is a new Open Source Package Manager to help install packages +// * and libraries for runtime execution. Nuts is the ultimate companion for +// * maven (and other build managers) as it helps installing all package +// * dependencies at runtime. Nuts is not tied to java and is a good choice +// * to share shell scripts and other 'things' . Its based on an extensible +// * architecture to help supporting a large range of sub managers / repositories. +// * +// *
+// *

+// * Copyright [2020] [thevpc] +// * Licensed under the Apache License, Version 2.0 (the "License"); you may +// * not use this file except in compliance with the License. You may obtain a +// * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// * either express or implied. See the License for the specific language +// * governing permissions and limitations under the License. +// *
+// * ==================================================================== +// */ +//package net.thevpc.nuts.runtime.bundles.common; +// +//import net.thevpc.nuts.*; +//import net.thevpc.nuts.runtime.bundles.string.GlobUtils; +//import net.thevpc.nuts.runtime.core.model.DefaultNutsVersion; +// +//import javax.script.ScriptEngine; +//import javax.script.ScriptEngineManager; +//import javax.script.ScriptException; +//import java.util.*; +//import java.util.regex.Pattern; +// +///** +// * +// * @author thevpc +// */ +//public class JavascriptHelper { +// +// public List blacklistClassNamePatterns = new ArrayList<>(); +// private ScriptEngine engine; +// private final NutsSession session; +// +// private final Set blacklistClassNames = new HashSet<>( +// Arrays.asList( +// "java.io.File", +// "java.lang.Process", +// "java.lang.System", +// "java.lang.Thread" +// ) +// ); +// +// public JavascriptHelper(String code, String initExprs, Set blacklist, Object util, NutsSession session) { +// this.session = session; +// if (blacklist == null) { +// blacklistClassNames.addAll(Arrays.asList( +// "java.io.File", +// "java.lang.Process", +// "java.lang.System", +// "java.lang.Thread" +// )); +// } else { +// for (String s : blacklist) { +// if (s.contains("*")) { +// blacklistClassNamePatterns.add(GlobUtils.ofExact(s)); +// } else { +// blacklistClassNames.add(s); +// } +// } +// } +// if (code == null) { +// throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("illegal js filter : empty content")); +// } +// if (!code.contains("return")) { +// throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("js filter must contain a return clause")); +// } +// try { +// engine = createScriptEngine(); +// } catch (Exception ex) { +// engine = createManagerJdk(); +// } +// try { +// if (NutsBlankable.isBlank(initExprs)) { +// initExprs = ""; +// } +// engine.eval("function accept(x) { " + initExprs + code + " }"); +// if (util == null) { +// util = new NutScriptUtil(session); +// } +// engine.put("util", util); +// } catch (ScriptException e) { +// throw new NutsParseException(session, NutsMessage.plain("javascript execution failed"), e); +// } +// } +// +// public void createEngine(String code, String initExprs) { +// +// } +// +// private ScriptEngine createScriptEngine() { +// jdk.nashorn.api.scripting.NashornScriptEngineFactory f = new jdk.nashorn.api.scripting.NashornScriptEngineFactory(); +// return f.getScriptEngine(new jdk.nashorn.api.scripting.ClassFilter() { +// @Override +// public boolean exposeToScripts(String s) { +// if (blacklistClassNames.contains(s)) { +// return false; +// } +// for (Pattern pattern : blacklistClassNamePatterns) { +// if (pattern.matcher(s).matches()) { +// return false; +// } +// } +// return true; +// } +// }); +// } +// +// private ScriptEngine createManagerJdk() { +// ScriptEngineManager engineManager +// = new ScriptEngineManager(); +// return engineManager.getEngineByName("nashorn"); +// } +// +// public boolean accept(Object id) { +// engine.put("x", id); +// try { +// return Boolean.TRUE.equals(engine.eval("accept(x);")); +// } catch (ScriptException e) { +// throw new NutsParseException(session, NutsMessage.plain("javascript execution failed"), e); +// } +// } +// +// public static class NutScriptUtil { +// +// NutsSession session; +// +// public NutScriptUtil(NutsSession session) { +// this.session = session; +// } +// +// public boolean matches(Object value, String pattern) { +// if (value == null) { +// value = ""; +// } +// if (value instanceof String) { +// if (pattern == null) { +// pattern = ""; +// } +// return GlobUtils.ofContains(pattern).matcher(value.toString()).matches(); +// } +// if (NutsBlankable.isBlank(pattern)) { +// return NutsBlankable.isBlank(value.toString()); +// } +// if (value instanceof NutsId) { +// NutsIdFilter f = NutsIdFilters.of(session).byExpression(pattern); +// return f.acceptId((NutsId) value, session); +// } +// if (value instanceof NutsDependency) { +// NutsDependencyFilter f = NutsDependencyFilters.of(session).byExpression(pattern); +// //TODO, how to pass parent Id for dependency? +// NutsId from = null; +// return f == null || f.acceptDependency(from, (NutsDependency) value, session); +// } +// if (value instanceof NutsVersion) { +// NutsVersionFilter f = NutsVersionFilters.of(session).byExpression(pattern); +// return f == null || f.acceptVersion((NutsVersion) value, session); +// } +// return true; +// } +// +// public int compareVersions(String v1, String v2) { +// return DefaultNutsVersion.compareVersions(v1, v2); +// } +// +// } +//} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/http/SimpleHttpClient.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/http/SimpleHttpClient.java index 849904420..7a68218c9 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/http/SimpleHttpClient.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/http/SimpleHttpClient.java @@ -96,7 +96,7 @@ public SimpleHttpClient setReadTimeout(int readTimeout) { } private void readHeader() { - NutsPath info = session.io().path(url); + NutsPath info = NutsPath.of(url,session); this.contentEncoding = info.getContentEncoding(); this.contentType = info.getContentType(); this.contentLength = info.getContentLength(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/FolderNutIdIterator.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/FolderNutIdIterator.java index d15567448..305c1d5a2 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/FolderNutIdIterator.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/FolderNutIdIterator.java @@ -92,7 +92,7 @@ public boolean hasNext() { while (!stack.isEmpty()) { PathAndDepth file = stack.pop(); if (Files.isDirectory(file.path)) { - session.getTerminal().printProgress("%-8s %s", "search",session.io().path(file.path.toString()).toCompressedForm()); + session.getTerminal().printProgress("%-8s %s", "search",NutsPath.of(file.path,session).toCompressedForm()); visitedFoldersCount++; boolean deep = file.depth < maxDepth; if (Files.isDirectory(file.path)) { @@ -102,7 +102,7 @@ public boolean accept(Path pathname) throws IOException { try { return (deep && Files.isDirectory(pathname)) || model.isDescFile(pathname); } catch (Exception ex) { - session.log().of(FolderNutIdIterator.class).with().session(session).level(Level.FINE).error(ex) + NutsLoggerOp.of(FolderNutIdIterator.class,session).level(Level.FINE).error(ex) .log(NutsMessage.jstyle("unable to test desc file {0}", pathname)); return false; } @@ -119,7 +119,7 @@ public boolean accept(Path pathname) throws IOException { } } } catch (IOException ex) { - session.log().of(FolderNutIdIterator.class).with().session(session).level(Level.FINEST).error(ex) + NutsLoggerOp.of(FolderNutIdIterator.class,session).level(Level.FINEST).error(ex) .log(NutsMessage.jstyle("unable to iterate {0}", file.path)); } } @@ -129,7 +129,7 @@ public boolean accept(Path pathname) throws IOException { try { t = model.parseId(file.path, rootFolder, filter, repository, session); } catch (Exception ex) { - session.log().of(FolderNutIdIterator.class).with().session(session).level(Level.FINEST).error(ex) + NutsLoggerOp.of(FolderNutIdIterator.class,session).level(Level.FINEST).error(ex) .log(NutsMessage.jstyle("unable to parse id from file {0}", file.path)); } if (t != null) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/FolderObjectIterator.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/FolderObjectIterator.java index de2c8089c..1abd4b86a 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/FolderObjectIterator.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/FolderObjectIterator.java @@ -83,7 +83,7 @@ public FolderObjectIterator(String name,Path folder, Predicate filter, int ma } this.folder=folder; stack.push(new PathAndDepth(folder, 0)); - LOG = session.log().of(DefaultNutsInstalledRepository.class); + LOG = NutsLogger.of(DefaultNutsInstalledRepository.class,session); } @Override @@ -92,7 +92,7 @@ public boolean hasNext() { while (!stack.isEmpty()) { PathAndDepth file = stack.pop(); if (Files.isDirectory(file.path)) { - session.getTerminal().printProgress("%-8s %s","browse",session.io().path(file.path.toString()).toCompressedForm()); + session.getTerminal().printProgress("%-8s %s","browse",NutsPath.of(file.path,session).toCompressedForm()); visitedFoldersCount++; boolean deep = maxDepth < 0 || file.depth < maxDepth; if (Files.isDirectory(file.path)) { @@ -102,7 +102,7 @@ public boolean accept(Path pathname) throws IOException { try { return (deep && Files.isDirectory(pathname)) || model.isObjectFile(pathname); } catch (Exception ex) { - session.log().of(FolderObjectIterator.class).with().session(session).level(Level.FINE).error(ex) + NutsLoggerOp.of(FolderObjectIterator.class,session).level(Level.FINE).error(ex) .log(NutsMessage.jstyle("Unable to test desk file {0}" ,pathname)); return false; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/NutsStreamOrPath.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/NutsStreamOrPath.java index 3299fc666..4033df6c8 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/NutsStreamOrPath.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/NutsStreamOrPath.java @@ -6,7 +6,6 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.Arrays; public class NutsStreamOrPath { @@ -36,6 +35,22 @@ public static NutsStreamOrPath ofDisposable(NutsPath value) { return new NutsStreamOrPath(value, Type.PATH, true); } + public static NutsStreamOrPath of(File value,NutsSession session) { + return of(NutsPath.of(value,session)); + } + + public static NutsStreamOrPath of(URL value,NutsSession session) { + return of(NutsPath.of(value,session)); + } + + public static NutsStreamOrPath of(Path value,NutsSession session) { + return of(NutsPath.of(value,session)); + } + + public static NutsStreamOrPath of(String value,NutsSession session) { + return of(NutsPath.of(value,session)); + } + public static NutsStreamOrPath of(NutsPath value) { return new NutsStreamOrPath(value, Type.PATH, false); } @@ -58,16 +73,16 @@ public static NutsStreamOrPath ofAnyInputOrNull(Object value, NutsSession sessio return of((NutsPath) value); } if (value instanceof File) { - return of(session.io().path((File) value)); + return of((File) value,session); } if (value instanceof URL) { - return of(session.io().path((URL) value)); + return of((URL) value,session); } if (value instanceof Path) { - return of(session.io().path((Path) value)); + return of((Path) value,session); } if (value instanceof String) { - return of(session.io().path((String) value)); + return of((String) value,session); } return null; } @@ -104,8 +119,8 @@ public NutsStreamOrPath toMultiRead(NutsSession session) { public NutsStreamOrPath toDisposable(NutsSession session) { String name = getName(); - Path tempFile = session.io().tmp().createTempFile(name).toFile(); - NutsIOCopyAction copy = session.io().copy(); + Path tempFile = NutsTmp.of(session).createTempFile(name).toFile(); + NutsCp copy = NutsCp.of(session); if (type == Type.PATH) { copy.from((NutsPath) value); } else { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/PipeThread.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/PipeThread.java index a0d32cbef..55d4a0a2b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/PipeThread.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/PipeThread.java @@ -25,16 +25,12 @@ */ package net.thevpc.nuts.runtime.bundles.io; -import net.thevpc.nuts.NutsLogVerb; -import net.thevpc.nuts.NutsMessage; -import net.thevpc.nuts.NutsWorkspace; +import net.thevpc.nuts.*; import java.io.IOException; import java.io.OutputStream; import java.util.logging.Level; -import net.thevpc.nuts.NutsSession; - public class PipeThread extends Thread implements StopMonitor { private final NonBlockingInputStream in; @@ -64,7 +60,7 @@ public void requestStop() { try { lock.wait(); } catch (InterruptedException e) { - session.log().of(PipeThread.class).with() + NutsLoggerOp.of(PipeThread.class,session) .error(e) .level(Level.FINEST) .verb(NutsLogVerb.WARNING) @@ -95,7 +91,7 @@ public void run() { } } } catch (IOException e) { - session.log().of(PipeThread.class).with() + NutsLoggerOp.of(PipeThread.class,session) .error(e) .level(Level.FINEST) .verb(NutsLogVerb.WARNING) diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/ProcessBuilder2.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/ProcessBuilder2.java index 5a26d87c2..1ae36c221 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/ProcessBuilder2.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/ProcessBuilder2.java @@ -57,7 +57,7 @@ public ProcessBuilder2(NutsSession session) { private static String formatArg(String s, NutsSession session) { DefaultNutsArgument a = new DefaultNutsArgument(s); StringBuilder sb = new StringBuilder(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (a.isKeyValue()) { if (a.isOption()) { sb.append(factory.ofStyled(CoreStringUtils.enforceDoubleQuote(a.getKey().getString(), session), NutsTextStyle.option())); @@ -335,25 +335,25 @@ private void waitFor0() throws IOException { if (isGrabOutputString()) { throw new NutsExecutionException(session, NutsMessage.cstyle("execution failed with code %d and message : %s. Command was %s", result, getOutputString(), - session.commandLine().create(getCommand())) + NutsCommandLine.of(getCommand(),session)) , result); } } else { if (isGrabErrorString()) { throw new NutsExecutionException(session, NutsMessage.cstyle("execution failed with code %d and message : %s. Command was %s", result, getOutputString(), - session.commandLine().create(getCommand())) + NutsCommandLine.of(getCommand(),session)) , result); } if (isGrabOutputString()) { throw new NutsExecutionException(session, NutsMessage.cstyle( "execution failed with code %d and message : %s. Command was %s", result, getOutputString(), - session.commandLine().create(getCommand()) + NutsCommandLine.of(getCommand(),session) ), result); } } throw new NutsExecutionException(session, NutsMessage.cstyle("execution failed with code %d. Command was %s", result, - session.commandLine().create(getCommand()) + NutsCommandLine.of(getCommand(),session) ), result); } } @@ -667,7 +667,7 @@ public String getFormattedCommandString(NutsSession session) { } private String escape(NutsSession session, String f) { - return session.text().ofPlain(f).toString(); + return NutsTexts.of(session).ofPlain(f).toString(); } public String getFormattedCommandString(NutsSession session, CommandStringFormat f) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/ZipUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/ZipUtils.java index 12544f1f3..16c6088bb 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/ZipUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/io/ZipUtils.java @@ -10,7 +10,7 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
- * + *

* Copyright [2020] [thevpc] Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -23,10 +23,7 @@ */ package net.thevpc.nuts.runtime.bundles.io; -import net.thevpc.nuts.NutsMessage; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsWorkspace; -import net.thevpc.nuts.NutsLogVerb; +import net.thevpc.nuts.*; import java.io.*; import java.nio.file.Files; @@ -44,7 +41,7 @@ */ public class ZipUtils { -// private static final Logger LOG = Logger.getLogger(ZipUtils.class.getName()); + // private static final Logger LOG = Logger.getLogger(ZipUtils.class.getName()); public static void zip(NutsSession ws, String target, ZipOptions options, String... source) throws IOException { if (options == null) { options = new ZipOptions(); @@ -202,7 +199,7 @@ public static void unzip(NutsSession session, String zipFile, String outputFolde //get the zip file content try (ZipInputStream zis - = new ZipInputStream(new FileInputStream(new File(zipFile)))) { + = new ZipInputStream(new FileInputStream(new File(zipFile)))) { //get the zipped file list entry ZipEntry ze = zis.getNextEntry(); String root = null; @@ -230,7 +227,7 @@ public static void unzip(NutsSession session, String zipFile, String outputFolde newFile.mkdirs(); } else { File newFile = new File(outputFolder + File.separator + fileName); - session.log().of(ZipUtils.class).with().session(session).level(Level.FINEST).verb(NutsLogVerb.WARNING) + NutsLoggerOp.of(ZipUtils.class, session).level(Level.FINEST).verb(NutsLogVerb.WARNING) .log(NutsMessage.jstyle("file unzip : {0}", newFile.getAbsoluteFile())); //create all non exists folders //else you will hit FileNotFoundException for compressed folder @@ -291,7 +288,7 @@ public static boolean extractFirstPath(InputStream zipFile, Set possible return false; } -// public static void zip(final File _folder, final File _zipFilePath) { + // public static void zip(final File _folder, final File _zipFilePath) { // final Path folder = _folder.toPath(); // Path zipFilePath = _zipFilePath.toPath(); // try ( diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/DirtyLuceneIndexParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/DirtyLuceneIndexParser.java index 0735f89f7..65ecb38b8 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/DirtyLuceneIndexParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/DirtyLuceneIndexParser.java @@ -1,6 +1,6 @@ package net.thevpc.nuts.runtime.bundles.mvn; -import net.thevpc.nuts.runtime.bundles.collections.EvictingQueue; +import net.thevpc.nuts.runtime.bundles.collections.EvictingIntQueue; import java.io.*; import java.util.Iterator; @@ -8,7 +8,7 @@ public class DirtyLuceneIndexParser implements Iterator, Closeable { private PushbackReader reader; private String last; - private EvictingQueue whites = new EvictingQueue<>(10); + private EvictingIntQueue whites = new EvictingIntQueue(10); private long count = 0; private boolean closed=false; @@ -70,7 +70,7 @@ private String preload() { if (withPipe) { String s = sb.toString(); boolean ignore = false; - if (whites.size() == 3 && whites.get(0).equals(0) && whites.get(1).equals(0) && whites.get(2).equals(0)) { + if (whites.size() == 3 && whites.get(0)==0 && whites.get(1)==0 && whites.get(2)==0) { s = s.substring(1); } if (!ignore) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/MavenMetadataParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/MavenMetadataParser.java index df82a8ebe..9e49e6e64 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/MavenMetadataParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/MavenMetadataParser.java @@ -45,7 +45,7 @@ public class MavenMetadataParser { public MavenMetadataParser(NutsSession session) { this.session = session; - LOG=session.log().of(MavenMetadataParser.class); + LOG=NutsLogger.of(MavenMetadataParser.class,session); } public String toXmlString(MavenMetadata m) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/NutsPomLogger.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/NutsPomLogger.java index 5bbf18f3c..b191abb8c 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/NutsPomLogger.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/NutsPomLogger.java @@ -1,9 +1,6 @@ package net.thevpc.nuts.runtime.bundles.mvn; -import net.thevpc.nuts.NutsLogVerb; -import net.thevpc.nuts.NutsLogger; -import net.thevpc.nuts.NutsMessage; -import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.*; import java.util.logging.Level; @@ -14,7 +11,7 @@ public class NutsPomLogger implements PomLogger { public NutsPomLogger(NutsSession session) { this.session = session; - LOG = session.log().of(PomIdResolver.class); + LOG = NutsLogger.of(PomIdResolver.class,session); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/PomXmlParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/PomXmlParser.java index 9554f27f2..f8b289f83 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/PomXmlParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/mvn/PomXmlParser.java @@ -1,9 +1,6 @@ package net.thevpc.nuts.runtime.bundles.mvn; -import net.thevpc.nuts.NutsBlankable; -import net.thevpc.nuts.NutsId; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsUtilStrings; +import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.format.xml.NutsXmlUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -182,7 +179,7 @@ public static PomDependency parseDependency(Element dependency, OsAndArch props, if (d_scope.isEmpty()) { d_scope = "compile"; } - NutsId id = session.id().builder().setGroupId(d_groupId).setArtifactId(d_artifactId).build(); + NutsId id = NutsIdBuilder.of(session).setGroupId(d_groupId).setArtifactId(d_artifactId).build(); return new PomDependency( d_groupId, d_artifactId, d_classifier, d_version, d_scope, d_optional, props == null ? null : props.getOs(id), @@ -208,7 +205,7 @@ public OsAndArch(Map props, NutsSession session) { if(a.startsWith("#")){ //ignore! }else{ - NutsId id = session.id().parser().setLenient(true).parse(a); + NutsId id = NutsIdParser.of(session).setLenient(true).parse(a); if(id!=null) { if (!NutsBlankable.isBlank(os)) { osMap.put(id.getShortName(), os); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/parsers/StreamTokenizerExt.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/parsers/StreamTokenizerExt.java index 47f5a86ed..306f42070 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/parsers/StreamTokenizerExt.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/parsers/StreamTokenizerExt.java @@ -856,7 +856,7 @@ public int lineno() { *

The precise string returned is unspecified, although the following * example can be considered typical: * - *

Token['a'], line 10
+ *
NutsToken['a'], line 10
* * @return a string representation of the token */ @@ -901,7 +901,7 @@ public String toString() { break; } } - return "Token[" + ret + "], line " + LINENO; + return "NutsToken[" + ret + "], line " + LINENO; } } \ No newline at end of file diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/string/GlobUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/string/GlobUtils.java index 639141d5d..0826fb851 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/string/GlobUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/bundles/string/GlobUtils.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
* is a new Open Source Package Manager to help install packages and libraries * for runtime execution. Nuts is the ultimate companion for maven (and other @@ -10,7 +10,7 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
- * + *

* Copyright [2020] [thevpc] Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -24,7 +24,6 @@ package net.thevpc.nuts.runtime.bundles.string; import net.thevpc.nuts.NutsBlankable; -import net.thevpc.nuts.NutsUtilStrings; import java.util.regex.Pattern; @@ -34,7 +33,7 @@ */ public class GlobUtils { - private static final Pattern PATTERN_ALL = Pattern.compile(".*"); + public static final Pattern PATTERN_ALL = Pattern.compile(".*"); public static Pattern ofExact(String pattern) { if (NutsBlankable.isBlank(pattern)) { @@ -42,6 +41,7 @@ public static Pattern ofExact(String pattern) { } return Pattern.compile(simpexpToRegexp(pattern, false)); } + public static Pattern ofContains(String pattern) { if (NutsBlankable.isBlank(pattern)) { return PATTERN_ALL; @@ -110,4 +110,76 @@ private static String simpexpToRegexp(String pattern, boolean contains) { } return sb.toString(); } + + + public static Pattern glob(String o,char s) { + switch (s){ + case '{': + case '}': + case '(': + case ')': + case '<': + case '>': + case '*': + case '?':{ + throw new IllegalArgumentException("unsupported glob separator "+s); + } + } + while (true) { + if (o.endsWith(s+"**"+s+"*")) { + o = o.substring(0, o.length() - 5); + } else if (o.endsWith(s+"**")) { + o = o.substring(0, o.length() - 3); + } else if (o.endsWith(s+"*")) { + o = o.substring(0, o.length() - 2); + } else { + break; + } + } + if (o.isEmpty()) { + return Pattern.compile(".*"); + } + StringBuilder sb = new StringBuilder(); + char[] chars = o.toCharArray(); + for (int i = 0; i < chars.length; i++) { + char c = chars[i]; + switch (c) { + case '.': + case '{': + case '}': + case '<': + case '>': { + sb.append('\\'); + sb.append(c); + break; + } + case '*': { + if (i + 1 < chars.length && chars[i + 1] == '*') { + if (i + 2 < chars.length && chars[i + 2] == s) { + i++; + if (i + 3 < chars.length) { + sb.append(".*["+s+"]"); + } else { + sb.append(".*"); + } + } else { + i++; + sb.append(".*"); + } + } else { + sb.append("[^"+s+"]*"); + } + break; + } + case '?': { + sb.append("[^").append(s).append("]?"); + break; + } + default: { + sb.append(c); + } + } + } + return Pattern.compile(sb.toString()); + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/AbstractNutsWorkspace.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/AbstractNutsWorkspace.java index 00ce5f436..dfb569771 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/AbstractNutsWorkspace.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/AbstractNutsWorkspace.java @@ -32,26 +32,10 @@ */ public abstract class AbstractNutsWorkspace implements NutsWorkspace { - protected NutsSession initSession; - protected DefaultNutsBootModel bootModel; public AbstractNutsWorkspace() { } - public NutsSession defaultSession() { - if (initSession != null) { - return initSession; - } - return bootModel.bootSession(); - } - - @Override - public NutsSession createSession() { - NutsSession nutsSession = new DefaultNutsSession(this); - nutsSession.setTerminal(nutsSession.term().createTerminal()); - nutsSession.setExpireTime(nutsSession.boot().getBootOptions().getExpireTime()); - return nutsSession; - } @Override public int getSupportLevel(NutsSupportLevelContext criteria) { @@ -65,4 +49,5 @@ public String toString() { + '}'; } + } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/DefaultNutsClassLoader.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/DefaultNutsClassLoader.java index 20f892700..6da8debc0 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/DefaultNutsClassLoader.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/DefaultNutsClassLoader.java @@ -53,7 +53,7 @@ public boolean contains(NutsClassLoaderNode node, boolean deep) { } public NutsClassLoaderNode search(NutsClassLoaderNode node, boolean deep) { - NutsId ii = ws.id().parser().parse(node.getId()); + NutsId ii = NutsId.of(node.getId(),ws); String sn = ii.getShortName(); NutsClassLoaderNode o = nodes.get(sn); if (o != null) { @@ -73,7 +73,7 @@ public NutsClassLoaderNode search(NutsClassLoaderNode node, boolean deep) { } public boolean add(NutsClassLoaderNode node) { - NutsId ii = ws.id().parser().parse(node.getId()); + NutsId ii = NutsId.of(node.getId(),ws); String sn = ii.getShortName(); if (!nodes.containsKey(sn)) { nodes.put(sn, node); @@ -84,7 +84,7 @@ public boolean add(NutsClassLoaderNode node) { protected boolean add(NutsClassLoaderNode node, boolean deep) { String s = node.getId(); - NutsId ii = ws.id().parser().parse(s); + NutsId ii = NutsId.of(s,ws); String sn = ii.getShortName(); if (!effective.containsKey(sn)) { effective.put(sn, node); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/DefaultNutsSession.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/DefaultNutsSession.java index a166d63c8..d799a22a4 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/DefaultNutsSession.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/DefaultNutsSession.java @@ -345,7 +345,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { getTerminal().setOut(getTerminal().out().setMode(NutsTerminalMode.FORMATTED)); getTerminal().setErr(getTerminal().err().setMode(NutsTerminalMode.FORMATTED)); } else { - NutsArgument bb = commandLine().createArgument(v); + NutsArgument bb = NutsArgument.of(v,this); Boolean b = bb.getAll().getBoolean(null); if (b != null) { if (b) { @@ -669,7 +669,7 @@ public NutsSession copy() { try { DefaultNutsSession cloned = (DefaultNutsSession) clone(); cloned.ws = new NutsWorkspaceSessionAwareImpl(cloned, ws); - cloned.terminal = terminal == null ? null : cloned.term().createTerminal(terminal); + cloned.terminal = terminal == null ? null : NutsSessionTerminal.of(terminal,cloned); cloned.properties = properties == null ? null : properties.copy(); cloned.outputFormatOptions = outputFormatOptions == null ? null : new ArrayList<>(outputFormatOptions); cloned.listeners = null; @@ -1003,7 +1003,7 @@ public NutsIterableFormat getIterableOutput() { if (!iterableOut) { return null; } - return elem().setContentType(getOutputFormat()).iter(out()); + return NutsElements.of(this).setContentType(getOutputFormat()).iter(out()); // if (iterFormatHandler == null) { // return null; // } @@ -1412,11 +1412,6 @@ public NutsUpdateStatisticsCommand updateStatistics() { return getWorkspace().updateStatistics(); } - @Override - public NutsWorkspaceAppsManager apps() { - return getWorkspace().apps(); - } - @Override public NutsWorkspaceExtensionManager extensions() { return getWorkspace().extensions(); @@ -1437,71 +1432,21 @@ public NutsWorkspaceSecurityManager security() { return getWorkspace().security(); } - @Override - public NutsFilterManager filters() { - return getWorkspace().filters(); - } - - @Override - public NutsIOManager io() { - return getWorkspace().io(); - } - - @Override - public NutsLogManager log() { - return getWorkspace().log(); - } @Override public NutsWorkspaceEventManager events() { return getWorkspace().events(); } - @Override - public NutsCommandLineManager commandLine() { - return getWorkspace().commandLine(); - } - - @Override - public NutsIdManager id() { - return getWorkspace().id(); - } - - @Override - public NutsVersionManager version() { - return getWorkspace().version(); - } - - @Override public NutsInfoFormat info() { return getWorkspace().info(); } - @Override - public NutsDescriptorManager descriptor() { - return getWorkspace().descriptor(); - } - - @Override - public NutsDependencyManager dependency() { - return getWorkspace().dependency(); - } - @Override public NutsFormatManager formats() { return getWorkspace().formats(); } - @Override - public NutsConcurrentManager concurrent() { - return getWorkspace().concurrent(); - } - - @Override - public NutsUtilManager util() { - return getWorkspace().util(); - } - @Override public NutsImportManager imports() { return getWorkspace().imports(); @@ -1527,21 +1472,6 @@ public NutsBootManager boot() { return getWorkspace().boot(); } - @Override - public NutsTerminalManager term() { - return getWorkspace().term(); - } - - @Override - public NutsTextManager text() { - return getWorkspace().text(); - } - - @Override - public NutsElementFormat elem() { - return getWorkspace().elem(); - } - @Override public String getDependencySolver() { return dependencySolver; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceExt.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceExt.java index 153684670..05ecd29f3 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceExt.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceExt.java @@ -6,6 +6,7 @@ package net.thevpc.nuts.runtime.core; import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.log.DefaultNutsLogModel; import net.thevpc.nuts.runtime.core.repos.NutsInstalledRepository; import net.thevpc.nuts.runtime.core.commands.ws.NutsExecutionContextBuilder; import net.thevpc.nuts.spi.NutsInstallerComponent; @@ -70,4 +71,5 @@ static NutsWorkspaceExt of(NutsWorkspace ws) { NutsSession defaultSession(); + NutsWorkspaceModel getModel(); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceFactory.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceFactory.java index 785904804..8fb3951bc 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceFactory.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceFactory.java @@ -42,19 +42,16 @@ public interface NutsWorkspaceFactory { Set discoverTypes(NutsId id, URL url, ClassLoader bootClassLoader, NutsSession session); - Set discoverTypes(NutsId id, URL url, ClassLoader bootClassLoader, Class[] extensionPoints, NutsSession session); - -// Set discoverTypes(ClassLoader bootClassLoader); - , V> T createSupported(Class type, V supportCriteria, NutsSession session); + Set discoverTypes(NutsId id, URL url, ClassLoader bootClassLoader, Class[] extensionPoints, NutsSession session); - , V> T createSupported(Class type, V supportCriteria, Class[] constructorParameterTypes, Object[] constructorParameters, NutsSession session); + , V> T createSupported(Class type, V supportCriteria, boolean required, NutsSession session); , V> List createAllSupported(Class type, V supportCriteria, NutsSession session); List createAll(Class type, NutsSession session); -// Set getExtensionPoints(); + T createFirst(Class type, NutsSession session); Set getExtensionTypes(Class extensionPoint, NutsSession session); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceModel.java new file mode 100644 index 000000000..cfc4a7a98 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/NutsWorkspaceModel.java @@ -0,0 +1,49 @@ +package net.thevpc.nuts.runtime.core; + +import net.thevpc.nuts.NutsId; +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.NutsVersion; +import net.thevpc.nuts.NutsWorkspace; +import net.thevpc.nuts.runtime.core.app.DefaultNutsWorkspaceLocationModel; +import net.thevpc.nuts.runtime.core.filters.DefaultNutsFilterModel; +import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTextManagerModel; +import net.thevpc.nuts.runtime.core.log.DefaultNutsLogModel; +import net.thevpc.nuts.runtime.core.repos.DefaultNutsRepositoryModel; +import net.thevpc.nuts.runtime.standalone.DefaultNutsWorkspaceEventModel; +import net.thevpc.nuts.runtime.standalone.boot.DefaultNutsBootModel; +import net.thevpc.nuts.runtime.standalone.config.DefaultCustomCommandsModel; +import net.thevpc.nuts.runtime.standalone.config.DefaultImportModel; +import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigModel; +import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceEnvManagerModel; +import net.thevpc.nuts.runtime.standalone.ext.DefaultNutsWorkspaceExtensionModel; +import net.thevpc.nuts.runtime.standalone.repos.DefaultNutsInstalledRepository; +import net.thevpc.nuts.runtime.standalone.security.DefaultNutsWorkspaceSecurityModel; + +public class NutsWorkspaceModel { + public NutsWorkspace ws; + public NutsSession initSession; + public DefaultNutsBootModel bootModel; + public DefaultNutsWorkspaceSecurityModel securityModel; + public DefaultNutsFilterModel filtersModel; + public DefaultNutsWorkspaceConfigModel configModel; + public DefaultNutsWorkspaceLocationModel locationsModel; + public DefaultNutsRepositoryModel repositoryModel; + public DefaultNutsWorkspaceEventModel eventsModel; + public DefaultNutsTextManagerModel textModel; + public String uuid; + public String location; + public String name; + public NutsVersion apiVersion; + public NutsId apiId; + public NutsId runtimeId; + public DefaultNutsInstalledRepository installedRepository; + public DefaultNutsLogModel logModel; + public DefaultNutsWorkspaceEnvManagerModel envModel; + public DefaultNutsWorkspaceExtensionModel extensionModel; + public DefaultCustomCommandsModel aliasesModel; + public DefaultImportModel importModel; + + public NutsWorkspaceModel(NutsWorkspace ws) { + this.ws = ws; + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/ArchitectureNonOption.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/ArchitectureNonOption.java index d8fc69333..8e846999f 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/ArchitectureNonOption.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/ArchitectureNonOption.java @@ -27,7 +27,7 @@ import net.thevpc.nuts.NutsArgumentCandidate; import net.thevpc.nuts.NutsCommandAutoComplete; -import net.thevpc.nuts.NutsCommandLineManager; +import net.thevpc.nuts.NutsCommandLines; import java.util.ArrayList; import java.util.List; @@ -45,11 +45,10 @@ public ArchitectureNonOption(String name) { @Override public List getCandidates(NutsCommandAutoComplete context) { List all = new ArrayList<>(); - NutsCommandLineManager c = context.getSession().commandLine(); - all.add(c.createCandidate("\"linux x86\"").build()); - all.add(c.createCandidate("\"linux x64\"").build()); - all.add(c.createCandidate("\"win x86\"").build()); - all.add(c.createCandidate("\"win x64\"").build()); + all.add(new NutsArgumentCandidate("\"linux x86\"")); + all.add(new NutsArgumentCandidate("\"linux x64\"")); + all.add(new NutsArgumentCandidate("\"win x86\"")); + all.add(new NutsArgumentCandidate("\"win x64\"")); return all; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/CoreNutsArgumentsParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/CoreNutsArgumentsParser.java index 041ad7b8e..1ad0b731c 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/CoreNutsArgumentsParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/CoreNutsArgumentsParser.java @@ -1111,7 +1111,7 @@ public static void parseNutsArguments(NutsSession session, String[] bootArgument ) )) { if (!showError.isEmpty()) { - NutsTextBuilder errorMessage = session.text().builder(); + NutsTextBuilder errorMessage = NutsTexts.of(session).builder(); for (NutsMessage s : showError) { errorMessage.append(s).append("\n"); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultDefaultNutsApplicationContexts.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultDefaultNutsApplicationContexts.java new file mode 100644 index 000000000..36e43eabb --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultDefaultNutsApplicationContexts.java @@ -0,0 +1,31 @@ +package net.thevpc.nuts.runtime.core.app; + +import net.thevpc.nuts.NutsApplicationContext; +import net.thevpc.nuts.NutsApplicationContexts; +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.spi.NutsSupportLevelContext; + +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) +public class DefaultDefaultNutsApplicationContexts implements NutsApplicationContexts { + private final NutsSession session; + + public DefaultDefaultNutsApplicationContexts(NutsSession session) { + this.session = session; + } + + public NutsApplicationContext create(String[] args, long startTimeMillis, Class appClass, String storeId) { +// if (session == null) { +// checkSession(this.session); +// session = this.session; +// } + return new DefaultNutsApplicationContext(session.getWorkspace(), session, args, appClass, storeId, startTimeMillis); + } + + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNonOption.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNonOption.java index 35408842d..cd3834329 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNonOption.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNonOption.java @@ -54,7 +54,7 @@ public String getName() { @Override public List getCandidates(NutsCommandAutoComplete context) { List list = new ArrayList<>(); - list.add(context.getSession().commandLine().createCandidate("<" + getName() + ">").build()); + list.add(new NutsArgumentCandidate("<" + getName() + ">")); return list; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsApplicationContext.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsApplicationContext.java index d9fc01f20..9a11d76b3 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsApplicationContext.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsApplicationContext.java @@ -63,7 +63,7 @@ public DefaultNutsApplicationContext(NutsWorkspace workspace, NutsSession sessio session = this.session;//will be used later int wordIndex = -1; if (args.length > 0 && args[0].startsWith("--nuts-exec-mode=")) { - NutsCommandLine execModeCommand = this.session.commandLine().parse(args[0].substring(args[0].indexOf('=') + 1)); + NutsCommandLine execModeCommand = NutsCommandLine.parse(args[0].substring(args[0].indexOf('=') + 1),session); if (execModeCommand.hasNext()) { NutsArgument a = execModeCommand.next(); switch (a.getKey().getString()) { @@ -91,7 +91,7 @@ public DefaultNutsApplicationContext(NutsWorkspace workspace, NutsSession sessio case "update": { mode = NutsApplicationMode.UPDATE; if (execModeCommand.hasNext()) { - appPreviousVersion = session.version().parser().parse(execModeCommand.next().getString()); + appPreviousVersion = NutsVersion.of(execModeCommand.next().getString(),session); } modeArgs = execModeCommand.toStringArray(); execModeCommand.skipAll(); @@ -108,7 +108,7 @@ public DefaultNutsApplicationContext(NutsWorkspace workspace, NutsSession sessio if (_appId != null) { //("=== Inherited "+_appId); } else { - _appId = this.session.id().setSession(session).resolveId(appClass); + _appId = NutsIdResolver.of(session).resolveId(appClass); } if (_appId == null) { throw new NutsExecutionException(session, NutsMessage.cstyle("invalid Nuts Application (%s). Id cannot be resolved",appClass.getName()), 203); @@ -229,7 +229,7 @@ public boolean configureFirst(NutsCommandLine cmd) { cmd.skip(); if (enabled) { if (cmd.isExecMode()) { - getSession().out().printf("%s%n", getSession().id().resolveId(getClass()).getVersion().toString()); + getSession().out().printf("%s%n", NutsIdResolver.of(session).resolveId(getClass()).getVersion().toString()); cmd.skipAll(); } throw new NutsExecutionException(session, NutsMessage.cstyle("version"), 0); @@ -424,8 +424,7 @@ public NutsApplicationContext setArgs(String[] args) { @Override public NutsCommandLine getCommandLine() { - return this.session.commandLine().setSession(getSession()) - .create(getArguments()) + return NutsCommandLine.of(getArguments(),getSession()) .setCommandName(getAppId().getArtifactId()) .setAutoComplete(getAutoComplete()); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsArgumentCandidateBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsArgumentCandidateBuilder.java deleted file mode 100644 index 3700ab865..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsArgumentCandidateBuilder.java +++ /dev/null @@ -1,44 +0,0 @@ -package net.thevpc.nuts.runtime.core.app; - -import net.thevpc.nuts.NutsDefaultArgumentCandidate; -import net.thevpc.nuts.NutsArgumentCandidate; -import net.thevpc.nuts.NutsArgumentCandidateBuilder; - -public class DefaultNutsArgumentCandidateBuilder implements NutsArgumentCandidateBuilder { - private String value; - private String display; - - @Override - public String getValue() { - return value; - } - - @Override - public DefaultNutsArgumentCandidateBuilder setValue(String value) { - this.value = value; - return this; - } - - @Override - public String getDisplay() { - return display; - } - - @Override - public DefaultNutsArgumentCandidateBuilder setDisplay(String display) { - this.display = display; - return this; - } - - @Override - public NutsArgumentCandidateBuilder setAll(NutsArgumentCandidate value) { - setValue(value==null?null:value.getValue()); - setDisplay(value==null?null:value.getDisplay()); - return this; - } - - @Override - public NutsArgumentCandidate build() { - return new NutsDefaultArgumentCandidate(value,display); - } -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLine.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLine.java index 516a5d8cb..c5e6c55a7 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLine.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLine.java @@ -218,7 +218,7 @@ public NutsCommandLine unexpectedArgument(NutsString errorMessage) { skipAll(); return this; } - NutsTextBuilder m = getSession().text().builder(); + NutsTextBuilder m = NutsTexts.of(getSession()).builder(); m.append("unexpected argument ").append(highlightText(String.valueOf(peek()))); if (errorMessage != null && errorMessage.textLength() > 0) { m.append(" , ").append(errorMessage); @@ -230,7 +230,7 @@ public NutsCommandLine unexpectedArgument(NutsString errorMessage) { @Override public NutsCommandLine unexpectedArgument(NutsMessage errorMessage) { - return unexpectedArgument(errorMessage == null ? null : getSession().text().toText(errorMessage)); + return unexpectedArgument(errorMessage == null ? null : NutsTexts.of(getSession()).toText(errorMessage)); } @Override @@ -251,7 +251,7 @@ public NutsCommandLine required(NutsString errorMessage) { return this; } throwError((errorMessage == null || errorMessage.isEmpty()) - ? getSession().text().toText("missing arguments") + ? NutsTexts.of(getSession()).toText("missing arguments") : errorMessage ); } @@ -260,7 +260,7 @@ public NutsCommandLine required(NutsString errorMessage) { @Override public NutsCommandLine required(NutsMessage errorMessage) { - return required(errorMessage == null ? null : getSession().text().toText(errorMessage)); + return required(errorMessage == null ? null : NutsTexts.of(getSession()).toText(errorMessage)); } @Override @@ -376,7 +376,7 @@ public NutsArgument next(NutsArgumentType expectValue, String... names) { } } default: { - throwError(getSession().text().builder().append("unsupported ") + throwError(NutsTexts.of(getSession()).builder().append("unsupported ") .append(highlightText(String.valueOf(expectValue))) .build() ); @@ -546,7 +546,7 @@ public boolean isNonOption(int index) { public NutsCommandLine parseLine(String commandLine) { setArguments( - session.commandLine().parse(commandLine).toStringArray() + NutsCommandLine.parse(commandLine,session).toStringArray() ); return this; } @@ -616,7 +616,7 @@ public void process(NutsCommandLineConfigurable defaultConfigurable, NutsCommand @Override public void throwError(NutsString message) { - NutsTextBuilder m = getSession().text().builder(); + NutsTextBuilder m = NutsTexts.of(getSession()).builder(); if (!NutsBlankable.isBlank(commandName)) { m.append(commandName).append(" : "); } @@ -626,7 +626,7 @@ public void throwError(NutsString message) { @Override public NutsCommandLineFormat formatter() { - return session.commandLine().formatter().setValue(this); + return NutsCommandLineFormat.of(session).setValue(this); } private NutsArgumentCandidate[] resolveRecommendations(NutsArgumentType expectValue, String[] names, int autoCompletecurrentWordIndex) { @@ -678,7 +678,7 @@ private NutsArgumentCandidate[] resolveRecommendations(NutsArgumentType expectVa // } skipToNext = true; } else if (xs.length() > 0 && a.startsWith(xs) && !xs.equals(a)) { - candidates.add(createCandidate(a)); + candidates.add(new NutsArgumentCandidate(a)); skipToNext = true; } else { skipToNext = true; @@ -693,7 +693,7 @@ private NutsArgumentCandidate[] resolveRecommendations(NutsArgumentType expectVa NutsArgument p = get(nameSeqArray.length - 1); if (p != null) { if (name.startsWith(p.getKey().getString())) { - candidates.add(createCandidate(name)); + candidates.add(new NutsArgumentCandidate(name)); // switch (expectValue) { // case ANY: { // candidates.add(createCandidate("")); @@ -713,7 +713,7 @@ private NutsArgumentCandidate[] resolveRecommendations(NutsArgumentType expectVa // } } } else { - candidates.add(createCandidate(name)); + candidates.add(new NutsArgumentCandidate(name)); } } } @@ -731,16 +731,12 @@ private boolean isPrefixed(String[] nameSeqArray) { return true; } - private NutsArgumentCandidate createCandidate(String s) { - return session.commandLine().createCandidate(s).build(); - } - public NutsArgument next(NutsArgumentName name, boolean forceNonOption, boolean error) { if (hasNext() && (!forceNonOption || !peek().isOption())) { if (isAutoComplete()) { List values = name == null ? null : name.getCandidates(getAutoComplete()); if (values == null || values.isEmpty()) { - autoComplete.addCandidate(createCandidate(name == null ? "" : name.getName())); + autoComplete.addCandidate(new NutsArgumentCandidate(name == null ? "" : name.getName())); } else { for (NutsArgumentCandidate value : values) { autoComplete.addCandidate(value); @@ -755,7 +751,7 @@ public NutsArgument next(NutsArgumentName name, boolean forceNonOption, boolean if (isAutoComplete()) { List values = name == null ? null : name.getCandidates(getAutoComplete()); if (values == null || values.isEmpty()) { - autoComplete.addCandidate(createCandidate(name == null ? "" : name.getName())); + autoComplete.addCandidate(new NutsArgumentCandidate(name == null ? "" : name.getName())); } else { for (NutsArgumentCandidate value : values) { autoComplete.addCandidate(value); @@ -768,11 +764,11 @@ public NutsArgument next(NutsArgumentName name, boolean forceNonOption, boolean return null;//return new Argument(""); } if (hasNext() && (!forceNonOption || !peek().isOption())) { - throwError(getSession().text().builder().append("unexpected option ").append(highlightText(String.valueOf(peek()))) + throwError(NutsTexts.of(getSession()).builder().append("unexpected option ").append(highlightText(String.valueOf(peek()))) .build() ); } - throwError(getSession().text().builder().append("missing argument ").append(highlightText((name == null ? "value" : name.getName()))) + throwError(NutsTexts.of(getSession()).builder().append("missing argument ").append(highlightText((name == null ? "value" : name.getName()))) .build() ); } @@ -891,7 +887,7 @@ private boolean ensureNext(boolean expandSimpleOptions, boolean ignoreExistingEx } private NutsArgument createArgument(String v) { - return DefaultNutsCommandLineManager.Factory.createArgument0(getSession(), v, eq); + return DefaultNutsCommandLines.Factory.createArgument0(getSession(), v, eq); } private boolean isAutoComplete() { @@ -906,7 +902,7 @@ public NutsCommandLine copy() { } private NutsString highlightText(String text) { - return getSession().text().ofStyled(text, NutsTextStyle.primary3()); + return NutsTexts.of(getSession()).ofStyled(text, NutsTextStyle.primary3()); } private boolean _configureLast(NutsCommandLine commandLine, NutsCommandLineConfigurable configurable) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLineFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLineFormat.java index 1c934a665..48f2ffb1e 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLineFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLineFormat.java @@ -3,6 +3,7 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.format.DefaultFormatBase; import net.thevpc.nuts.runtime.core.shell.NutsShellHelper; +import net.thevpc.nuts.spi.NutsSupportLevelContext; public class DefaultNutsCommandLineFormat extends DefaultFormatBase implements NutsCommandLineFormat { @@ -10,8 +11,8 @@ public class DefaultNutsCommandLineFormat extends DefaultFormatBase context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLineManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLines.java similarity index 72% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLineManager.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLines.java index 633195f78..6abf9452d 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLineManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsCommandLines.java @@ -1,37 +1,38 @@ package net.thevpc.nuts.runtime.core.app; -import net.thevpc.nuts.NutsDefaultArgumentCandidate; import net.thevpc.nuts.*; import java.util.List; import net.thevpc.nuts.runtime.core.shell.NutsShellHelper; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; -public class DefaultNutsCommandLineManager implements NutsCommandLineManager { +public class DefaultNutsCommandLines implements NutsCommandLines { private NutsWorkspace ws; private NutsSession session; private NutsShellFamily family = NutsShellFamily.getCurrent(); - public DefaultNutsCommandLineManager(NutsWorkspace ws) { - this.ws = ws; + public DefaultNutsCommandLines(NutsSession session) { + this.session = session; + this.ws = session.getWorkspace(); } public NutsSession getSession() { return session; } - public NutsCommandLineManager setSession(NutsSession session) { + public NutsCommandLines setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(ws, session); return this; } - public NutsShellFamily getCommandlineFamily() { + public NutsShellFamily getShellFamily() { return family; } - public NutsCommandLineManager setCommandlineFamily(NutsShellFamily family) { + public NutsCommandLines setShellFamily(NutsShellFamily family) { this.family = family == null ? NutsShellFamily.getCurrent() : family; return this; } @@ -40,20 +41,6 @@ public NutsWorkspace getWorkspace() { return ws; } - @Override - public NutsCommandLineFormat formatter(NutsCommandLine commandLine) { - return formatter().setValue(commandLine); - } - - @Override - public NutsCommandLineFormat formatter() { - checkSession(); - return new DefaultNutsCommandLineFormat(getWorkspace()) - .setSession(session) - .setShellFamily(getCommandlineFamily()) - ; - } - @Override public NutsCommandLine parse(String line) { checkSession(); @@ -61,7 +48,7 @@ public NutsCommandLine parse(String line) { } private String[] parseCommandLineArr(String line) { - NutsShellFamily f = getCommandlineFamily(); + NutsShellFamily f = getShellFamily(); if (f == null) { f = NutsShellFamily.getCurrent(); } @@ -84,12 +71,6 @@ public NutsCommandLine create(List args) { return new DefaultNutsCommandLine(getSession(), args, null); } - @Override - public NutsArgumentCandidateBuilder createCandidate() { - checkSession(); - return new DefaultNutsArgumentCandidateBuilder(); - } - @Override public NutsArgument createArgument(String argument) { checkSession(); @@ -114,10 +95,6 @@ public static NutsArgument createArgument0(NutsSession ws, String argument, char return new DefaultNutsArgument(argument, eq); } - public static NutsArgumentCandidate createCandidate0(NutsWorkspace ws, String value, String label) { - return new NutsDefaultArgumentCandidate(value, NutsBlankable.isBlank(label) ? value : label); - } - public static NutsArgumentName createName0(NutsSession session, String type, String label) { if (type == null) { type = ""; @@ -164,9 +141,7 @@ public static NutsArgumentName createName0(NutsSession session, String type, Str } @Override - public NutsCommandHistoryBuilder createHistory() { - checkSession(); - return new NutsCommandHistoryBuilderImpl(getSession()); + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; } - } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsWorkspaceLocationManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsWorkspaceLocationManager.java index 37fb7cdb2..84822535c 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsWorkspaceLocationManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsWorkspaceLocationManager.java @@ -109,7 +109,7 @@ public String getHomeLocation(NutsHomeLocation location) { } @Override - public String getWorkspaceLocation() { + public NutsPath getWorkspaceLocation() { return model.getWorkspaceLocation(); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsWorkspaceLocationModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsWorkspaceLocationModel.java index 71087ea5f..66c8858a8 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsWorkspaceLocationModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/DefaultNutsWorkspaceLocationModel.java @@ -13,14 +13,14 @@ import java.util.Map; public class DefaultNutsWorkspaceLocationModel { - private NutsWorkspace ws; - private String workspaceLocation; - private NutsWorkspaceInitInformation info; + private final NutsWorkspace ws; + private final NutsPath workspaceLocation; + private final NutsWorkspaceInitInformation info; public DefaultNutsWorkspaceLocationModel(NutsWorkspace ws, NutsWorkspaceInitInformation info, String workspaceLocation) { this.ws = ws; this.info = info; - this.workspaceLocation = workspaceLocation; + this.workspaceLocation = NutsPath.of(workspaceLocation, NutsWorkspaceUtils.defaultSession(ws)); } public NutsWorkspace getWorkspace() { @@ -43,7 +43,7 @@ public void setHomeLocation(NutsHomeLocation homeType, String location, NutsSess } - public String getWorkspaceLocation() { + public NutsPath getWorkspaceLocation() { return workspaceLocation; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/ExtensionNonOption.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/ExtensionNonOption.java index 913e8995f..8866ca5d1 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/ExtensionNonOption.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/ExtensionNonOption.java @@ -42,9 +42,8 @@ public ExtensionNonOption(String name, NutsSession session) { @Override public List getCandidates(NutsCommandAutoComplete context) { - NutsCommandLineManager c=context.getSession().commandLine(); List all = new ArrayList<>(); - all.add(c.createCandidate(NutsConstants.Ids.NUTS_RUNTIME).build()); + all.add(new NutsArgumentCandidate(NutsConstants.Ids.NUTS_RUNTIME)); //should find all nuts with packaging "nuts-extension" return all; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/GroupNonOption.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/GroupNonOption.java index afadbd569..3ac5d79d1 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/GroupNonOption.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/GroupNonOption.java @@ -59,24 +59,23 @@ public GroupNonOption(String name) { @Override public List getCandidates(NutsCommandAutoComplete context) { - NutsCommandLineManager c=context.getSession().commandLine(); List all = new ArrayList<>(); NutsRepository repository=context.get(NutsRepository.class); NutsUserConfig securityEntityConfig=context.get(NutsUserConfig.class); if (securityEntityConfig != null) { for (String n : securityEntityConfig.getGroups()) { - all.add(c.createCandidate(n).build()); + all.add(new NutsArgumentCandidate(n)); } } else if (repository != null) { for (NutsUser nutsSecurityEntityConfig : repository.security().setSession(context.getSession()) .findUsers()) { - all.add(c.createCandidate(nutsSecurityEntityConfig.getUser()).build()); + all.add(new NutsArgumentCandidate(nutsSecurityEntityConfig.getUser())); } } else { for (NutsUser nutsSecurityEntityConfig : context.getSession().security() .setSession(context.getSession()) .findUsers()) { - all.add(c.createCandidate(nutsSecurityEntityConfig.getUser()).build()); + all.add(new NutsArgumentCandidate(nutsSecurityEntityConfig.getUser())); } } return all; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/NutsCommandHistoryBuilderImpl.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/NutsCommandHistoryBuilderImpl.java deleted file mode 100644 index e61f5b220..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/NutsCommandHistoryBuilderImpl.java +++ /dev/null @@ -1,63 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages and libraries - * for runtime execution. Nuts is the ultimate companion for maven (and other - * build managers) as it helps installing all package dependencies at runtime. - * Nuts is not tied to java and is a good choice to share shell scripts and - * other 'things' . Its based on an extensible architecture to help supporting a - * large range of sub managers / repositories. - *
- * - * Copyright [2020] [thevpc] Licensed under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law - * or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
==================================================================== - */ -package net.thevpc.nuts.runtime.core.app; - -import java.io.File; -import java.nio.file.Path; -import net.thevpc.nuts.NutsCommandHistory; -import net.thevpc.nuts.NutsCommandHistoryBuilder; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsWorkspace; - -/** - * - * @author vpc - */ -class NutsCommandHistoryBuilderImpl implements NutsCommandHistoryBuilder { - - private NutsSession session; - - public NutsCommandHistoryBuilderImpl(NutsSession session) { - this.session = session; - } - private Path path; - - @Override - public NutsCommandHistoryBuilder setPath(Path path) { - this.path = path; - return this; - } - - @Override - public NutsCommandHistoryBuilder setPath(File path) { - this.path = path==null?null:path.toPath(); - return this; - } - - @Override - public NutsCommandHistory build() { - return new NutsCommandHistoryImpl(session,path); - } - -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/NutsCommandHistoryImpl.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/NutsCommandHistoryImpl.java index 9c75e118a..2620e84a2 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/NutsCommandHistoryImpl.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/NutsCommandHistoryImpl.java @@ -23,14 +23,7 @@ */ package net.thevpc.nuts.runtime.core.app; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.UncheckedIOException; -import java.nio.file.Files; +import java.io.*; import java.nio.file.Path; import java.time.Instant; import java.util.ArrayList; @@ -38,7 +31,7 @@ import java.util.ListIterator; import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.core.util.CoreIOUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; /** * @@ -46,20 +39,35 @@ */ public class NutsCommandHistoryImpl implements NutsCommandHistory { + private NutsPath path; private NutsSession session; private List entries = new ArrayList<>(); - private Path path; - public NutsCommandHistoryImpl(NutsSession session, Path path) { + public NutsCommandHistoryImpl(NutsSession session) { this.session = session; + } + + @Override + public NutsCommandHistory setPath(Path path) { + this.path = path==null?null:NutsPath.of(path,session); + return this; + } + + @Override + public NutsCommandHistory setPath(File path) { + this.path = path==null?null:NutsPath.of(path,session); + return this; + } + + @Override + public NutsCommandHistory setPath(NutsPath path) { this.path = path; - if (path == null) { - if(session==null) { - throw new IllegalArgumentException("path cannot be null"); - }else{ - throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("path cannot be null")); - } - } + return this; + } + + @Override + public NutsPath getPath() { + return path; } @Override @@ -70,8 +78,11 @@ public int size() { @Override public void load() { entries.clear(); - if (Files.exists(path)) { - try (InputStream in = Files.newInputStream(path)) { + if(path==null){ + throw new NutsIllegalArgumentException(session, NutsMessage.plain("missing path")); + } + if (path.exists()) { + try (InputStream in = path.getInputStream()) { load(in); } catch (IOException ex) { throw new UncheckedIOException(ex); @@ -116,9 +127,14 @@ public void save(OutputStream outs) { @Override public void save() { - Path p = path.getParent(); - CoreIOUtils.mkdirs(p,session); - try (OutputStream out = Files.newOutputStream(path)) { + if(path==null){ + throw new NutsIllegalArgumentException(session, NutsMessage.plain("missing path")); + } + NutsPath p = path.getParent(); + if(p!=null){ + p.mkdir(true); + } + try (OutputStream out = path.getOutputStream()) { save(out); } catch (IOException ex) { throw new UncheckedIOException(ex); @@ -128,12 +144,8 @@ public void save() { @Override public void purge() { entries.clear(); - if (Files.exists(path)) { - try { - Files.delete(path); - } catch (IOException ex) { - throw new UncheckedIOException(ex); - } + if (path.exists()) { + path.delete(); } } @@ -152,4 +164,8 @@ public void add(Instant time, String line) { entries.add(new NutsCommandHistoryEntryImpl(entries.size(), line, time)); } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/PackagingNonOption.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/PackagingNonOption.java index 9a1ba8226..26bc61950 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/PackagingNonOption.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/PackagingNonOption.java @@ -28,7 +28,7 @@ import net.thevpc.nuts.NutsArgumentCandidate; import net.thevpc.nuts.NutsCommandAutoComplete; -import net.thevpc.nuts.NutsCommandLineManager; +import net.thevpc.nuts.NutsCommandLines; import java.util.ArrayList; import java.util.List; @@ -46,15 +46,14 @@ public PackagingNonOption(String name) { @Override public List getCandidates(NutsCommandAutoComplete context) { List all = new ArrayList<>(); - NutsCommandLineManager c=context.getSession().commandLine(); - all.add(c.createCandidate("jar").build()); - all.add(c.createCandidate("war").build()); - all.add(c.createCandidate("war").build()); - all.add(c.createCandidate("ear").build()); - all.add(c.createCandidate("nuts-extension").build()); - all.add(c.createCandidate("elf").build()); - all.add(c.createCandidate("pe").build()); - all.add(c.createCandidate("bin").build()); + all.add(new NutsArgumentCandidate("jar")); + all.add(new NutsArgumentCandidate("war")); + all.add(new NutsArgumentCandidate("war")); + all.add(new NutsArgumentCandidate("ear")); + all.add(new NutsArgumentCandidate("nuts-extension")); + all.add(new NutsArgumentCandidate("elf")); + all.add(new NutsArgumentCandidate("pe")); + all.add(new NutsArgumentCandidate("bin")); return all; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/PermissionNonOption.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/PermissionNonOption.java index 779185dd3..68f4b065b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/PermissionNonOption.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/PermissionNonOption.java @@ -51,9 +51,8 @@ public PermissionNonOption(String name, String user, boolean existing) { @Override public List getCandidates(NutsCommandAutoComplete context) { List all = new ArrayList<>(); - NutsCommandLineManager c= context.getSession().commandLine(); for (String r : NutsConstants.Permissions.ALL) { - all.add(c.createCandidate(r).build()); + all.add(new NutsArgumentCandidate(r)); } Iterator i = all.iterator(); NutsRepository repository=context.get(NutsRepository.class); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/RepositoryNonOption.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/RepositoryNonOption.java index 9cee55222..99c92a133 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/RepositoryNonOption.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/RepositoryNonOption.java @@ -46,17 +46,16 @@ public RepositoryNonOption(String name) { @Override public List getCandidates(NutsCommandAutoComplete context) { List all = new ArrayList<>(); - NutsCommandLineManager c = context.getSession().commandLine(); NutsRepository repository=context.get(NutsRepository.class); if(repository!=null){ if (repository.config().isSupportedMirroring()) { for (NutsRepository repo : repository.config().setSession(context.getSession()).getMirrors()) { - all.add(c.createCandidate(repo.getName()).build()); + all.add(new NutsArgumentCandidate(repo.getName())); } } }else{ for (NutsRepository repo : context.getSession().repos().setSession(context.getSession()).getRepositories()) { - all.add(c.createCandidate(repo.getName()).build()); + all.add(new NutsArgumentCandidate(repo.getName())); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/RepositoryTypeNonOption.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/RepositoryTypeNonOption.java index 5f7a4d28a..dc35a86d9 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/RepositoryTypeNonOption.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/RepositoryTypeNonOption.java @@ -54,9 +54,8 @@ public List getCandidates(NutsCommandAutoComplete context } } List all = new ArrayList<>(); - NutsCommandLineManager c = context.getSession().commandLine(); for (String v : allValid) { - all.add(c.createCandidate(v).build()); + all.add(new NutsArgumentCandidate(v)); } return all; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/UserNonOption.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/UserNonOption.java index 276321eff..fc2d2c02d 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/UserNonOption.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/app/UserNonOption.java @@ -40,19 +40,18 @@ public UserNonOption(String name) { @Override public List getCandidates(NutsCommandAutoComplete context) { List all = new ArrayList<>(); - NutsCommandLineManager c = context.getSession().commandLine(); NutsRepository repository = context.get(NutsRepository.class); if (repository != null) { for (NutsUser nutsSecurityEntityConfig : repository.security() .setSession(context.getSession()) .findUsers()) { - all.add(c.createCandidate(nutsSecurityEntityConfig.getUser()).build()); + all.add(new NutsArgumentCandidate(nutsSecurityEntityConfig.getUser())); } } else { for (NutsUser nutsSecurityEntityConfig : context.getSession().security() .setSession(context.getSession()) .findUsers()) { - all.add(c.createCandidate(nutsSecurityEntityConfig.getUser()).build()); + all.add(new NutsArgumentCandidate(nutsSecurityEntityConfig.getUser())); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/commands/ws/AbstractNutsStream.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/commands/ws/AbstractNutsStream.java index 1cf14a31d..e096a3afe 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/commands/ws/AbstractNutsStream.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/commands/ws/AbstractNutsStream.java @@ -108,7 +108,7 @@ public T required() throws NutsNotFoundException { if (it.hasNext()) { return it.next(); } - NutsId n = session.id().parser().setLenient(true).parse(nutsBase); + NutsId n = NutsIdParser.of(session).setLenient(true).parse(nutsBase); if (n != null) { throw new NutsNotFoundException(session, n); } @@ -125,7 +125,7 @@ public T singleton() { } return t; } else { - NutsId nid = session.id().parser().setLenient(true).parse(nutsBase); + NutsId nid = NutsIdParser.of(session).setLenient(true).parse(nutsBase); if (nid != null) { throw new NutsNotFoundException(session, nid); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/commands/ws/DefaultNutsQueryBaseOptions.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/commands/ws/DefaultNutsQueryBaseOptions.java index 240bc0557..b6517badf 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/commands/ws/DefaultNutsQueryBaseOptions.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/commands/ws/DefaultNutsQueryBaseOptions.java @@ -287,7 +287,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { case "--repository": { String val = cmdLine.nextString().getValue().getString(); if (enabled) { - addRepositoryFilter(getSession().filters().repository().byName(val)); + addRepositoryFilter(NutsRepositoryFilters.of(getSession()).byName(val)); } return true; } @@ -407,7 +407,7 @@ public NutsDependencyFilter getDependencyFilter() { // @Override public T setDependencyFilter(String filter) { checkSession(); - this.dependencyFilter = getSession().dependency().filter().byExpression(filter); + this.dependencyFilter = NutsDependencyFilters.of(getSession()).parse(filter); return (T) this; } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultFctNode.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultFctNode.java new file mode 100644 index 000000000..d6f96c5c8 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultFctNode.java @@ -0,0 +1,58 @@ +package net.thevpc.nuts.runtime.core.eval; + +import net.thevpc.nuts.NutsIllegalArgumentException; +import net.thevpc.nuts.NutsMessage; +import net.thevpc.nuts.NutsExpr; + +import java.util.Arrays; +import java.util.stream.Collectors; + +public class DefaultFctNode implements NutsExpr.Node { + private final String name; + private final NutsExpr.Node[] args; + public DefaultFctNode(String name,NutsExpr.Node[] args) { + this.name = name; + this.args = args; + } + + public NutsExpr.Node getArg(int index) { + if (index >= args.length) { + throw new IllegalArgumentException("Missing argument " + (index + 1) + " for " + name); + } + return args[index]; + } + + public NutsExpr.Node[] getArgs() { + return args; + } + + @Override + public NutsExpr.NodeType getType() { + return NutsExpr.NodeType.FUNCTION; + } + + @Override + public NutsExpr.Node[] getChildren() { + return new NutsExpr.Node[0]; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return name + "(" + + Arrays.stream(args).map(Object::toString).collect(Collectors.joining(",")) + + ')'; + } + + @Override + public Object eval(NutsExpr context) { + NutsExpr.Fct f = context.getFunction(getName()); + if (f != null) { + return f.eval(getName(), getArgs(), context.newChild()); + } + throw new NutsIllegalArgumentException(context.getSession(), NutsMessage.cstyle("function not found %s", getName())); + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultLiteralNode.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultLiteralNode.java new file mode 100644 index 000000000..776371f1b --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultLiteralNode.java @@ -0,0 +1,68 @@ +package net.thevpc.nuts.runtime.core.eval; + +import net.thevpc.nuts.NutsExpr; + +public class DefaultLiteralNode implements NutsExpr.Node { + private final Object lit; + + @Override + public NutsExpr.NodeType getType() { + return NutsExpr.NodeType.LITERAL; + } + + + @Override + public NutsExpr.Node[] getChildren() { + return new NutsExpr.Node[0]; + } + + @Override + public String getName() { + return null; + } + + public DefaultLiteralNode(Object lit) { + this.lit = lit; + } + + @Override + public Object eval(NutsExpr context) { + return lit; + } + + @Override + public String toString() { + if (lit == null) { + return "null"; + } + if (lit instanceof String) { + StringBuilder sb = new StringBuilder("\""); + for (char c : lit.toString().toCharArray()) { + switch (c) { + case '"': { + sb.append("\\\""); + break; + } + case '\\': { + sb.append("\\\\"); + break; + } + case '\n': { + sb.append("\\n"); + break; + } + case '\r': { + sb.append("\\r"); + break; + } + default: { + sb.append(c); + } + } + } + sb.append("\""); + return sb.toString(); + } + return String.valueOf(lit); + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultNutsExpr.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultNutsExpr.java new file mode 100644 index 000000000..fe60c65d2 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultNutsExpr.java @@ -0,0 +1,838 @@ +package net.thevpc.nuts.runtime.core.eval; + +import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsSupportLevelContext; +import org.jetbrains.annotations.NotNull; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.math.RoundingMode; +import java.util.*; + +public class DefaultNutsExpr implements NutsExpr { + final static Map defaultFunctions = new HashMap<>(); + final static Map defaultPrefixOps = new HashMap<>(); + final static Map defaultInfixOps = new HashMap<>(); + final static Map defaultPostOps = new HashMap<>(); + + private final NutsSession session; + private final Map userFunctions = new LinkedHashMap<>(); + private final Map userFunctionsFlag = new HashMap<>(); + + private final Map prefixOps = new LinkedHashMap<>(); + private final Map prefixOpsFlag = new HashMap<>(); + private final Map infixOps = new LinkedHashMap<>(); + private final Map infixOpsFlag = new HashMap<>(); + private final Map postfixOps = new LinkedHashMap<>(); + private final Map postfixOpsFlag = new HashMap<>(); + + private final Map userVars = new LinkedHashMap<>(); + private final Map userVarsFlag = new HashMap<>(); + private NutsExpr parent; + + { + addDefaultOp(new AndFctNode(), "and", "&", "&&"); + addDefaultOp(new OrFctNode(), "or", "|", "||"); + addDefaultOp(new NotFctNode(), "not", "!"); + addDefaultOp(new LTFctNode(), "lt", "<"); + addDefaultOp(new LTEFctNode(), "lte", "<="); + addDefaultOp(new GTFctNode(), "gt", ">"); + addDefaultOp(new GTEFctNode(), "gte", ">="); + addDefaultOp(new EQFctNode(), "eq", "=", "=="); + addDefaultOp(new NEQFctNode(), "neq", "!=", "!==", "<>"); + addDefaultOp(new PlusFctNode(), "plus", "+"); + addDefaultOp(new MinusFctNode(), "minus", "-"); + addDefaultOp(new MulFctNode(), "multiply", "mul", "*"); + addDefaultOp(new DivFctNode(), "divide", "div", "/"); + addDefaultFct(new Fct() { + @Override + public Object eval(String name, Node[] args, NutsExpr context) { + Object o = args[0].eval(context); + return EvalUtils.castToString(o); + } + }, "string"); + addDefaultFct(new Fct() { + @Override + public Object eval(String name, Node[] args, NutsExpr context) { + Object o = args[0].eval(context); + return EvalUtils.castToBoolean(o); + } + }, "boolean"); + addDefaultFct(new Fct() { + @Override + public Object eval(String name, Node[] args, NutsExpr context) { + Object o = args[0].eval(context); + return EvalUtils.castToDouble(o); + } + }, "double"); + addDefaultFct(new Fct() { + @Override + public Object eval(String name, Node[] args, NutsExpr context) { + Object o = args[0].eval(context); + return EvalUtils.castToLong(o); + } + }, "long"); + addDefaultFct(new Fct() { + @Override + public Object eval(String name, Node[] args, NutsExpr context) { + Object o = args[0].eval(context); + return (int) EvalUtils.castToLong(o); + } + }, "int"); + addDefaultFct(new Fct() { + @Override + public Object eval(String name, Node[] args, NutsExpr context) { + Object o = args[0].eval(context); + return (float) EvalUtils.castToDouble(o); + } + }, "float"); + addDefaultFct(new Fct() { + @Override + public Object eval(String name, Node[] args, NutsExpr context) { + Object o = args[0].eval(context); + return EvalUtils.isNumber(o); + } + }, "isNumber"); + addDefaultFct(new Fct() { + @Override + public Object eval(String name, Node[] args, NutsExpr context) { + Object o = args[0].eval(context); + return EvalUtils.isBoolean(o); + } + }, "isBoolean"); + } + + public DefaultNutsExpr(NutsSession session) { + this.session = session; + } + + public DefaultNutsExpr(NutsExpr parent) { + this.session = parent.getSession(); + this.parent = parent; + } + + private static void addDefaultFct(Fct fct, String... names) { + for (String name : names) { + defaultFunctions.put(name, fct); + } + } + + private static void addDefaultOp(AbstractOp op, String... names) { + for (String name : names) { + OpImpl opImpl = new OpImpl(name, op.type, op.precedence, op.rightAssociative,op); + getStaticOps(op.type).put(name, opImpl); + } + } + + public static String wrapPars(Node n) { + if (n instanceof DefaultLiteralNode) { + String s = n.toString(); + if (s.charAt(0) == '-' || s.charAt(0) == '+') { + return "(" + s + ")"; + } + return s; + } + if (n instanceof DefaultVarNode) { + return n.toString(); + } + if (n instanceof DefaultOpNode) { + String s = n.toString(); + switch (s.charAt(0)) { + case '-': + case '+': + case '!': { + return "(" + s + ")"; + } + } + return s; + } + return "(" + n + ")"; + } + + public static Map getStaticOps(NutsExpr.OpType type) { + return type == NutsExpr.OpType.PREFIX ? DefaultNutsExpr.defaultPrefixOps : + type == NutsExpr.OpType.INFIX ? DefaultNutsExpr.defaultInfixOps : + DefaultNutsExpr.defaultPostOps; + } + + @Override + public Node parse(String expression) { + return new SyntaxParser(expression, getEvalWithCache()).parse(); + } + + @Override + public NutsSession getSession() { + return session; + } + + @Override + public NutsExpr.Var getVar(String name) { + NutsExpr.Var f = userVars.get(name); + if (f != null) { + return f; + } + Boolean s = userVarsFlag.get(name); + if (s != null && !s.booleanValue()) { + return null; + } + if (parent != null) { + return parent.getVar(name); + } else { + return null; + } + } + + @Override + public void setFunction(String name, NutsExpr.Fct impl) { + if (!NutsBlankable.isBlank(name)) { + if (impl == null) { + if (userFunctions.containsKey(name)) { + userFunctions.remove(name); + } else { + userFunctionsFlag.put(name, false); + } + } else { + userFunctions.remove(name); + } + } else { + userFunctions.put(name, impl); + } + } + + @Override + public void unsetFunction(String name) { + setFunction(name, null); + } + + @Override + public NutsExpr.Fct getFunction(String name) { + NutsExpr.Fct f = userFunctions.get(name); + if (f != null) { + return f; + } + Boolean s = userFunctionsFlag.get(name); + if (s != null && !s.booleanValue()) { + return null; + } + if (parent != null) { + return parent.getFunction(name); + } else { + return DefaultNutsExpr.defaultFunctions.get(name); + } + } + + @Override + public String[] getFunctionNames() { + LinkedHashSet all = new LinkedHashSet<>(); + for (Map.Entry e : userFunctions.entrySet()) { + all.add(e.getKey()); + } + if (parent != null) { + for (String f : parent.getFunctionNames()) { + Boolean s = userFunctionsFlag.get(f); + if (s == null || s.booleanValue()) { + all.add(f); + } + } + } else { + for (String f : DefaultNutsExpr.defaultFunctions.keySet()) { + Boolean s = userFunctionsFlag.get(f); + if (s == null || s.booleanValue()) { + all.add(f); + } + } + } + return all.toArray(new String[0]); + } + + @Override + public Object evalFunction(String fctName, Object... args) { + NutsExpr.Fct f = getFunction(fctName); + if (f == null) { + throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("function not found %s", fctName)); + } + return f.eval(fctName, Arrays.stream(args).map(DefaultLiteralNode::new).toArray(NutsExpr.Node[]::new), newChild()); + } + + public void setOperator(String name, OpType type, int precedence, boolean rightAssociative, Fct fct) { + if (NutsBlankable.isBlank(name)) { + throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("empty operator")); + } + //TODO: should check supported op!! + if (fct == null) { + NutsExpr.OpType[] allTypes = type == null ? NutsExpr.OpType.values() : new NutsExpr.OpType[]{type}; + for (NutsExpr.OpType type0 : allTypes) { + Map ops = getOps(type0); + Map opsFlag = getOpsFlag(type0); + if (ops.containsKey(name)) { + ops.remove(name); + } else { + opsFlag.put(name, false); + } + } + } else { + if (type == null) { + throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("missing op type")); + } + Map ops = getOps(type); + ops.put(name, new OpImpl(name, type, precedence, rightAssociative, fct)); + } + } + + @Override + public NutsExpr.Op getOperator(String opName, NutsExpr.OpType type) { + NutsExpr.Op f = getOps(type).get(opName); + if (f != null) { + return f; + } + Boolean b = getOpsFlag(type).get(opName); + if (b != null && !b) { + return null; + } + if (parent != null) { + return parent.getOperator(opName, type); + } else { + return getStaticOps(type).get(opName); + } + } + + @Override + public void unsetOperator(String name, OpType type) { + setOperator(name, type, -1, false, null); + } + + @Override + public String[] getOperatorNames(NutsExpr.OpType type) { + if (type == null) { + LinkedHashSet all = new LinkedHashSet<>(); + for (OpType value : OpType.values()) { + all.addAll(Arrays.asList(getOperatorNames(value))); + } + return all.toArray(new String[0]); + } + LinkedHashSet all = new LinkedHashSet<>(); + Map ops = getOps(type); + + Map opsFlag = getOpsFlag(type); + + for (Map.Entry e : ops.entrySet()) { + all.add(e.getKey()); + } + if (parent != null) { + for (String f : parent.getFunctionNames()) { + Boolean s = opsFlag.get(f); + if (s == null || s.booleanValue()) { + all.add(f); + } + } + } else { + for (String f : + getStaticOps(type) + .keySet()) { + Boolean s = opsFlag.get(f); + if (s == null || s.booleanValue()) { + all.add(f); + } + } + } + return all.toArray(new String[0]); + } + + @Override + public void setVar(String name, NutsExpr.Var impl) { + if (!NutsBlankable.isBlank(name)) { + if (impl == null) { + if (userVars.containsKey(name)) { + userVars.remove(name); + } else { + userVarsFlag.put(name, false); + } + } else { + userVars.remove(name); + } + } else { + userVars.put(name, impl); + } + } + + @Override + public Object evalVar(String fctName) { + NutsExpr.Var f = getVar(fctName); + if (f == null) { + throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("var not found %s", fctName)); + } + return f.get(fctName, this); + } + + public NutsExpr newChild() { + return new DefaultNutsExpr(this); + } + + @Override + public Object evalNode(NutsExpr.Node node) { + return node.eval(this); + } + + @NotNull + private NutsExprWithCache getEvalWithCache() { + return new NutsExprWithCache(this); + } + + private Map getOpsFlag(NutsExpr.OpType type) { + return type == NutsExpr.OpType.PREFIX ? this.prefixOpsFlag : + type == NutsExpr.OpType.INFIX ? this.infixOpsFlag : + postfixOpsFlag; + } + + private Map getOps(NutsExpr.OpType type) { + return type == NutsExpr.OpType.PREFIX ? this.prefixOps : + type == NutsExpr.OpType.INFIX ? this.infixOps : + postfixOps; + } + + private abstract class BinCompareFctNode extends AbstractOp { + public BinCompareFctNode(String name, int precedence) { + super(name, precedence, false,OpType.INFIX); + } + + @Override + public Object eval(String name, Node[] args, NutsExpr e) { + Object a = args[0].eval(e); + Object b = args[1].eval(e); + if (EvalUtils.isNumber(a) && EvalUtils.isNumber(b)) { + return compare(EvalUtils.castToNumber(a).doubleValue(), EvalUtils.castToNumber(b).doubleValue()); + } + if (EvalUtils.isBoolean(a) && EvalUtils.isBoolean(b)) { + return compare(EvalUtils.castToNumber(a).doubleValue(), EvalUtils.castToNumber(b).doubleValue()); + } + String aa = EvalUtils.castToString(a); + String bb = EvalUtils.castToString(b); + if (aa == null) { + aa = ""; + } + if (bb == null) { + bb = ""; + } + return compare(aa.length(), bb.length()); + } + + protected final boolean compare(Number a, Number b) { + if (EvalUtils.isBig(a) || EvalUtils.isBig(b)) { + if (EvalUtils.isFloat(a) || EvalUtils.isFloat(b)) { + BigDecimal aa = (a instanceof BigDecimal) ? ((BigDecimal) a) : new BigDecimal(a.toString()); + BigDecimal bb = (b instanceof BigDecimal) ? ((BigDecimal) b) : new BigDecimal(b.toString()); + return evalBigDecimal(aa, bb); + } + BigInteger aa = (a instanceof BigInteger) ? ((BigInteger) a) : new BigInteger(a.toString()); + BigInteger bb = (b instanceof BigInteger) ? ((BigInteger) b) : new BigInteger(b.toString()); + return evalBigInteger(aa, bb); + } else { + if (EvalUtils.isFloat(a) || EvalUtils.isFloat(b)) { + double aa = a.doubleValue(); + double bb = b.doubleValue(); + return evalFloat(aa, bb); + } + long aa = a.longValue(); + long bb = b.longValue(); + return evalOrdinal(aa, bb); + } + } + + protected abstract boolean evalOrdinal(long a, long b); + + protected abstract boolean evalFloat(double a, double b); + + protected abstract boolean evalBigDecimal(BigDecimal a, BigDecimal b); + + protected abstract boolean evalBigInteger(BigInteger a, BigInteger b); + } + + private abstract class BinArithFctNode extends AbstractOp { + public BinArithFctNode(String name, int precedence) { + super(name, precedence, false,OpType.INFIX); + } + + @Override + public Object eval(String name, Node[] args, NutsExpr e) { + Object a = args[0].eval(e); + Object b = args[1].eval(e); + if (EvalUtils.isNumber(a) && EvalUtils.isNumber(b)) { + return evalAny(EvalUtils.castToNumber(a).doubleValue(), EvalUtils.castToNumber(b).doubleValue()); + } + if (EvalUtils.isBoolean(a) && EvalUtils.isBoolean(b)) { + return evalAny(EvalUtils.castToNumber(a).doubleValue(), EvalUtils.castToNumber(b).doubleValue()); + } + String aa = EvalUtils.castToString(a); + String bb = EvalUtils.castToString(b); + if (aa == null) { + aa = ""; + } + if (bb == null) { + bb = ""; + } + return evalAny(aa.length(), bb.length()); + } + + protected final Number evalAny(Number a, Number b) { + if (EvalUtils.isBig(a) || EvalUtils.isBig(b)) { + if (EvalUtils.isFloat(a) || EvalUtils.isFloat(b)) { + BigDecimal aa = (a instanceof BigDecimal) ? ((BigDecimal) a) : new BigDecimal(a.toString()); + BigDecimal bb = (b instanceof BigDecimal) ? ((BigDecimal) b) : new BigDecimal(b.toString()); + return evalBigDecimal(aa, bb); + } + BigInteger aa = (a instanceof BigInteger) ? ((BigInteger) a) : new BigInteger(a.toString()); + BigInteger bb = (b instanceof BigInteger) ? ((BigInteger) b) : new BigInteger(b.toString()); + return evalBigInteger(aa, bb); + } else { + if (EvalUtils.isFloat(a) || EvalUtils.isFloat(b)) { + double aa = a.doubleValue(); + double bb = b.doubleValue(); + return evalFloat(aa, bb); + } + long aa = a.longValue(); + long bb = b.longValue(); + return evalOrdinal(aa, bb); + } + } + + protected abstract long evalOrdinal(long a, long b); + + protected abstract double evalFloat(double a, double b); + + protected abstract BigDecimal evalBigDecimal(BigDecimal a, BigDecimal b); + + protected abstract BigInteger evalBigInteger(BigInteger a, BigInteger b); + } + + private abstract class AbstractOp implements Fct { + private final OpType type; + private final String name; + private final int precedence; + private final boolean rightAssociative; + + public AbstractOp(String name, int precedence, boolean rightAssociative,OpType type) { + this.name = name; + this.type = type; + this.precedence = precedence; + this.rightAssociative = rightAssociative; + } + + public OpType getOpType() { + return type; + } + + public int getPrecedence() { + return precedence; + } + } + + private class AndFctNode extends AbstractOp { + public AndFctNode() { + super("&&", 40, false,OpType.INFIX); + } + + @Override + public Object eval(String name, Node[] args, NutsExpr context) { + for (Node arg : args) { + if (!EvalUtils.castToBoolean(arg.eval(context))) { + return false; + } + } + return true; + } + } + + private class OrFctNode extends AbstractOp { + public OrFctNode() { + super("or", 30,false, OpType.INFIX); + } + + @Override + public Object eval(String name, Node[] args, NutsExpr e) { + for (Node arg : args) { + if (EvalUtils.castToBoolean(arg.eval(e))) { + return true; + } + } + return false; + } + } + + private class NotFctNode extends AbstractOp { + public NotFctNode() { + super("!", 130,true, OpType.PREFIX); + } + + @Override + public Object eval(String name, Node[] args, NutsExpr e) { + return !EvalUtils.castToBoolean(args[0].eval(e)); + } + } + + private class LTFctNode extends BinCompareFctNode { + + public LTFctNode() { + super("lt", 90); + } + + @Override + protected boolean evalOrdinal(long a, long b) { + return a < b; + } + + @Override + protected boolean evalFloat(double a, double b) { + return a < b; + } + + @Override + protected boolean evalBigDecimal(BigDecimal a, BigDecimal b) { + return a.compareTo(b) < 0; + } + + @Override + protected boolean evalBigInteger(BigInteger a, BigInteger b) { + return a.compareTo(b) < 0; + } + } + + private class LTEFctNode extends BinCompareFctNode { + public LTEFctNode() { + super("lte", 90); + } + + @Override + protected boolean evalOrdinal(long a, long b) { + return a <= b; + } + + @Override + protected boolean evalFloat(double a, double b) { + return a <= b; + } + + @Override + protected boolean evalBigDecimal(BigDecimal a, BigDecimal b) { + return a.compareTo(b) <= 0; + } + + @Override + protected boolean evalBigInteger(BigInteger a, BigInteger b) { + return a.compareTo(b) <= 0; + } + } + + private class GTFctNode extends BinCompareFctNode { + public GTFctNode() { + super("gt", 90); + } + + @Override + protected boolean evalOrdinal(long a, long b) { + return a > b; + } + + @Override + protected boolean evalFloat(double a, double b) { + return a > b; + } + + @Override + protected boolean evalBigDecimal(BigDecimal a, BigDecimal b) { + return a.compareTo(b) > 0; + } + + @Override + protected boolean evalBigInteger(BigInteger a, BigInteger b) { + return a.compareTo(b) > 0; + } + } + + private class GTEFctNode extends BinCompareFctNode { + public GTEFctNode() { + super("gte", 90); + } + + @Override + protected boolean evalOrdinal(long a, long b) { + return a >= b; + } + + @Override + protected boolean evalFloat(double a, double b) { + return a >= b; + } + + @Override + protected boolean evalBigDecimal(BigDecimal a, BigDecimal b) { + return a.compareTo(b) >= 0; + } + + @Override + protected boolean evalBigInteger(BigInteger a, BigInteger b) { + return a.compareTo(b) >= 0; + } + } + + private class EQFctNode extends BinCompareFctNode { + public EQFctNode() { + super("eq", 80); + } + + @Override + protected boolean evalOrdinal(long a, long b) { + return a == b; + } + + @Override + protected boolean evalFloat(double a, double b) { + return a == b; + } + + @Override + protected boolean evalBigDecimal(BigDecimal a, BigDecimal b) { + return a.compareTo(b) == 0; + } + + @Override + protected boolean evalBigInteger(BigInteger a, BigInteger b) { + return a.compareTo(b) == 0; + } + } + + private class NEQFctNode extends BinCompareFctNode { + public NEQFctNode() { + super("neq", 80); + } + + @Override + protected boolean evalOrdinal(long a, long b) { + return a != b; + } + + @Override + protected boolean evalFloat(double a, double b) { + return a != b; + } + + @Override + protected boolean evalBigDecimal(BigDecimal a, BigDecimal b) { + return a.compareTo(b) != 0; + } + + @Override + protected boolean evalBigInteger(BigInteger a, BigInteger b) { + return a.compareTo(b) != 0; + } + } + + private class PlusFctNode extends BinArithFctNode { + public PlusFctNode() { + super("plus", 110); + } + + @Override + protected long evalOrdinal(long a, long b) { + return a + b; + } + + @Override + protected double evalFloat(double a, double b) { + return a + b; + } + + @Override + protected BigDecimal evalBigDecimal(BigDecimal a, BigDecimal b) { + return a.add(b); + } + + @Override + protected BigInteger evalBigInteger(BigInteger a, BigInteger b) { + return a.add(b); + } + } + + private class MinusFctNode extends BinArithFctNode { + public MinusFctNode() { + super("minus", 110); + } + + @Override + protected long evalOrdinal(long a, long b) { + return a - b; + } + + @Override + protected double evalFloat(double a, double b) { + return a - b; + } + + @Override + protected BigDecimal evalBigDecimal(BigDecimal a, BigDecimal b) { + return a.subtract(b); + } + + @Override + protected BigInteger evalBigInteger(BigInteger a, BigInteger b) { + return a.subtract(b); + } + } + + private class MulFctNode extends BinArithFctNode { + public MulFctNode() { + super("multiply", 120); + } + + @Override + protected long evalOrdinal(long a, long b) { + return a * b; + } + + @Override + protected double evalFloat(double a, double b) { + return a * b; + } + + @Override + protected BigDecimal evalBigDecimal(BigDecimal a, BigDecimal b) { + return a.multiply(b); + } + + @Override + protected BigInteger evalBigInteger(BigInteger a, BigInteger b) { + return a.multiply(b); + } + } + + private class DivFctNode extends BinArithFctNode { + public DivFctNode() { + super("divide", 120); + } + + @Override + protected long evalOrdinal(long a, long b) { + return a / b; + } + + @Override + protected double evalFloat(double a, double b) { + return a / b; + } + + @Override + protected BigDecimal evalBigDecimal(BigDecimal a, BigDecimal b) { + return a.divide(b, RoundingMode.HALF_EVEN); + } + + @Override + protected BigInteger evalBigInteger(BigInteger a, BigInteger b) { + return a.divide(b); + } + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } +} + diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultOpNode.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultOpNode.java new file mode 100644 index 000000000..099918995 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultOpNode.java @@ -0,0 +1,86 @@ +package net.thevpc.nuts.runtime.core.eval; + +import net.thevpc.nuts.NutsExpr; +import net.thevpc.nuts.NutsIllegalArgumentException; +import net.thevpc.nuts.NutsMessage; + +import java.util.Arrays; +import java.util.stream.Collectors; + +public class DefaultOpNode implements NutsExpr.Node { + private final String name; + private final NutsExpr.Node[] args; + private final NutsExpr.OpType op; + private final int precedence; + + public DefaultOpNode(String name, NutsExpr.OpType type, int precedence, NutsExpr.Node[] args) { + this.op = type; + this.name = name; + this.precedence = precedence; + this.args = args; + } + + public NutsExpr.Node getArg(int index) { + if (index >= args.length) { + throw new IllegalArgumentException("Missing argument " + (index + 1) + " for " + name); + } + return args[index]; + } + + public NutsExpr.Node[] getArgs() { + return args; + } + + @Override + public NutsExpr.NodeType getType() { + return NutsExpr.NodeType.OPERATOR; + } + + @Override + public NutsExpr.Node[] getChildren() { + return args; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + switch (op) { + case PREFIX: { + return name + " " + DefaultNutsExpr.wrapPars(args[0]); + } + case POSTFIX: { + return DefaultNutsExpr.wrapPars(args[0]) + name; + } + case INFIX: { + if (args.length == 2) { + return DefaultNutsExpr.wrapPars(args[0]) + " " + name + " " + DefaultNutsExpr.wrapPars(args[1]); + } + if (args.length > 2) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < args.length; i++) { + if (i > 0) { + sb.append(" ").append(name).append(" "); + } + sb.append(DefaultNutsExpr.wrapPars(args[i])); + } + return sb.toString(); + } + } + } + return name + "(" + + Arrays.stream(args).map(Object::toString).collect(Collectors.joining(",")) + + ')'; + } + + @Override + public Object eval(NutsExpr context) { + NutsExpr.Fct f = context.getFunction(getName()); + if (f != null) { + return f.eval(getName(), getArgs(), context.newChild()); + } + throw new NutsIllegalArgumentException(context.getSession(), NutsMessage.cstyle("function not found %s", getName())); + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultVarNode.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultVarNode.java new file mode 100644 index 000000000..f59962309 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/DefaultVarNode.java @@ -0,0 +1,37 @@ +package net.thevpc.nuts.runtime.core.eval; + +import net.thevpc.nuts.NutsExpr; + +public class DefaultVarNode implements NutsExpr.Node { + private final String name; + + @Override + public NutsExpr.NodeType getType() { + return NutsExpr.NodeType.VARIABLE; + } + + + @Override + public NutsExpr.Node[] getChildren() { + return new NutsExpr.Node[0]; + } + + @Override + public String getName() { + return name; + } + + public DefaultVarNode(String name) { + this.name = name; + } + + @Override + public Object eval(NutsExpr context) { + return context.getVar(name); + } + + @Override + public String toString() { + return String.valueOf(name); + } +} diff --git a/toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/EvalUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/EvalUtils.java similarity index 67% rename from toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/EvalUtils.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/EvalUtils.java index e8ad3f0e4..afcafe295 100644 --- a/toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/EvalUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/EvalUtils.java @@ -1,68 +1,11 @@ -package net.thevpc.nuts.toolbox.nwork.filescanner.eval; +package net.thevpc.nuts.runtime.core.eval; import java.math.BigDecimal; import java.math.BigInteger; import java.util.regex.Pattern; public class EvalUtils { - public static Pattern glob(String o) { - while(true) { - if (o.endsWith("/**/*")) { - o = o.substring(0, o.length() - 5); - }else if (o.endsWith("/**")) { - o = o.substring(0, o.length() - 3); - }else if (o.endsWith("/*")) { - o = o.substring(0, o.length() - 2); - }else{ - break; - } - } - if(o.isEmpty()){ - return Pattern.compile(".*"); - } - StringBuilder sb=new StringBuilder(); - char[] chars = o.toCharArray(); - for (int i = 0; i < chars.length; i++) { - char c = chars[i]; - switch (c) { - case '.': - case '{': - case '}': - case '<': - case '>':{ - sb.append('\\'); - sb.append(c); - break; - } - case '*': { - if(i+1 < chars.length && chars[i+1]=='*'){ - if(i+2 < chars.length && chars[i+2]=='/'){ - i++; - if(i+3 < chars.length) { - sb.append(".*/"); - }else{ - sb.append(".*"); - } - }else { - i++; - sb.append(".*"); - } - }else { - sb.append("[^/]*"); - } - break; - } - case '?': { - sb.append("[^/]?"); - break; - } - default: { - sb.append(c); - } - } - } - return Pattern.compile(sb.toString()); - } + public static String castToString(Object o) { if (o == null) { return null; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/NutsExprWithCache.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/NutsExprWithCache.java new file mode 100644 index 000000000..f01cd3471 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/NutsExprWithCache.java @@ -0,0 +1,70 @@ +package net.thevpc.nuts.runtime.core.eval; + +import net.thevpc.nuts.NutsExpr; + +import java.util.*; + +class NutsExprWithCache { + NutsExpr evaluator; + int[] precedences; + Map> prefixOpByName = new HashMap<>(); + Map> infixOpByName = new HashMap<>(); + Map> postfixOpByName = new HashMap<>(); + + public NutsExprWithCache(DefaultNutsExpr evaluator) { + this.evaluator=evaluator; + SortedSet precedences = new TreeSet<>(); + for (NutsExpr.OpType opType : NutsExpr.OpType.values()) { + Map> byName = getByName(opType); + for (String f : ((NutsExpr) evaluator).getOperatorNames(opType)) { + NutsExpr.Op ff = ((NutsExpr) evaluator).getOperator(f, opType); + if (ff != null) { + int p = ff.getPrecedence(); + precedences.add(p); + Set li = byName.get(p); + if (li == null) { + li = new TreeSet<>(); + byName.put(p, li); + } + li.add(f); + } + } + } + this.precedences = precedences.stream().mapToInt(Integer::intValue).toArray(); + } + + public NutsExpr getEvaluator() { + return evaluator; + } + + private Map> getByName(NutsExpr.OpType opType) { + return opType == NutsExpr.OpType.PREFIX ? this.prefixOpByName + : opType == NutsExpr.OpType.INFIX ? this.infixOpByName + : this.postfixOpByName; + } + + public boolean isOp(String str, NutsExpr.OpType opType, int precIndex) { + return str!=null && getAt(opType, precIndex).contains(str); + } + + public Set getAt(NutsExpr.OpType opType, int precIndex) { + if (precIndex < precedences.length) { + Set q = getByName(opType).get(precedences[precIndex]); + if (q != null) { + return q; + } + } + return Collections.emptySet(); + } + + @Override + public String toString() { + return "NutsExprWithCache{" + + "evaluator=" + evaluator + + ", precedences=" + Arrays.toString(precedences) + + ", prefixOpByName=" + prefixOpByName + + ", infixOpByName=" + infixOpByName + + ", postfixOpByName=" + postfixOpByName + + '}'; + } +} diff --git a/toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/Token.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/NutsToken.java similarity index 68% rename from toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/Token.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/NutsToken.java index 8d60367f3..1c61370bd 100644 --- a/toolbox/nwork/src/main/java/net/thevpc/nuts/toolbox/nwork/filescanner/eval/Token.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/NutsToken.java @@ -1,6 +1,8 @@ -package net.thevpc.nuts.toolbox.nwork.filescanner.eval; +package net.thevpc.nuts.runtime.core.eval; -public class Token { +import net.thevpc.nuts.runtime.core.util.CoreStringUtils; + +public class NutsToken { /** * A constant indicating that the end of the stream has been read. @@ -27,21 +29,15 @@ public class Token { * made available as the part of the API in a future release. */ public static final int TT_NOTHING = -4; - public static final int TT_AND = -5; - public static final int TT_OR = -6; - public static final int TT_NOT = -7; - public static final int TT_OPEN_PAR = -8; - public static final int TT_CLOSE_PAR = -9; public static final int TT_STRING_LITERAL = -10; public static final int TT_SPACE = -11; - public static final int TT_COMMA = -12; - int ttype; - int lineno; - String sval; - double nval; + public int ttype; + public int lineno; + public String sval; + public double nval; - public Token(int ttype, String sval, double nval, int lineno) { + public NutsToken(int ttype, String sval, double nval, int lineno) { this.ttype = ttype; this.sval = sval; this.nval = nval; @@ -51,17 +47,17 @@ public Token(int ttype, String sval, double nval, int lineno) { @Override public String toString() { if(ttype>=32){ - return "Token{" + + return "NutsToken{" + "ttype='" + (char)ttype +"'"+ ", lineno=" + lineno + - ", sval='" + sval + '\'' + + ", sval=" + (sval==null?"null": CoreStringUtils.simpleQuote(sval)) + ", nval=" + nval + '}'; } - return "Token{" + + return "NutsToken{" + "ttype=" + ttype + ", lineno=" + lineno + - ", sval='" + sval + '\'' + + ", sval=" + (sval==null?"null": CoreStringUtils.simpleQuote(sval)) + ", nval=" + nval + '}'; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/OpImpl.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/OpImpl.java new file mode 100644 index 000000000..765ed4750 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/OpImpl.java @@ -0,0 +1,47 @@ +package net.thevpc.nuts.runtime.core.eval; + +import net.thevpc.nuts.NutsExpr; + +public class OpImpl implements NutsExpr.Op { + private final String name; + private NutsExpr.OpType type; + private int precedence; + private boolean rightAssociative; + private final NutsExpr.Fct fct; + + public OpImpl(String name, NutsExpr.OpType type, int precedence, boolean rightAssociative,NutsExpr.Fct fct) { + this.name = name; + this.type = type; + this.precedence = precedence; + this.rightAssociative = rightAssociative; + this.fct = fct; + } + + public boolean isLeftAssociative() { + return !rightAssociative; + } + + public boolean isRightAssociative() { + return rightAssociative; + } + + @Override + public String getName() { + return name; + } + + @Override + public NutsExpr.OpType getType() { + return type; + } + + @Override + public int getPrecedence() { + return precedence; + } + + @Override + public NutsExpr.Fct getFct() { + return fct; + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/SyntaxParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/SyntaxParser.java new file mode 100644 index 000000000..f0ed9c1e7 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/SyntaxParser.java @@ -0,0 +1,210 @@ +package net.thevpc.nuts.runtime.core.eval; + +import net.thevpc.nuts.NutsExpr; +import net.thevpc.nuts.NutsIllegalArgumentException; +import net.thevpc.nuts.NutsMessage; + +import java.io.StringReader; +import java.util.*; + +public class SyntaxParser { + TokenIterator tokens; + NutsExpr evaluator; + NutsExprWithCache withCache; + + public SyntaxParser(String anyStr, NutsExprWithCache withCache) { + this(new TokenIterator(new StringReader(anyStr == null ? "" : anyStr)), withCache); + } + + + public SyntaxParser(TokenIterator tokens, NutsExprWithCache withCache) { + this.tokens = tokens; + this.withCache = withCache; + this.evaluator = withCache.getEvaluator(); + } + + public NutsExpr.Node parse() { + NutsExpr.Node e = nextExpr(); + if(tokens.peek()!=null){ + throw new NutsIllegalArgumentException(evaluator.getSession(),NutsMessage.cstyle("unexpected token %s, after reading %s",tokens.peek(),e)); + } + return e; + } + + private NutsExpr.Node nextExpr() { + return nextNonTerminal(0); + } + + String opName(NutsToken t){ + if(t==null){ + return null; + } + switch (t.ttype){ + case '(': + case ')': + case NutsToken.TT_SPACE: + case NutsToken.TT_STRING_LITERAL: + case NutsToken.TT_EOL: + case NutsToken.TT_EOF: + case NutsToken.TT_NUMBER: + return null; + } + String s=t.sval; + if(s==null){ + s=String.valueOf((char)t.ttype); + } + return s; + } + + boolean isOp(NutsToken t, NutsExpr.OpType opType, int precedenceIndex){ + if(t==null){ + return false; + } + switch (t.ttype){ + case '(': + case ')': + case NutsToken.TT_SPACE: + case NutsToken.TT_STRING_LITERAL: + case NutsToken.TT_EOL: + case NutsToken.TT_EOF: + case NutsToken.TT_NUMBER: + return false; + } + String s=t.sval; + if(s==null){ + s=String.valueOf((char)t.ttype); + } + return withCache.isOp(s,opType, precedenceIndex); + } + private NutsExpr.Node nextNonTerminal(int precedenceIndex) { + if (precedenceIndex == withCache.precedences.length) { + return nextTerminal(); + } + NutsToken t = tokens.peek(); + if (t == null) { + return null; + } + NutsExpr.Node first = null; + if (isOp(t, NutsExpr.OpType.PREFIX, precedenceIndex)) { + tokens.next(); + NutsExpr.Node q = nextNonTerminal(precedenceIndex); + if (q == null) { + //error ? + //q=null + if (true) { + throw new NutsIllegalArgumentException(evaluator.getSession(), NutsMessage.cstyle("expected expression")); + } + } + first = new DefaultOpNode(opName(t), NutsExpr.OpType.PREFIX, withCache.precedences[precedenceIndex], new NutsExpr.Node[]{q}); + } else { + first = nextNonTerminal(precedenceIndex + 1); + } + if (first == null) { + throw new NutsIllegalArgumentException(evaluator.getSession(), NutsMessage.cstyle("expected expression")); + } + NutsToken infixOp = tokens.peek(); + if (isOp(infixOp, NutsExpr.OpType.INFIX, precedenceIndex)) { + tokens.next(); + //if right associative +// NutsExpr.Node q = nextNonTerminal(precedenceIndex); +// if (q == null) { +// throw new NutsIllegalArgumentException(evaluator.getSession(), NutsMessage.cstyle("expected expression")); +// } +// return new DefaultOpNode(opName(infixOp), NutsExpr.OpType.INFIX, withCache.precedences[precedenceIndex], new NutsExpr.Node[]{first,q}); + //else + NutsExpr.Node q = nextNonTerminal(precedenceIndex+1); + if (q == null) { + throw new NutsIllegalArgumentException(evaluator.getSession(), NutsMessage.cstyle("expected expression")); + } + first= new DefaultOpNode(opName(infixOp), NutsExpr.OpType.INFIX, withCache.precedences[precedenceIndex], new NutsExpr.Node[]{first,q}); + infixOp = tokens.peek(); + while(infixOp!=null && isOp(infixOp, NutsExpr.OpType.INFIX, precedenceIndex)){ + tokens.next(); + q = nextNonTerminal(precedenceIndex+1); + if (q == null) { + throw new NutsIllegalArgumentException(evaluator.getSession(), NutsMessage.cstyle("expected expression")); + } + first= new DefaultOpNode(opName(infixOp), NutsExpr.OpType.INFIX, withCache.precedences[precedenceIndex], new NutsExpr.Node[]{first,q}); + infixOp = tokens.peek(); + } + return first; + } else if (isOp(infixOp, NutsExpr.OpType.POSTFIX, precedenceIndex)) { + tokens.next(); + return new DefaultOpNode(opName(infixOp), NutsExpr.OpType.POSTFIX, withCache.precedences[precedenceIndex], new NutsExpr.Node[]{first}); + } else { + return first; + } + } + + private NutsExpr.Node nextTerminal() { + NutsToken t = tokens.peek(); + if (t == null) { + return null; + } + switch (t.ttype) { + case '(': { + tokens.next(); + t = tokens.peek(); + if (t.ttype == ')') { + throw new IllegalArgumentException("empty par"); + } + NutsExpr.Node e = nextExpr(); + if (e == null) { + throw new IllegalArgumentException("expected expr"); + } + return e; + } + case NutsToken.TT_WORD: { + String n = t.sval; + tokens.next(); + t = tokens.peek(); + if (t.ttype == '(') { + //function + List functionParams = new ArrayList<>(); + tokens.next(); + t = tokens.peek(); + if (t.ttype == ')') { + tokens.next(); + //okkay + } else { + NutsExpr.Node e = nextExpr(); + if (e == null) { + throw new IllegalArgumentException("expected expr"); + } + functionParams.add(e); + while (true) { + t = tokens.peek(); + if (t.ttype == ')') { + tokens.next(); + break; + } + if (t.ttype == ',') { + tokens.next(); + e = nextExpr(); + if (e == null) { + throw new IllegalArgumentException("expected expr"); + } + functionParams.add(e); + } else { + throw new IllegalArgumentException("expected ',' or ')'"); + } + } + } + return new DefaultFctNode(n, functionParams.toArray(new NutsExpr.Node[0])); + } else { + return new DefaultVarNode(n); + } + } + case NutsToken.TT_NUMBER: { + tokens.next(); + return new DefaultLiteralNode(t.nval); + } + case NutsToken.TT_STRING_LITERAL: { + tokens.next(); + return new DefaultLiteralNode(t.sval); + } + } + throw new NutsIllegalArgumentException(this.evaluator.getSession(),NutsMessage.cstyle("unsupported %s",t)); + } + +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/TokenIterator.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/TokenIterator.java new file mode 100644 index 000000000..8aea0df50 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/eval/TokenIterator.java @@ -0,0 +1,113 @@ +package net.thevpc.nuts.runtime.core.eval; + +import java.io.IOException; +import java.io.Reader; +import java.io.StreamTokenizer; +import java.util.Iterator; + +class TokenIterator implements Iterator { + private final StreamTokenizer st; + private NutsToken previous; + private boolean returnSpace=false; + private boolean returnComment=false; + private boolean doReplay; + + public TokenIterator(Reader r) { + this.st=new StreamTokenizer(r); + } + + public void pushBack() { + doReplay = true; + } + + public NutsToken peek() { + if (doReplay) { + return previous; + } + if (hasNext()) { + NutsToken n = next(); + doReplay = true; + return n; + } + return null; + } + + public NutsToken read() { + if (hasNext()) { + return next(); + } + return null; + } + + @Override + public boolean hasNext() { + if (doReplay) { + return true; + } + while (true) { + int nt = StreamTokenizer.TT_EOF; + try { + nt = st.nextToken(); + } catch (IOException e) { + return false; + } + switch (nt) { + case StreamTokenizer.TT_EOF: { + previous = null; + return false; + } + case ' ': + case '\t': + case StreamTokenizer.TT_EOL: { + if(returnSpace) { + previous = new NutsToken(NutsToken.TT_SPACE, st.sval, 0, st.lineno()); + return true; + } + break; + } + default: { + switch (st.ttype) { + case ' ': + case '\n': + case '\r': + case '\t': { + if(returnSpace) { + previous = new NutsToken(NutsToken.TT_SPACE, st.sval, 0, st.lineno()); + return true; + } + break; + } + case '\"': + case '\'': { + String sval = st.sval; + previous = new NutsToken(NutsToken.TT_STRING_LITERAL, sval, 0, st.lineno()); + return true; + } + case NutsToken.TT_NUMBER: { + previous = new NutsToken(NutsToken.TT_NUMBER, st.sval, st.nval, st.lineno()); + return true; + } + default:{ + String s = st.sval; + if(st.ttype>=32){ + s=String.valueOf((char)st.ttype); + }else{ + s=null; + } + previous = new NutsToken(st.ttype, s, 0, st.lineno()); + return true; + } + } + } + } + } + } + + @Override + public NutsToken next() { + if (doReplay) { + doReplay = false; + } + return previous; + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/AbstractNutsFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/AbstractNutsFilter.java index 8a272d912..46c5c7ed3 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/AbstractNutsFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/AbstractNutsFilter.java @@ -1,9 +1,6 @@ package net.thevpc.nuts.runtime.core.filters; -import net.thevpc.nuts.NutsFilter; -import net.thevpc.nuts.NutsFilterOp; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsWorkspace; +import net.thevpc.nuts.*; public abstract class AbstractNutsFilter implements NutsFilter { @@ -39,27 +36,27 @@ public NutsFilter[] getSubFilters() { @Override public NutsFilter or(NutsFilter other) { - return other == null ? this : getSession().filters().any(this, other); + return other == null ? this : NutsFilters.of(getSession()).any(this, other); } @Override public NutsFilter and(NutsFilter other) { - return other == null ? this : getSession().filters().all(this, other); + return other == null ? this : NutsFilters.of(getSession()).all(this, other); } @Override public NutsFilter neg() { - return getSession().filters().not(this); + return NutsFilters.of(getSession()).not(this); } @Override public T to(Class type) { - return getSession().filters().to(type, this); + return NutsFilters.of(getSession()).to(type, this); } @Override public Class getFilterType() { - return getSession().filters().detectType(this); + return NutsFilters.of(getSession()).detectType(this); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/CoreFilterUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/CoreFilterUtils.java index 77ba09f8b..be8473100 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/CoreFilterUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/CoreFilterUtils.java @@ -258,7 +258,7 @@ private static int orInts(Boolean a, Boolean b) { public static T[] getTopLevelFilters(NutsFilter idFilter, Class clazz, NutsSession ws) { return Arrays.stream(getTopLevelFilters(idFilter)) - .map(x -> ws.filters().as(clazz, x)) + .map(x -> NutsFilters.of(ws).as(clazz, x)) .toArray(value -> (T[]) Array.newInstance(clazz, value)); } @@ -274,15 +274,15 @@ public static NutsFilter[] getTopLevelFilters(NutsFilter idFilter) { public static NutsIdFilter idFilterOf(Map map, NutsIdFilter idFilter, NutsDescriptorFilter descriptorFilter, NutsSession ws) { - return (NutsIdFilter) ws.id().filter().nonnull(idFilter).and( + return (NutsIdFilter) NutsIdFilters.of(ws).nonnull(idFilter).and( CoreFilterUtils.createNutsDescriptorFilter(map, ws).and(descriptorFilter).to(NutsIdFilter.class) ); } public static NutsDescriptorFilter createNutsDescriptorFilter(String arch, String os, String osDist, String - platform, String desktopEnv, NutsSession ws) { - NutsDescriptorFilterManager d = ws.descriptor().filter(); + platform, String desktopEnv, NutsSession session) { + NutsDescriptorFilters d = NutsDescriptorFilters.of(session); return (NutsDescriptorFilter) d.byArch(arch) .and(d.byOs(os)) .and(d.byOsDist(osDist)) @@ -339,7 +339,7 @@ public static boolean matchesPackaging(String packaging, NutsDescriptor desc, Nu if (NutsBlankable.isBlank(desc.getPackaging())) { return true; } - NutsIdParser parser = session.id().parser(); + NutsIdParser parser = NutsIdParser.of(session); NutsId _v = parser.parse(packaging); NutsId _v2 = parser.parse(desc.getPackaging()); if (_v == null || _v2 == null) { @@ -405,7 +405,7 @@ public static boolean matchesArch(String current, NutsEnvCondition envCond, Nuts if (NutsBlankable.isBlank(current)) { return true; } - NutsIdParser parser = session.id().parser(); + NutsIdParser parser = NutsIdParser.of(session); NutsId currentId = parser.parse(current); String[] allConds = envCond.getArch(); if (allConds != null && allConds.length > 0) { @@ -434,7 +434,7 @@ public static boolean matchesOs(String os, NutsEnvCondition envCond, NutsSession if (NutsBlankable.isBlank(os)) { return true; } - NutsIdParser parser = session.id().parser(); + NutsIdParser parser = NutsIdParser.of(session); NutsId currentId = parser.parse(os); String[] allConds = envCond.getOs(); if (allConds != null && allConds.length > 0) { @@ -459,7 +459,7 @@ public static boolean matchesOsDist(String current, NutsEnvCondition envCond, Nu if (NutsBlankable.isBlank(current)) { return true; } - NutsIdParser parser = session.id().parser(); + NutsIdParser parser = NutsIdParser.of(session); NutsId currentId = parser.parse(current); String[] allConds = envCond.getOsDist(); if (allConds != null && allConds.length > 0) { @@ -493,7 +493,7 @@ public static boolean matchesPlatform(String current, NutsEnvCondition envCond, if (NutsBlankable.isBlank(current)) { return true; } - NutsIdParser parser = session.id().parser(); + NutsIdParser parser = NutsIdParser.of(session); NutsId currentId = parser.parse(current); String[] allConds = envCond.getPlatform(); if (allConds != null && allConds.length > 0) { @@ -527,7 +527,7 @@ public static boolean matchesDesktopEnvironment(String current, NutsEnvCondition if (NutsBlankable.isBlank(current)) { return true; } - NutsIdParser parser = session.id().parser(); + NutsIdParser parser = NutsIdParser.of(session); NutsId currentId = parser.parse(current); String[] allConds = envCond.getDesktopEnvironment(); if (allConds != null && allConds.length > 0) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsFilterModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsFilterModel.java index 8c6c581d7..389052e72 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsFilterModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsFilterModel.java @@ -1,16 +1,15 @@ package net.thevpc.nuts.runtime.core.filters; import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.core.filters.dependency.InternalNutsDependencyFilterManager; +import net.thevpc.nuts.runtime.core.filters.dependency.InternalNutsDependencyFilters; import net.thevpc.nuts.runtime.core.filters.dependency.NutsDependencyFilterNone; -import net.thevpc.nuts.runtime.core.filters.descriptor.InternalNutsDescriptorFilterManager; +import net.thevpc.nuts.runtime.core.filters.descriptor.InternalNutsDescriptorFilters; import net.thevpc.nuts.runtime.core.filters.descriptor.NutsDescriptorFilterNone; -import net.thevpc.nuts.runtime.core.filters.id.InternalNutsIdFilterManager; import net.thevpc.nuts.runtime.core.filters.id.NutsIdFilterNone; -import net.thevpc.nuts.runtime.core.filters.installstatus.InternalNutsInstallStatusFilterManager; -import net.thevpc.nuts.runtime.core.filters.repository.InternalNutsRepositoryFilterManager; +import net.thevpc.nuts.runtime.core.filters.installstatus.InternalNutsInstallStatusFilters; +import net.thevpc.nuts.runtime.core.filters.repository.InternalNutsRepositoryFilters; import net.thevpc.nuts.runtime.core.filters.repository.NutsRepositoryFilterNone; -import net.thevpc.nuts.runtime.core.filters.version.InternalNutsVersionFilterManager; +import net.thevpc.nuts.runtime.core.filters.version.InternalNutsVersionFilters; import net.thevpc.nuts.runtime.core.filters.version.NutsVersionFilterNone; import java.util.*; @@ -46,22 +45,22 @@ public NutsTypedFilters resolveNutsTypedFilters(Class type, NutsSession session) } switch (type.getName()) { case "net.thevpc.nuts.NutsDependencyFilter": { - return dependency().setSession(session); + return NutsDependencyFilters.of(session); } case "net.thevpc.nuts.NutsRepositoryFilter": { - return repository().setSession(session); + return NutsRepositoryFilters.of(session); } case "net.thevpc.nuts.NutsIdFilter": { - return id().setSession(session); + return NutsIdFilters.of(session); } case "net.thevpc.nuts.NutsVersionFilter": { - return version().setSession(session); + return NutsVersionFilters.of(session); } case "net.thevpc.nuts.NutsDescriptorFilter": { - return descriptor().setSession(session); + return NutsDescriptorFilters.of(session); } case "net.thevpc.nuts.NutsInstallStatusFilter": { - return installStatus().setSession(session); + return NutsInstallStatusFilters.of(session); } } throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("unsupported filter type: %s", type)); @@ -137,7 +136,7 @@ public T none(Class type, NutsFilter[] others, NutsSes case "net.thevpc.nuts.NutsDependencyFilter": { List all = new ArrayList<>(); for (NutsFilter other : others) { - NutsDependencyFilter a = dependency().from(other); + NutsDependencyFilter a = NutsDependencyFilters.of(session).from(other); if (a != null) { all.add(a); } @@ -150,7 +149,7 @@ public T none(Class type, NutsFilter[] others, NutsSes case "net.thevpc.nuts.NutsRepositoryFilter": { List all = new ArrayList<>(); for (NutsFilter other : others) { - NutsRepositoryFilter a = repository().from(other); + NutsRepositoryFilter a = NutsRepositoryFilters.of(session).from(other); if (a != null) { all.add(a); } @@ -163,7 +162,7 @@ public T none(Class type, NutsFilter[] others, NutsSes case "net.thevpc.nuts.NutsIdFilter": { List all = new ArrayList<>(); for (NutsFilter other : others) { - NutsIdFilter a = id().from(other); + NutsIdFilter a = NutsIdFilters.of(session).from(other); if (a != null) { all.add(a); } @@ -176,7 +175,7 @@ public T none(Class type, NutsFilter[] others, NutsSes case "net.thevpc.nuts.NutsVersionFilter": { List all = new ArrayList<>(); for (NutsFilter other : others) { - NutsVersionFilter a = version().from(other); + NutsVersionFilter a = NutsVersionFilters.of(session).from(other); if (a != null) { all.add(a); } @@ -189,7 +188,7 @@ public T none(Class type, NutsFilter[] others, NutsSes case "net.thevpc.nuts.NutsDescriptorFilter": { List all = new ArrayList<>(); for (NutsFilter other : others) { - NutsDescriptorFilter a = descriptor().from(other); + NutsDescriptorFilter a = NutsDescriptorFilters.of(session).from(other); if (a != null) { all.add(a); } @@ -222,30 +221,6 @@ public Class detectType(NutsFilter nutsFilter, NutsSession return detectType(nutsFilter.getClass(), session); } - public NutsIdFilterManager id() { - return new InternalNutsIdFilterManager(this); - } - - public NutsDependencyFilterManager dependency() { - return new InternalNutsDependencyFilterManager(this); - } - - public NutsRepositoryFilterManager repository() { - return new InternalNutsRepositoryFilterManager(this); - } - - public NutsVersionFilterManager version() { - return new InternalNutsVersionFilterManager(this); - } - - public NutsDescriptorFilterManager descriptor() { - return new InternalNutsDescriptorFilterManager(this); - } - - public NutsInstallStatusFilterManager installStatus() { - return new InternalNutsInstallStatusFilterManager(this); - } - private Collection expandAny(NutsFilter... others) { List ok = new ArrayList<>(); if (others != null) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsFilterManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsFilters.java similarity index 67% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsFilterManager.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsFilters.java index 9c86edc34..6d1c7b336 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsFilterManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsFilters.java @@ -1,31 +1,22 @@ package net.thevpc.nuts.runtime.core.filters; import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; -public class DefaultNutsFilterManager implements NutsFilterManager { +public class DefaultNutsFilters implements NutsFilters { public DefaultNutsFilterModel model; public NutsSession session; - public DefaultNutsFilterManager(DefaultNutsFilterModel model) { - this.model = model; + public DefaultNutsFilters(NutsSession session) { + this.model = NutsWorkspaceExt.of(session.getWorkspace()).getModel().filtersModel; + this.session=session; } public DefaultNutsFilterModel getModel() { return model; } - @Override - public NutsSession getSession() { - return session; - } - - @Override - public NutsFilterManager setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(model.getWorkspace(), session); - return this; - } - - @Override public T nonnull(Class type, NutsFilter filter) { checkSession(); @@ -114,39 +105,7 @@ public Class detectType(NutsFilter nutsFilter) { } @Override - public NutsIdFilterManager id() { -// checkSession(); - return model.id().setSession(session); - } - - @Override - public NutsDependencyFilterManager dependency() { -// checkSession(); - return model.dependency().setSession(session); - } - - @Override - public NutsRepositoryFilterManager repository() { -// checkSession(); - return model.repository().setSession(session); - } - - @Override - public NutsVersionFilterManager version() { -// checkSession(); - return model.version().setSession(session); + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; } - - @Override - public NutsDescriptorFilterManager descriptor() { -// checkSession(); - return model.descriptor().setSession(session); - } - - @Override - public NutsInstallStatusFilterManager installStatus() { -// checkSession(); - return model.installStatus().setSession(session); - } - } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsIdMultiFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsIdMultiFilter.java deleted file mode 100755 index 726fbcfce..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsIdMultiFilter.java +++ /dev/null @@ -1,187 +0,0 @@ -//package net.thevpc.nuts.runtime.core.filters; -// -//import net.thevpc.nuts.*; -//import net.thevpc.nuts.runtime.core.filters.descriptor.JsNutsDescriptorFilter; -//import net.thevpc.nuts.runtime.core.filters.version.JsNutsVersionFilter; -//import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; -//import net.thevpc.nuts.runtime.core.util.Simplifiable; -// -//import java.util.ArrayList; -//import java.util.List; -//import java.util.Map; -//import java.util.logging.Level; -//import java.util.logging.Logger; -//import net.thevpc.nuts.core.NutsWorkspaceExt; -//import net.thevpc.nuts.runtime.core.util.CoreStringUtils; -//import net.thevpc.nuts.runtime.core.filters.id.NutsScriptAwareIdFilter; -// -//public class DefaultNutsIdMultiFilter implements NutsIdFilter, Simplifiable, NutsScriptAwareIdFilter { -// -// private final NutsIdFilter idFilter; -// -// -// private final NutsDescriptorFilter descriptorFilter; -// private final NutsRepository repository; -// private final NutsSession session; -// -// public DefaultNutsIdMultiFilter(Map map, NutsIdFilter idFilter, NutsDescriptorFilter descriptorFilter, NutsRepository repository, NutsSession session) { -// this.idFilter = CoreNutsUtils.simplify(idFilter); -// this.descriptorFilter = CoreNutsUtils.simplify(CoreFilterUtils.And( -// CoreNutsUtils.createNutsDescriptorFilter(map), descriptorFilter)); -// this.repository = repository; -// this.session = session; -// } -// -// public NutsIdFilter getIdFilter() { -// return idFilter; -// } -// -// public NutsDescriptorFilter getDescriptorFilter() { -// return descriptorFilter; -// } -// -// @Override -// public boolean acceptSearchId(NutsSearchId sid, NutsSession session) { -// if (idFilter != null) { -// if (!idFilter.acceptSearchId(sid, ws, session)) { -// return false; -// } -// } -// if (descriptorFilter != null) { -// if (!descriptorFilter.acceptSearchId(sid, ws, session)) { -// return false; -// } -// } -// return true; -// } -// -// @Override -// public boolean accept(NutsId id, NutsSession session) { -// if (idFilter != null) { -// if (!idFilter.accept(id,ws, session)) { -// return false; -// } -// } -// if (descriptorFilter != null) { -// NutsDescriptor descriptor = null; -// try { -// descriptor = repository.fetchDescriptor().setId(id).session(this.session).getResult(); -// if (!CoreNutsUtils.isEffectiveId(descriptor.getId())) { -// NutsDescriptor nutsDescriptor = null; -// try { -// //NutsWorkspace ws = repository.getWorkspace(); -// nutsDescriptor = NutsWorkspaceExt.of(ws).resolveEffectiveDescriptor(descriptor, this.session); -// } catch (Exception e) { -// //throw new NutsException(e); -// } -// descriptor = nutsDescriptor; -// } -// } catch (Exception ex) { -// //suppose we cannot retrieve descriptor -// if (LOG.isLoggable(Level.FINER)) { -// LOG.log(Level.FINER, this.session.getFetchMode() + " Unable to fetch Descriptor for " + id + " from repository " + repository.config().getName() + " : " + CoreStringUtils.exceptionToString(ex)); -// } -// return false; -// } -// if (!descriptorFilter.accept(descriptor, ws, session)) { -// return false; -// } -// } -// return true; -// } -// -// @Override -// public NutsIdFilter simplify() { -// NutsIdFilter idFilter2 = CoreNutsUtils.simplify(idFilter); -// -// -// NutsDescriptorFilter descriptorFilter2 = CoreNutsUtils.simplify(descriptorFilter); -// if (idFilter2 == null && descriptorFilter2 == null) { -// return null; -// } -// if (idFilter2 != idFilter || descriptorFilter2 != descriptorFilter) { -// return new DefaultNutsIdMultiFilter(null, idFilter2, descriptorFilter2, repository, session); -// } -// return this; -// } -// -// @Override -// public String toJsNutsIdFilterExpr() { -// class Item { -// -// Class type; -// Object value; -// -// public Item(Class type, Object value) { -// this.type = type; -// this.value = value; -// } -// -// } -// List all = new ArrayList<>(); -// if (idFilter != null) { -// all.add(new Item(NutsIdFilter.class, idFilter)); -// } -// if (descriptorFilter != null) { -// all.add(new Item(NutsDescriptorFilter.class, descriptorFilter)); -// } -// StringBuilder sb = new StringBuilder(); -// if (all.isEmpty()) { -// return "true"; -// } -// if (all.size() > 1) { -// sb.append("("); -// } -// for (Item id : all) { -// if (sb.length() > 0) { -// sb.append(" && "); -// } -// if (id.type.equals(NutsIdFilter.class)) { -// if (id.value instanceof NutsScriptAwareIdFilter) { -// NutsScriptAwareIdFilter b = (NutsScriptAwareIdFilter) id.value; -// String expr = b.toJsNutsIdFilterExpr(); -// if (NutsBlankable.isBlank(expr)) { -// return null; -// } -// sb.append("(").append(expr).append("')"); -// } else { -// return null; -// } -// } else if (id.type.equals(NutsVersionFilter.class)) { -// if (id.value instanceof JsNutsVersionFilter) { -// JsNutsVersionFilter b = (JsNutsVersionFilter) id.value; -// String expr = b.toJsNutsVersionFilterExpr(); -// if (NutsBlankable.isBlank(expr)) { -// return null; -// } -// sb.append("(").append(expr).append("')"); -// } else { -// return null; -// } -// } else if (id.type.equals(NutsDescriptorFilter.class)) { -// if (id.value instanceof JsNutsDescriptorFilter) { -// JsNutsDescriptorFilter b = (JsNutsDescriptorFilter) id.value; -// String expr = b.toJsNutsDescriptorFilterExpr(); -// if (NutsBlankable.isBlank(expr)) { -// return null; -// } -// sb.append("(").append(expr).append("')"); -// } else { -// return null; -// } -// } else { -// return null; -// } -// } -// if (all.size() > 0) { -// sb.append(")"); -// } -// return sb.toString(); -// } -// -// @Override -// public String toString() { -// return "DefaultNutsIdMultiFilter{" + "idFilter=" + idFilter + ", descriptorFilter=" + descriptorFilter + ", repository=" + (repository == null ? "" : repository.config().getName()) + '}'; -// } -// -//} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsTokenFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsTokenFilter.java deleted file mode 100755 index 06ac4dcde..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/DefaultNutsTokenFilter.java +++ /dev/null @@ -1,39 +0,0 @@ -//package net.thevpc.nuts.runtime.core.filters; -// -//import net.thevpc.nuts.NutsTokenFilter; -//import net.thevpc.nuts.runtime.bundles.string.GlobUtils; -//import net.thevpc.nuts.runtime.core.util.CoreStringUtils; -// -//public class DefaultNutsTokenFilter implements NutsTokenFilter { -// -// protected String expression; -// -// public DefaultNutsTokenFilter(String expression) { -// this.expression = expression; -// } -// -// @Override -// public boolean isNull() { -// return expression == null; -// } -// -// @Override -// public boolean isBlank() { -// return expression == null || expression.trim().isEmpty(); -// } -// -// @Override -// public boolean like(String pattern) { -// return GlobUtils.ofExact(pattern).matcher(expression == null ? "" : expression).matches(); -// } -// -// @Override -// public boolean matches(String pattern) { -// return (expression == null ? "" : expression).matches((pattern == null ? ".*" : pattern)); -// } -// -// @Override -// public boolean contains(String substring) { -// return (expression == null ? "" : expression).matches((substring == null ? "" : substring)); -// } -//} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/InternalNutsTypedFilters.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/InternalNutsTypedFilters.java index 5302865f4..61b96b6d3 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/InternalNutsTypedFilters.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/InternalNutsTypedFilters.java @@ -7,6 +7,7 @@ import java.util.ArrayList; import java.util.List; import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; public abstract class InternalNutsTypedFilters implements NutsTypedFilters { @@ -16,23 +17,17 @@ public abstract class InternalNutsTypedFilters implements private Class type; private NutsSession session; - public InternalNutsTypedFilters(DefaultNutsFilterModel model, Class type) { - this.model = model; + public InternalNutsTypedFilters(NutsSession session, Class type) { + this.session = session; + this.model = NutsWorkspaceExt.of(session.getWorkspace()).getModel().filtersModel; this.ws = model.getWorkspace(); this.type = type; } - @Override public NutsSession getSession() { return session; } - @Override - public NutsTypedFilters setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(ws, session); - return this; - } - protected void checkSession(){ NutsWorkspaceUtils.checkSession(ws, session); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/NutsIdAndNutsDependencyFilterItem.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/NutsIdAndNutsDependencyFilterItem.java deleted file mode 100755 index 23a37f43d..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/NutsIdAndNutsDependencyFilterItem.java +++ /dev/null @@ -1,42 +0,0 @@ -//package net.thevpc.nuts.runtime.core.filters; -// -//import net.thevpc.nuts.NutsDescriptor; -//import net.thevpc.nuts.NutsSession; -//import net.thevpc.nuts.runtime.standalone.util.NutsIdGraph; -//import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; -// -//public class NutsIdAndNutsDependencyFilterItem { -// -// public boolean optional; -// public NutsIdGraph.NutsIdNode id; -// public NutsDescriptor descriptor; -// public NutsDescriptor effDescriptor; -// public NutsIdAndNutsDependencyFilterItem parent; -// -// public NutsIdAndNutsDependencyFilterItem(NutsIdGraph.NutsIdNode id, NutsIdAndNutsDependencyFilterItem parent) { -// this.id = id; -// this.parent = parent; -// this.optional = id.optional || (parent != null && parent.optional); -// } -// -// public NutsIdAndNutsDependencyFilterItem getParent() { -// return parent; -// } -// -// public NutsDescriptor getEffDescriptor(NutsSession session) { -// if (effDescriptor == null) { -// effDescriptor = session.fetch().setId(id.id) -// .setEffective(true) -// .setSession(CoreNutsUtils.silent(session)) -// .getResultDescriptor(); -// } -// return effDescriptor; -// } -// -// public NutsDescriptor getDescriptor(NutsSession session) { -// if (descriptor == null) { -// descriptor = session.fetch().setId(id.id).setSession(session).getResultDescriptor(); -// } -// return descriptor; -// } -//} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/InternalNutsDependencyFilterManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/InternalNutsDependencyFilters.java similarity index 78% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/InternalNutsDependencyFilterManager.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/InternalNutsDependencyFilters.java index e206e25c8..98408314e 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/InternalNutsDependencyFilterManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/InternalNutsDependencyFilters.java @@ -1,50 +1,21 @@ package net.thevpc.nuts.runtime.core.filters.dependency; import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; import net.thevpc.nuts.runtime.core.filters.InternalNutsTypedFilters; import java.util.Arrays; import java.util.Collection; import java.util.List; -import net.thevpc.nuts.runtime.core.filters.DefaultNutsFilterModel; - -public class InternalNutsDependencyFilterManager extends InternalNutsTypedFilters implements NutsDependencyFilterManager { - -// private static class LocalModel { -// -// private NutsDependencyFilterFalse nutsDependencyFilterFalse; -// private NutsDependencyFilterTrue nutsDependencyFilterTrue; -// private NutsWorkspace ws; -// -// public LocalModel(NutsWorkspace ws) { -// this.ws = ws; -// } -// -// public NutsDependencyFilter always() { -// if (nutsDependencyFilterTrue == null) { -// nutsDependencyFilterTrue = new NutsDependencyFilterTrue(ws); -// } -// return nutsDependencyFilterTrue; -// } -// -// public NutsDependencyFilter never() { -// if (nutsDependencyFilterFalse == null) { -// nutsDependencyFilterFalse = new NutsDependencyFilterFalse(ws); -// } -// return nutsDependencyFilterFalse; -// } -// -// } -// private final LocalModel localModel; - public InternalNutsDependencyFilterManager(DefaultNutsFilterModel model) { - super(model, NutsDependencyFilter.class); -// localModel = model.getShared(LocalModel.class, () -> new LocalModel(ws)); - } - @Override - public InternalNutsDependencyFilterManager setSession(NutsSession session) { - super.setSession(session); - return this; +import net.thevpc.nuts.spi.NutsSupportLevelContext; + +public class InternalNutsDependencyFilters extends InternalNutsTypedFilters + implements NutsDependencyFilters { + + public InternalNutsDependencyFilters(NutsSession session) { + super(session, NutsDependencyFilter.class); +// localModel = model.getShared(LocalModel.class, () -> new LocalModel(ws)); } @Override @@ -196,19 +167,11 @@ public NutsDependencyFilter byOptional(Boolean optional) { return new NutsDependencyOptionFilter(getSession(), optional); } - @Override - public NutsDependencyFilter byExpression(String expression) { - checkSession(); - if (NutsBlankable.isBlank(expression)) { - return always(); - } - return NutsDependencyJavascriptFilter.valueOf(expression, getSession()); - } @Override public NutsDependencyFilter byExclude(NutsDependencyFilter filter, String[] exclusions) { checkSession(); - return new NutsExclusionDependencyFilter(getSession(), filter, Arrays.stream(exclusions).map(x -> getSession().id().parser().setLenient(false).parse(x)).toArray(NutsId[]::new)); + return new NutsExclusionDependencyFilter(getSession(), filter, Arrays.stream(exclusions).map(x -> NutsId.of(x,getSession())).toArray(NutsId[]::new)); } @Override @@ -274,4 +237,9 @@ public NutsDependencyFilter parse(String expression) { checkSession(); return new NutsDependencyFilterParser(expression, getSession()).parse(); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/JsNutsDependencyFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/JsNutsDependencyFilter.java index dff632e68..b35089879 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/JsNutsDependencyFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/JsNutsDependencyFilter.java @@ -1,42 +1,42 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
- * - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== -*/ -package net.thevpc.nuts.runtime.core.filters.dependency; - -/** - * Created by vpc on 1/5/17. - */ -public interface JsNutsDependencyFilter { - - /** - * if convertible to javascript boolean expression return valid non null - * code. Return null in all other cases. - * - * @return if convertible to javascript boolean expression return valid non - * null code. Return null in all other cases. - */ - String toJsNutsDependencyFilterExpr(); -} +///** +// * ==================================================================== +// * Nuts : Network Updatable Things Service +// * (universal package manager) +// *
+// * is a new Open Source Package Manager to help install packages +// * and libraries for runtime execution. Nuts is the ultimate companion for +// * maven (and other build managers) as it helps installing all package +// * dependencies at runtime. Nuts is not tied to java and is a good choice +// * to share shell scripts and other 'things' . Its based on an extensible +// * architecture to help supporting a large range of sub managers / repositories. +// * +// *
+// * +// * Copyright [2020] [thevpc] +// * Licensed under the Apache License, Version 2.0 (the "License"); you may +// * not use this file except in compliance with the License. You may obtain a +// * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// * either express or implied. See the License for the specific language +// * governing permissions and limitations under the License. +// *
+// * ==================================================================== +//*/ +//package net.thevpc.nuts.runtime.core.filters.dependency; +// +///** +// * Created by vpc on 1/5/17. +// */ +//public interface JsNutsDependencyFilter { +// +// /** +// * if convertible to javascript boolean expression return valid non null +// * code. Return null in all other cases. +// * +// * @return if convertible to javascript boolean expression return valid non +// * null code. Return null in all other cases. +// */ +// String toJsNutsDependencyFilterExpr(); +//} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyArchFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyArchFilter.java index 8c1244388..4ab9f00b2 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyArchFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyArchFilter.java @@ -61,6 +61,6 @@ public String toString() { @Override public NutsDependencyFilter simplify() { - return archs.isEmpty() ? getSession().filters().dependency().always() : this; + return archs.isEmpty() ? NutsDependencyFilters.of(getSession()).always() : this; } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyFilterParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyFilterParser.java index 54b5f32d2..7775f9bf7 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyFilterParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyFilterParser.java @@ -9,8 +9,8 @@ public NutsDependencyFilterParser(String str, NutsSession session) { } @Override - protected NutsDependencyFilterManager getTManager() { - return getSession().filters().dependency(); + protected NutsDependencyFilters getTManager() { + return NutsDependencyFilters.of(getSession()); } protected NutsDependencyFilter wordToPredicate(String word){ diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyJavascriptFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyJavascriptFilter.java index 69b07e61b..45b8cf3ee 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyJavascriptFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyJavascriptFilter.java @@ -1,108 +1,108 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
- * - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== -*/ -package net.thevpc.nuts.runtime.core.filters.dependency; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.bundles.common.JavascriptHelper; - -import java.util.Objects; - -/** - * Created by vpc on 1/7/17. - */ -public class NutsDependencyJavascriptFilter extends AbstractDependencyFilter implements JsNutsDependencyFilter { - -// private static NutsId SAMPLE_NUTS_ID = new DefaultNutsId("sample", "sample", "sample", "sample", "sample"); - - private String code; - - public static NutsDependencyJavascriptFilter valueOf(String value, NutsSession session) { - if (NutsBlankable.isBlank(value)) { - return null; - } - return new NutsDependencyJavascriptFilter(session,value); - } - - public NutsDependencyJavascriptFilter(NutsSession session,String code) { - super(session, NutsFilterOp.CUSTOM); - this.code = code; - //check if valid -// accept(SAMPLE_DependencyNUTS_DESCRIPTOR); - } - - public String getCode() { - return code; - } - - @Override - public boolean acceptDependency(NutsId from, NutsDependency d, NutsSession session) { - JavascriptHelper engineHelper = new JavascriptHelper(code, "var dependency=x; var id=x.getId(); var version=id.getVersion();", null, null, session); - return engineHelper.accept(d); - } - - @Override - public NutsDependencyFilter simplify() { - return this; - } - - @Override - public String toJsNutsDependencyFilterExpr() { -// return "util.matches(dependency,'" + CoreStringUtils.escapeCoteStrings(code) + "')"; - return getCode(); - } - - @Override - public String toString() { - return "NutsDependencyJavascriptFilter{" + code + '}'; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 19 * hash + Objects.hashCode(this.code); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final NutsDependencyJavascriptFilter other = (NutsDependencyJavascriptFilter) obj; - if (!Objects.equals(this.code, other.code)) { - return false; - } - return true; - } - -} +///** +// * ==================================================================== +// * Nuts : Network Updatable Things Service +// * (universal package manager) +// *
+// * is a new Open Source Package Manager to help install packages +// * and libraries for runtime execution. Nuts is the ultimate companion for +// * maven (and other build managers) as it helps installing all package +// * dependencies at runtime. Nuts is not tied to java and is a good choice +// * to share shell scripts and other 'things' . Its based on an extensible +// * architecture to help supporting a large range of sub managers / repositories. +// * +// *
+// * +// * Copyright [2020] [thevpc] +// * Licensed under the Apache License, Version 2.0 (the "License"); you may +// * not use this file except in compliance with the License. You may obtain a +// * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// * either express or implied. See the License for the specific language +// * governing permissions and limitations under the License. +// *
+// * ==================================================================== +//*/ +//package net.thevpc.nuts.runtime.core.filters.dependency; +// +//import net.thevpc.nuts.*; +//import net.thevpc.nuts.runtime.bundles.common.JavascriptHelper; +// +//import java.util.Objects; +// +///** +// * Created by vpc on 1/7/17. +// */ +//public class NutsDependencyJavascriptFilter extends AbstractDependencyFilter implements JsNutsDependencyFilter { +// +//// private static NutsId SAMPLE_NUTS_ID = new DefaultNutsId("sample", "sample", "sample", "sample", "sample"); +// +// private String code; +// +// public static NutsDependencyJavascriptFilter valueOf(String value, NutsSession session) { +// if (NutsBlankable.isBlank(value)) { +// return null; +// } +// return new NutsDependencyJavascriptFilter(session,value); +// } +// +// public NutsDependencyJavascriptFilter(NutsSession session,String code) { +// super(session, NutsFilterOp.CUSTOM); +// this.code = code; +// //check if valid +//// accept(SAMPLE_DependencyNUTS_DESCRIPTOR); +// } +// +// public String getCode() { +// return code; +// } +// +// @Override +// public boolean acceptDependency(NutsId from, NutsDependency d, NutsSession session) { +// JavascriptHelper engineHelper = new JavascriptHelper(code, "var dependency=x; var id=x.getId(); var version=id.getVersion();", null, null, session); +// return engineHelper.accept(d); +// } +// +// @Override +// public NutsDependencyFilter simplify() { +// return this; +// } +// +// @Override +// public String toJsNutsDependencyFilterExpr() { +//// return "util.matches(dependency,'" + CoreStringUtils.escapeCoteStrings(code) + "')"; +// return getCode(); +// } +// +// @Override +// public String toString() { +// return "NutsDependencyJavascriptFilter{" + code + '}'; +// } +// +// @Override +// public int hashCode() { +// int hash = 7; +// hash = 19 * hash + Objects.hashCode(this.code); +// return hash; +// } +// +// @Override +// public boolean equals(Object obj) { +// if (this == obj) { +// return true; +// } +// if (obj == null) { +// return false; +// } +// if (getClass() != obj.getClass()) { +// return false; +// } +// final NutsDependencyJavascriptFilter other = (NutsDependencyJavascriptFilter) obj; +// if (!Objects.equals(this.code, other.code)) { +// return false; +// } +// return true; +// } +// +//} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyOsFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyOsFilter.java index ae1464681..a78d52d75 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyOsFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyOsFilter.java @@ -61,6 +61,6 @@ public String toString() { @Override public NutsDependencyFilter simplify() { - return os.isEmpty() ? getSession().filters().dependency().always() : this; + return os.isEmpty() ? NutsDependencyFilters.of(getSession()).always() : this; } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyScopeFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyScopeFilter.java index 85265495b..c7dc07250 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyScopeFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/dependency/NutsDependencyScopeFilter.java @@ -50,6 +50,6 @@ public String toString() { @Override public NutsDependencyFilter simplify() { - return scope.isEmpty()?getSession().filters().dependency().always() : this; + return scope.isEmpty()?NutsDependencyFilters.of(getSession()).always() : this; } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/InternalNutsDescriptorFilterManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/InternalNutsDescriptorFilters.java similarity index 75% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/InternalNutsDescriptorFilterManager.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/InternalNutsDescriptorFilters.java index b01616b35..fdb47dacc 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/InternalNutsDescriptorFilterManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/InternalNutsDescriptorFilters.java @@ -1,52 +1,23 @@ package net.thevpc.nuts.runtime.core.filters.descriptor; import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; import net.thevpc.nuts.runtime.core.filters.InternalNutsTypedFilters; import net.thevpc.nuts.runtime.core.filters.id.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import net.thevpc.nuts.runtime.core.filters.DefaultNutsFilterModel; -public class InternalNutsDescriptorFilterManager extends InternalNutsTypedFilters implements NutsDescriptorFilterManager { +import net.thevpc.nuts.spi.NutsSupportLevelContext; -// private static class LocalModel { -// -// private NutsDescriptorFilterTrue nutsDescriptorFilterTrue; -// private NutsDescriptorFilterFalse nutsDescriptorFilterFalse; -// private NutsWorkspace ws; -// -// public LocalModel(NutsWorkspace ws) { -// this.ws = ws; -// } -// -// public NutsDescriptorFilter always() { -// if (nutsDescriptorFilterTrue == null) { -// nutsDescriptorFilterTrue = new NutsDescriptorFilterTrue(ws); -// } -// return nutsDescriptorFilterTrue; -// } -// -// public NutsDescriptorFilter never() { -// if (nutsDescriptorFilterFalse == null) { -// nutsDescriptorFilterFalse = new NutsDescriptorFilterFalse(ws); -// } -// return nutsDescriptorFilterFalse; -// } -// -// } -// private final LocalModel localModel; +public class InternalNutsDescriptorFilters extends InternalNutsTypedFilters + implements NutsDescriptorFilters { - public InternalNutsDescriptorFilterManager(DefaultNutsFilterModel model) { - super(model, NutsDescriptorFilter.class); -// localModel = model.getShared(LocalModel.class, () -> new LocalModel(ws)); - } - @Override - public InternalNutsDescriptorFilterManager setSession(NutsSession session) { - super.setSession(session); - return this; + public InternalNutsDescriptorFilters(NutsSession session) { + super(session, NutsDescriptorFilter.class); +// localModel = model.getShared(LocalModel.class, () -> new LocalModel(ws)); } @Override @@ -67,15 +38,6 @@ public NutsDescriptorFilter not(NutsFilter other) { return new NutsDescriptorFilterNone(getSession(), (NutsDescriptorFilter) other); } - @Override - public NutsDescriptorFilter byExpression(String expression) { - checkSession(); - if (NutsBlankable.isBlank(expression)) { - return always(); - } - return NutsDescriptorJavascriptFilter.valueOf(expression, getSession()); - } - @Override public NutsDescriptorFilter byPackaging(String... values) { checkSession(); @@ -181,7 +143,7 @@ public NutsDescriptorFilter byFlag(NutsDescriptorFlag... flags) { public NutsDescriptorFilter byExtension(NutsVersion targetApiVersion) { checkSession(); return new NutsExecExtensionFilter(getSession(), - targetApiVersion == null ? null : getSession().id().parser().parse(NutsConstants.Ids.NUTS_API).builder().setVersion(targetApiVersion).build() + targetApiVersion == null ? null : NutsId.of(NutsConstants.Ids.NUTS_API,getSession()).builder().setVersion(targetApiVersion).build() ); } @@ -189,7 +151,7 @@ public NutsDescriptorFilter byExtension(NutsVersion targetApiVersion) { public NutsDescriptorFilter byRuntime(NutsVersion targetApiVersion) { checkSession(); return new NutsExecRuntimeFilter(getSession(), - targetApiVersion == null ? null : getSession().id().parser().parse(NutsConstants.Ids.NUTS_API).builder().setVersion(targetApiVersion).build(), + targetApiVersion == null ? null : NutsId.of(NutsConstants.Ids.NUTS_API,getSession()).builder().setVersion(targetApiVersion).build(), false ); } @@ -198,7 +160,7 @@ public NutsDescriptorFilter byRuntime(NutsVersion targetApiVersion) { public NutsDescriptorFilter byCompanion(NutsVersion targetApiVersion) { checkSession(); return new NutsExecCompanionFilter(getSession(), - targetApiVersion == null ? null : getSession().id().parser().parse(NutsConstants.Ids.NUTS_API).builder().setVersion(targetApiVersion).build(), + targetApiVersion == null ? null : NutsId.of(NutsConstants.Ids.NUTS_API,getSession()).builder().setVersion(targetApiVersion).build(), getSession().extensions().getCompanionIds().stream().map(NutsId::getShortName).toArray(String[]::new) ); } @@ -211,7 +173,7 @@ public NutsDescriptorFilter byApiVersion(NutsVersion apiVersion) { } return new BootAPINutsDescriptorFilter( getSession(), - getSession().id().parser().parse(NutsConstants.Ids.NUTS_API).builder().setVersion(apiVersion).build().getVersion() + NutsId.of(NutsConstants.Ids.NUTS_API,getSession()).builder().setVersion(apiVersion).build().getVersion() ); } @@ -219,7 +181,7 @@ public NutsDescriptorFilter byApiVersion(NutsVersion apiVersion) { public NutsDescriptorFilter byLockedIds(String... ids) { checkSession(); return new NutsLockedIdExtensionFilter(getSession(), - Arrays.stream(ids).map(x -> getSession().id().parser().setLenient(false).parse(x)).toArray(NutsId[]::new) + Arrays.stream(ids).map(x -> NutsId.of(x,getSession())).toArray(NutsId[]::new) ); } @@ -289,4 +251,9 @@ public NutsDescriptorFilter parse(String expression) { checkSession(); return new NutsDescriptorFilterParser(expression, getSession()).parse(); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/JsNutsDescriptorFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/JsNutsDescriptorFilter.java index e58bff8ca..f54442816 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/JsNutsDescriptorFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/JsNutsDescriptorFilter.java @@ -1,42 +1,42 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
- * - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== -*/ -package net.thevpc.nuts.runtime.core.filters.descriptor; - -/** - * Created by vpc on 1/5/17. - */ -public interface JsNutsDescriptorFilter { - - /** - * if convertible to javascript boolean expression return valid non null - * code. Return null in all other cases. - * - * @return if convertible to javascript boolean expression return valid non - * null code. Return null in all other cases. - */ - String toJsNutsDescriptorFilterExpr(); -} +///** +// * ==================================================================== +// * Nuts : Network Updatable Things Service +// * (universal package manager) +// *
+// * is a new Open Source Package Manager to help install packages +// * and libraries for runtime execution. Nuts is the ultimate companion for +// * maven (and other build managers) as it helps installing all package +// * dependencies at runtime. Nuts is not tied to java and is a good choice +// * to share shell scripts and other 'things' . Its based on an extensible +// * architecture to help supporting a large range of sub managers / repositories. +// * +// *
+// * +// * Copyright [2020] [thevpc] +// * Licensed under the Apache License, Version 2.0 (the "License"); you may +// * not use this file except in compliance with the License. You may obtain a +// * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// * either express or implied. See the License for the specific language +// * governing permissions and limitations under the License. +// *
+// * ==================================================================== +//*/ +//package net.thevpc.nuts.runtime.core.filters.descriptor; +// +///** +// * Created by vpc on 1/5/17. +// */ +//public interface JsNutsDescriptorFilter { +// +// /** +// * if convertible to javascript boolean expression return valid non null +// * code. Return null in all other cases. +// * +// * @return if convertible to javascript boolean expression return valid non +// * null code. Return null in all other cases. +// */ +// String toJsNutsDescriptorFilterExpr(); +//} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterAnd.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterAnd.java index a331f4ade..8f43a4dc8 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterAnd.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterAnd.java @@ -8,7 +8,7 @@ import java.util.List; import java.util.stream.Collectors; -public class NutsDescriptorFilterAnd extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterAnd extends AbstractDescriptorFilter{ private NutsDescriptorFilter[] all; @@ -43,35 +43,6 @@ public NutsDescriptorFilter simplify() { return CoreNutsUtils.simplifyFilterAnd(getSession(),NutsDescriptorFilter.class,this,all); } - @Override - public String toJsNutsDescriptorFilterExpr() { - StringBuilder sb = new StringBuilder(); - if (all.length == 0) { - return "true"; - } - if (all.length > 1) { - sb.append("("); - } - for (NutsDescriptorFilter id : all) { - if (sb.length() > 0) { - sb.append(" && "); - } - if (id instanceof JsNutsDescriptorFilter) { - JsNutsDescriptorFilter b = (JsNutsDescriptorFilter) id; - String expr = b.toJsNutsDescriptorFilterExpr(); - if (NutsBlankable.isBlank(expr)) { - return null; - } - sb.append("(").append(expr).append("')"); - } else { - return null; - } - } - if (all.length > 0) { - sb.append(")"); - } - return sb.toString(); - } @Override public int hashCode() { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterArch.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterArch.java index 258b6872d..d7a19453b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterArch.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterArch.java @@ -35,7 +35,7 @@ /** * Created by vpc on 2/20/17. */ -public class NutsDescriptorFilterArch extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterArch extends AbstractDescriptorFilter { private final String arch; @@ -63,11 +63,11 @@ public NutsDescriptorFilter simplify() { } return this; } - - @Override - public String toJsNutsDescriptorFilterExpr() { - return "descriptor.matchesArch('" + CoreStringUtils.escapeQuoteStrings(arch) + "')"; - } +// +// @Override +// public String toJsNutsDescriptorFilterExpr() { +// return "descriptor.matchesArch('" + CoreStringUtils.escapeQuoteStrings(arch) + "')"; +// } @Override public int hashCode() { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterById.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterById.java index 69c3cc796..21c6e1937 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterById.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterById.java @@ -36,7 +36,7 @@ * * @author thevpc */ -public class NutsDescriptorFilterById extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterById extends AbstractDescriptorFilter { private NutsIdFilter id; @@ -67,17 +67,6 @@ public NutsDescriptorFilter simplify() { return this; } - @Override - public String toJsNutsDescriptorFilterExpr() { - if (id == null) { - return "true"; - } - if (id instanceof NutsScriptAwareIdFilter) { - return ((NutsScriptAwareIdFilter) id).toJsNutsIdFilterExpr(); - } - return null; - } - @Override public String toString() { return "Id{" + id + '}'; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterDesktopEnvironment.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterDesktopEnvironment.java index 6766e5df8..2bd3624fc 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterDesktopEnvironment.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterDesktopEnvironment.java @@ -35,7 +35,7 @@ /** * Created by vpc on 2/20/17. */ -public class NutsDescriptorFilterDesktopEnvironment extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterDesktopEnvironment extends AbstractDescriptorFilter { private final String desktopEnvironment; @@ -64,11 +64,6 @@ public NutsDescriptorFilter simplify() { return this; } - @Override - public String toJsNutsDescriptorFilterExpr() { - return "descriptor.matchesPlatform('" + CoreStringUtils.escapeQuoteStrings(desktopEnvironment) + "')"; - } - @Override public int hashCode() { int hash = 5; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterFalse.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterFalse.java index 1214ff1eb..15a9cb870 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterFalse.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterFalse.java @@ -30,7 +30,7 @@ /** * Created by vpc on 2/20/17. */ -public class NutsDescriptorFilterFalse extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterFalse extends AbstractDescriptorFilter { public NutsDescriptorFilterFalse(NutsSession session) { super(session, NutsFilterOp.FALSE); @@ -49,11 +49,6 @@ public NutsDescriptorFilter simplify() { return this; } - @Override - public String toJsNutsDescriptorFilterExpr() { - return "false"; - } - @Override public int hashCode() { return getClass().getName().hashCode(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterNone.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterNone.java index beea2c7d2..15ed16dcc 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterNone.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterNone.java @@ -8,7 +8,7 @@ import java.util.List; import java.util.stream.Collectors; -public class NutsDescriptorFilterNone extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterNone extends AbstractDescriptorFilter { private NutsDescriptorFilter[] all; @@ -43,36 +43,6 @@ public NutsDescriptorFilter simplify() { return CoreNutsUtils.simplifyFilterNone(getSession(),NutsDescriptorFilter.class,this,all); } - @Override - public String toJsNutsDescriptorFilterExpr() { - StringBuilder sb = new StringBuilder(); - if (all.length == 0) { - return "true"; - } - if (all.length > 1) { - sb.append("("); - } - for (NutsDescriptorFilter id : all) { - if (sb.length() > 0) { - sb.append(" && "); - } - if (id instanceof JsNutsDescriptorFilter) { - JsNutsDescriptorFilter b = (JsNutsDescriptorFilter) id; - String expr = b.toJsNutsDescriptorFilterExpr(); - if (NutsBlankable.isBlank(expr)) { - return null; - } - sb.append("(").append(expr).append("')"); - } else { - return null; - } - } - if (all.length > 0) { - sb.append(")"); - } - return sb.toString(); - } - @Override public int hashCode() { int hash = 7; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOr.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOr.java index 775a12290..8a174ead5 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOr.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOr.java @@ -8,7 +8,7 @@ import java.util.List; import java.util.stream.Collectors; -public class NutsDescriptorFilterOr extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterOr extends AbstractDescriptorFilter { private NutsDescriptorFilter[] all; @@ -43,36 +43,6 @@ public NutsDescriptorFilter simplify() { return CoreNutsUtils.simplifyFilterOr(getSession(),NutsDescriptorFilter.class,this,all); } - @Override - public String toJsNutsDescriptorFilterExpr() { - StringBuilder sb = new StringBuilder(); - if (all.length == 0) { - return "true"; - } - if (all.length > 1) { - sb.append("("); - } - for (NutsDescriptorFilter id : all) { - if (sb.length() > 0) { - sb.append(" || "); - } - if (id instanceof JsNutsDescriptorFilter) { - JsNutsDescriptorFilter b = (JsNutsDescriptorFilter) id; - String expr = b.toJsNutsDescriptorFilterExpr(); - if (NutsBlankable.isBlank(expr)) { - return null; - } - sb.append("(").append(expr).append("')"); - } else { - return null; - } - } - if (all.length > 0) { - sb.append(")"); - } - return sb.toString(); - } - @Override public String toString() { return String.join(" Or ", Arrays.asList(all).stream().map(x -> "(" + x.toString() + ")").collect(Collectors.toList())); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOs.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOs.java index 6e1ea5ff2..fb8cd33df 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOs.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOs.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
* is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -11,7 +11,7 @@ * architecture to help supporting a large range of sub managers / repositories. * *
- * + *

* Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -23,19 +23,20 @@ * governing permissions and limitations under the License. *
* ==================================================================== -*/ + */ package net.thevpc.nuts.runtime.core.filters.descriptor; import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.util.CoreStringUtils; import java.util.Objects; + import net.thevpc.nuts.runtime.core.filters.CoreFilterUtils; /** * Created by vpc on 2/20/17. */ -public class NutsDescriptorFilterOs extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterOs extends AbstractDescriptorFilter { private final String os; @@ -64,16 +65,6 @@ public NutsDescriptorFilter simplify() { return this; } - @Override - public String toJsNutsDescriptorFilterExpr() { - return "descriptor.matchesOs('" + CoreStringUtils.escapeQuoteStrings(os) + "')"; - } - - @Override - public String toString() { - return "Os{" + os + '}'; - } - @Override public int hashCode() { int hash = 7; @@ -93,10 +84,12 @@ public boolean equals(Object obj) { return false; } final NutsDescriptorFilterOs other = (NutsDescriptorFilterOs) obj; - if (!Objects.equals(this.os, other.os)) { - return false; - } - return true; + return Objects.equals(this.os, other.os); + } + + @Override + public String toString() { + return "Os{" + os + '}'; } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOsDist.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOsDist.java index 08c4eb76a..0f4b22a22 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOsDist.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterOsDist.java @@ -34,7 +34,7 @@ /** * Created by vpc on 2/20/17. */ -public class NutsDescriptorFilterOsDist extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterOsDist extends AbstractDescriptorFilter { private final String osDist; @@ -63,11 +63,6 @@ public NutsDescriptorFilter simplify() { return this; } - @Override - public String toJsNutsDescriptorFilterExpr() { - return "descriptor.matchesOsdist('" + CoreStringUtils.escapeQuoteStrings(osDist) + "')"; - } - @Override public int hashCode() { int hash = 7; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterPackaging.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterPackaging.java index 5db36a2c7..e800efd8e 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterPackaging.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterPackaging.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
* is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -11,7 +11,7 @@ * architecture to help supporting a large range of sub managers / repositories. * *
- * + *

* Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -23,7 +23,7 @@ * governing permissions and limitations under the License. *
* ==================================================================== -*/ + */ package net.thevpc.nuts.runtime.core.filters.descriptor; import net.thevpc.nuts.*; @@ -35,7 +35,7 @@ /** * Created by vpc on 2/20/17. */ -public class NutsDescriptorFilterPackaging extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterPackaging extends AbstractDescriptorFilter { private final String packaging; @@ -64,11 +64,7 @@ public NutsDescriptorFilter simplify() { return this; } - @Override - public String toJsNutsDescriptorFilterExpr() { - return "descriptor.matchesPackaging('" + CoreStringUtils.escapeQuoteStrings(packaging) + "')"; - } - + @Override public int hashCode() { int hash = 3; @@ -88,10 +84,7 @@ public boolean equals(Object obj) { return false; } final NutsDescriptorFilterPackaging other = (NutsDescriptorFilterPackaging) obj; - if (!Objects.equals(this.packaging, other.packaging)) { - return false; - } - return true; + return Objects.equals(this.packaging, other.packaging); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterParser.java index ae7ea2298..a40e68348 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterParser.java @@ -9,8 +9,8 @@ public NutsDescriptorFilterParser(String str, NutsSession session) { } @Override - protected NutsDescriptorFilterManager getTManager() { - return getSession().filters().descriptor(); + protected NutsDescriptorFilters getTManager() { + return NutsDescriptorFilters.of(getSession()); } protected NutsDescriptorFilter wordToPredicate(String word){ diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterPlatform.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterPlatform.java index 0dbfeca21..c0e1690b9 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterPlatform.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterPlatform.java @@ -36,7 +36,7 @@ /** * Created by vpc on 2/20/17. */ -public class NutsDescriptorFilterPlatform extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterPlatform extends AbstractDescriptorFilter { private final String platform; @@ -65,11 +65,6 @@ public NutsDescriptorFilter simplify() { return this; } - @Override - public String toJsNutsDescriptorFilterExpr() { - return "descriptor.matchesPlatform('" + CoreStringUtils.escapeQuoteStrings(platform) + "')"; - } - @Override public int hashCode() { int hash = 5; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterTrue.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterTrue.java index 4e8f563aa..945048352 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterTrue.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorFilterTrue.java @@ -10,7 +10,7 @@ * to share shell scripts and other 'things' . Its based on an extensible * architecture to help supporting a large range of sub managers / repositories. *
- * + *

* Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -22,7 +22,7 @@ * governing permissions and limitations under the License. *
* ==================================================================== -*/ + */ package net.thevpc.nuts.runtime.core.filters.descriptor; import net.thevpc.nuts.*; @@ -30,7 +30,7 @@ /** * Created by vpc on 2/20/17. */ -public class NutsDescriptorFilterTrue extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { +public class NutsDescriptorFilterTrue extends AbstractDescriptorFilter { public NutsDescriptorFilterTrue(NutsSession session) { super(session, NutsFilterOp.TRUE); @@ -49,11 +49,6 @@ public NutsDescriptorFilter simplify() { return null; } - @Override - public String toJsNutsDescriptorFilterExpr() { - return "true"; - } - @Override public int hashCode() { return getClass().getName().hashCode(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorJavascriptFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorJavascriptFilter.java deleted file mode 100755 index 88eea54e3..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/descriptor/NutsDescriptorJavascriptFilter.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
- * - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== -*/ -package net.thevpc.nuts.runtime.core.filters.descriptor; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.bundles.common.JavascriptHelper; - -import java.util.Objects; - -/** - * Created by vpc on 1/7/17. - */ -public class NutsDescriptorJavascriptFilter extends AbstractDescriptorFilter implements JsNutsDescriptorFilter { - - private String code; - - public static NutsDescriptorFilter valueOf(String value, NutsSession session) { - if (NutsBlankable.isBlank(value)) { - return session.descriptor().filter().always(); - } - return new NutsDescriptorJavascriptFilter(session,value); - } - - public NutsDescriptorJavascriptFilter(NutsSession session,String code) { - super(session, NutsFilterOp.CUSTOM); - this.code = code; - } - - public String getCode() { - return code; - } - - @Override - public boolean acceptDescriptor(NutsDescriptor d, NutsSession session) { - JavascriptHelper engineHelper = new JavascriptHelper(code, "var descriptor=x; var id=x.getId(); var version=id.getVersion();", null, null,session); - return engineHelper.accept(d); - } - - @Override - public NutsDescriptorFilter simplify() { - return this; - } - - @Override - public String toJsNutsDescriptorFilterExpr() { - return getCode(); - } - - @Override - public int hashCode() { - int hash = 5; - hash = 97 * hash + Objects.hashCode(this.code); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final NutsDescriptorJavascriptFilter other = (NutsDescriptorJavascriptFilter) obj; - if (!Objects.equals(this.code, other.code)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "NutsDescriptorJavascriptFilter{" + code + '}'; - } - -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/InternalNutsIdFilterManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/InternalNutsIdFilters.java similarity index 69% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/InternalNutsIdFilterManager.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/InternalNutsIdFilters.java index 84fe6dd84..68d441e6a 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/InternalNutsIdFilterManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/InternalNutsIdFilters.java @@ -1,52 +1,21 @@ package net.thevpc.nuts.runtime.core.filters.id; import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; import net.thevpc.nuts.runtime.core.filters.InternalNutsTypedFilters; import net.thevpc.nuts.runtime.core.filters.NutsPatternIdFilter; import net.thevpc.nuts.runtime.bundles.io.NutsInstallStatusIdFilter; import java.util.List; import net.thevpc.nuts.runtime.core.filters.DefaultNutsFilterModel; +import net.thevpc.nuts.spi.NutsSupportLevelContext; -public class InternalNutsIdFilterManager extends InternalNutsTypedFilters implements NutsIdFilterManager { - - private static class LocalModel { - - private NutsIdFilterTrue nutsIdFilterTrue; - private NutsIdFilterFalse nutsIdFilterFalse; - private NutsWorkspace ws; - - public LocalModel(NutsWorkspace ws) { - this.ws = ws; - } -// -// public NutsIdFilter always() { -// if (nutsIdFilterTrue == null) { -// nutsIdFilterTrue = new NutsIdFilterTrue(ws); -// } -// return nutsIdFilterTrue; -// } -// -// public NutsIdFilter never() { -// if (nutsIdFilterFalse == null) { -// nutsIdFilterFalse = new NutsIdFilterFalse(ws); -// } -// return nutsIdFilterFalse; -// } +public class InternalNutsIdFilters extends InternalNutsTypedFilters implements NutsIdFilters { + public InternalNutsIdFilters(NutsSession session) { + super(session, NutsIdFilter.class); } - private final LocalModel localModel; - public InternalNutsIdFilterManager(DefaultNutsFilterModel model) { - super(model, NutsIdFilter.class); - localModel = model.getShared(LocalModel.class, () -> new LocalModel(ws)); - } - - @Override - public InternalNutsIdFilterManager setSession(NutsSession session) { - super.setSession(session); - return this; - } @Override public NutsIdFilter always() { @@ -65,14 +34,6 @@ public NutsIdFilter never() { return new NutsIdFilterFalse(getSession()); } - @Override - public NutsIdFilter byExpression(String expression) { - if (NutsBlankable.isBlank(expression)) { - return always(); - } - return NutsJavascriptIdFilter.valueOf(expression, getSession()); - } - @Override public NutsIdFilter byDefaultVersion(Boolean defaultVersion) { if (defaultVersion == null) { @@ -95,9 +56,9 @@ public NutsIdFilter byName(String... names) { NutsIdFilter f = null; for (String wildcardId : names) { if (f == null) { - f = new NutsPatternIdFilter(getSession(), getSession().id().parser().parse(wildcardId)); + f = new NutsPatternIdFilter(getSession(), NutsId.of(wildcardId,getSession())); } else { - f = (NutsIdFilter) f.or(new NutsPatternIdFilter(getSession(), getSession().id().parser().parse(wildcardId))); + f = (NutsIdFilter) f.or(new NutsPatternIdFilter(getSession(), NutsId.of(wildcardId,getSession()))); } } return f; @@ -168,4 +129,9 @@ public NutsIdFilter none(NutsFilter... others) { public NutsIdFilter parse(String expression) { return new NutsIdFilterParser(expression, getSession()).parse(); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsDescriptorIdFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsDescriptorIdFilter.java index b8d2d69f2..919763d64 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsDescriptorIdFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsDescriptorIdFilter.java @@ -40,7 +40,7 @@ public boolean acceptId(NutsId id, NutsSession session) { return true; } if(LOG==null){ - LOG=session.log().of(MavenRepositoryFolderHelper.class); + LOG=NutsLogger.of(MavenRepositoryFolderHelper.class,session); } NutsDescriptor descriptor = null; try { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsIdFilterParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsIdFilterParser.java index d90c16741..1686f103f 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsIdFilterParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsIdFilterParser.java @@ -9,8 +9,8 @@ public NutsIdFilterParser(String str, NutsSession session) { } @Override - protected NutsIdFilterManager getTManager() { - return getSession().filters().id(); + protected NutsIdFilters getTManager() { + return NutsIdFilters.of(getSession()); } protected NutsIdFilter wordToPredicate(String word){ diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsIdIdFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsIdIdFilter.java index e69b5510a..f4d7a4e11 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsIdIdFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsIdIdFilter.java @@ -40,7 +40,7 @@ public boolean acceptId(NutsId id, NutsSession session) { return true; } if(LOG==null){ - LOG=session.log().of(NutsIdIdFilter.class); + LOG=NutsLogger.of(NutsIdIdFilter.class,session); } if(id.getShortName().equals(filter.getShortName())){ if (!filter.getVersion().filter().acceptVersion(id.getVersion(), session)) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsJavascriptIdFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsJavascriptIdFilter.java index a019bbe82..61c87b384 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsJavascriptIdFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/id/NutsJavascriptIdFilter.java @@ -1,110 +1,110 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
- * - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== -*/ -package net.thevpc.nuts.runtime.core.filters.id; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.bundles.common.JavascriptHelper; -import net.thevpc.nuts.runtime.core.util.Simplifiable; - -import java.util.Objects; -import java.util.Set; - -/** - * Created by vpc on 1/7/17. - */ -public class NutsJavascriptIdFilter extends AbstractIdFilter implements NutsIdFilter, Simplifiable, NutsScriptAwareIdFilter { - -// private static NutsId SAMPLE_NUTS_ID = new DefaultNutsId("sample", "sample", "sample", "sample", "sample"); - - private String code; - - public static NutsIdFilter valueOf(String value, NutsSession session) { - if (NutsBlankable.isBlank(value)) { - return session.id().filter().always(); - } - return new NutsJavascriptIdFilter(session,value); - } - - - public NutsJavascriptIdFilter(NutsSession session,String code) { - super(session, NutsFilterOp.CUSTOM); - this.code = code; - } - - public String getCode() { - return code; - } - - @Override - public boolean acceptId(NutsId id, NutsSession session) { - Set blacklist = null; - JavascriptHelper engineHelper = new JavascriptHelper(code, "var id=x.getId(); var version=id.getVersion();", blacklist, null, session); - return engineHelper.accept(id); - } - - @Override - public NutsIdFilter simplify() { - return this; - } - - @Override - public String toJsNutsIdFilterExpr() { -// return "util.matches(dependency,'" + CoreStringUtils.escapeCoteStrings(code) + "')"; - return getCode(); - } - - @Override - public int hashCode() { - int hash = 3; - hash = 17 * hash + Objects.hashCode(this.code); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final NutsJavascriptIdFilter other = (NutsJavascriptIdFilter) obj; - if (!Objects.equals(this.code, other.code)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "NutsIdJavascriptFilter{" + code + '}'; - } - -} +///** +// * ==================================================================== +// * Nuts : Network Updatable Things Service +// * (universal package manager) +// *
+// * is a new Open Source Package Manager to help install packages +// * and libraries for runtime execution. Nuts is the ultimate companion for +// * maven (and other build managers) as it helps installing all package +// * dependencies at runtime. Nuts is not tied to java and is a good choice +// * to share shell scripts and other 'things' . Its based on an extensible +// * architecture to help supporting a large range of sub managers / repositories. +// * +// *
+// * +// * Copyright [2020] [thevpc] +// * Licensed under the Apache License, Version 2.0 (the "License"); you may +// * not use this file except in compliance with the License. You may obtain a +// * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// * either express or implied. See the License for the specific language +// * governing permissions and limitations under the License. +// *
+// * ==================================================================== +//*/ +//package net.thevpc.nuts.runtime.core.filters.id; +// +//import net.thevpc.nuts.*; +//import net.thevpc.nuts.runtime.bundles.common.JavascriptHelper; +//import net.thevpc.nuts.runtime.core.util.Simplifiable; +// +//import java.util.Objects; +//import java.util.Set; +// +///** +// * Created by vpc on 1/7/17. +// */ +//public class NutsJavascriptIdFilter extends AbstractIdFilter implements NutsIdFilter, Simplifiable, NutsScriptAwareIdFilter { +// +//// private static NutsId SAMPLE_NUTS_ID = new DefaultNutsId("sample", "sample", "sample", "sample", "sample"); +// +// private String code; +// +// public static NutsIdFilter valueOf(String value, NutsSession session) { +// if (NutsBlankable.isBlank(value)) { +// return NutsIdFilters.of(session).always(); +// } +// return new NutsJavascriptIdFilter(session,value); +// } +// +// +// public NutsJavascriptIdFilter(NutsSession session,String code) { +// super(session, NutsFilterOp.CUSTOM); +// this.code = code; +// } +// +// public String getCode() { +// return code; +// } +// +// @Override +// public boolean acceptId(NutsId id, NutsSession session) { +// Set blacklist = null; +// JavascriptHelper engineHelper = new JavascriptHelper(code, "var id=x.getId(); var version=id.getVersion();", blacklist, null, session); +// return engineHelper.accept(id); +// } +// +// @Override +// public NutsIdFilter simplify() { +// return this; +// } +// +// @Override +// public String toJsNutsIdFilterExpr() { +//// return "util.matches(dependency,'" + CoreStringUtils.escapeCoteStrings(code) + "')"; +// return getCode(); +// } +// +// @Override +// public int hashCode() { +// int hash = 3; +// hash = 17 * hash + Objects.hashCode(this.code); +// return hash; +// } +// +// @Override +// public boolean equals(Object obj) { +// if (this == obj) { +// return true; +// } +// if (obj == null) { +// return false; +// } +// if (getClass() != obj.getClass()) { +// return false; +// } +// final NutsJavascriptIdFilter other = (NutsJavascriptIdFilter) obj; +// if (!Objects.equals(this.code, other.code)) { +// return false; +// } +// return true; +// } +// +// @Override +// public String toString() { +// return "NutsIdJavascriptFilter{" + code + '}'; +// } +// +//} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/installstatus/InternalNutsInstallStatusFilterManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/installstatus/InternalNutsInstallStatusFilters.java similarity index 66% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/installstatus/InternalNutsInstallStatusFilterManager.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/installstatus/InternalNutsInstallStatusFilters.java index fa8937ec9..8ef7d519f 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/installstatus/InternalNutsInstallStatusFilterManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/installstatus/InternalNutsInstallStatusFilters.java @@ -1,59 +1,19 @@ package net.thevpc.nuts.runtime.core.filters.installstatus; import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; import net.thevpc.nuts.runtime.core.filters.InternalNutsTypedFilters; import java.util.List; -import net.thevpc.nuts.runtime.core.filters.DefaultNutsFilterModel; - -public class InternalNutsInstallStatusFilterManager extends InternalNutsTypedFilters implements NutsInstallStatusFilterManager { - -// private static class LocalModel { -// -// NutsInstallStatusFilter ANY; -// NutsInstallStatusFilter NEVER; -// -// NutsInstallStatusFilter INSTALLED; -// NutsInstallStatusFilter NOT_INSTALLED; -// NutsInstallStatusFilter REQUIRED; -// NutsInstallStatusFilter NOT_REQUIRED; -// NutsInstallStatusFilter OBSOLETE; -// NutsInstallStatusFilter NOT_OBSOLETE; -// -// NutsInstallStatusFilter DEFAULT_VALUE; -// NutsInstallStatusFilter NOT_DEFAULT_VALUE; -// -// NutsInstallStatusFilter DEPLOYED; -// -// NutsInstallStatusFilter NOT_DEPLOYED; -// private NutsWorkspace ws; -// -// public LocalModel(NutsWorkspace ws) { -// this.ws = ws; -// ANY = new NutsInstallStatusFilter2(ws, 0, 0, 0, 0); -//// INSTALLED = new NutsInstallStatusFilter2(ws, 1, 0, 0, 0); -//// NOT_INSTALLED = new NutsInstallStatusFilter2(ws, -1, 0, 0, 0); -//// REQUIRED = new NutsInstallStatusFilter2(ws, 0, 1, 0, 0); -//// NOT_REQUIRED = new NutsInstallStatusFilter2(ws, 0, -1, 0, 0); -//// OBSOLETE = new NutsInstallStatusFilter2(ws, 0, 0, 1, 0); -//// NOT_OBSOLETE = new NutsInstallStatusFilter2(ws, 0, 0, -1, 0); -// DEFAULT_VALUE = new NutsInstallStatusFilter2(ws, 0, 0, 0, 1); -// NOT_DEFAULT_VALUE = new NutsInstallStatusFilter2(ws, 0, 0, 0, -1); -// NEVER = new NutsInstallStatusFilterFalse(ws); -// } -// -// } -// private LocalModel localModel; - public InternalNutsInstallStatusFilterManager(DefaultNutsFilterModel model) { - super(model, NutsInstallStatusFilter.class); -// localModel = model.getShared(LocalModel.class, () -> new LocalModel(ws)); - } +import net.thevpc.nuts.spi.NutsSupportLevelContext; - @Override - public InternalNutsInstallStatusFilterManager setSession(NutsSession session) { - super.setSession(session); - return this; +public class InternalNutsInstallStatusFilters extends InternalNutsTypedFilters + implements NutsInstallStatusFilters { + + public InternalNutsInstallStatusFilters(NutsSession session) { + super(session, NutsInstallStatusFilter.class); +// localModel = model.getShared(LocalModel.class, () -> new LocalModel(ws)); } @Override @@ -166,4 +126,8 @@ public NutsInstallStatusFilter byDeployed(boolean value) { : byDeployed(true).neg().to(NutsInstallStatusFilter.class); } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/installstatus/NutsInstallStatusFilterParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/installstatus/NutsInstallStatusFilterParser.java index 312112f86..476e59e46 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/installstatus/NutsInstallStatusFilterParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/installstatus/NutsInstallStatusFilterParser.java @@ -1,9 +1,8 @@ package net.thevpc.nuts.runtime.core.filters.installstatus; import net.thevpc.nuts.NutsInstallStatusFilter; -import net.thevpc.nuts.NutsInstallStatusFilterManager; +import net.thevpc.nuts.NutsInstallStatusFilters; import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsWorkspace; import net.thevpc.nuts.runtime.core.filters.NutsTypedFiltersParser; public class NutsInstallStatusFilterParser extends NutsTypedFiltersParser { @@ -12,8 +11,8 @@ public NutsInstallStatusFilterParser(String str,NutsSession session) { } @Override - protected NutsInstallStatusFilterManager getTManager() { - return getSession().filters().installStatus(); + protected NutsInstallStatusFilters getTManager() { + return NutsInstallStatusFilters.of(getSession()); } protected NutsInstallStatusFilter wordToPredicate(String word){ diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/repository/InternalNutsRepositoryFilterManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/repository/InternalNutsRepositoryFilters.java similarity index 88% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/repository/InternalNutsRepositoryFilterManager.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/repository/InternalNutsRepositoryFilters.java index a3748a233..3684dcfe6 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/repository/InternalNutsRepositoryFilterManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/repository/InternalNutsRepositoryFilters.java @@ -1,23 +1,20 @@ package net.thevpc.nuts.runtime.core.filters.repository; import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; import net.thevpc.nuts.runtime.core.filters.InternalNutsTypedFilters; import java.util.Arrays; import java.util.List; -import net.thevpc.nuts.runtime.core.filters.DefaultNutsFilterModel; -import net.thevpc.nuts.runtime.standalone.repos.DefaultNutsInstalledRepository; -public class InternalNutsRepositoryFilterManager extends InternalNutsTypedFilters implements NutsRepositoryFilterManager { +import net.thevpc.nuts.runtime.standalone.repos.DefaultNutsInstalledRepository; +import net.thevpc.nuts.spi.NutsSupportLevelContext; - public InternalNutsRepositoryFilterManager(DefaultNutsFilterModel model) { - super(model, NutsRepositoryFilter.class); - } +public class InternalNutsRepositoryFilters extends InternalNutsTypedFilters + implements NutsRepositoryFilters { - @Override - public InternalNutsRepositoryFilterManager setSession(NutsSession session) { - super.setSession(session); - return this; + public InternalNutsRepositoryFilters(NutsSession session) { + super(session, NutsRepositoryFilter.class); } @Override @@ -125,4 +122,9 @@ public NutsRepositoryFilter parse(String expression) { checkSession(); return new NutsRepositoryFilterParser(expression, getSession()).parse(); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/repository/NutsRepositoryFilterParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/repository/NutsRepositoryFilterParser.java index 878a1d90d..208f7800d 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/repository/NutsRepositoryFilterParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/repository/NutsRepositoryFilterParser.java @@ -9,8 +9,8 @@ public NutsRepositoryFilterParser(String str, NutsSession session) { } @Override - protected NutsRepositoryFilterManager getTManager() { - return getSession().filters().repository(); + protected NutsRepositoryFilters getTManager() { + return NutsRepositoryFilters.of(getSession()); } protected NutsRepositoryFilter wordToPredicate(String word){ diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/DefaultNutsVersionFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/DefaultNutsVersionFilter.java index ddb8f07dc..45bd528c0 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/DefaultNutsVersionFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/DefaultNutsVersionFilter.java @@ -80,7 +80,7 @@ public DefaultNutsVersionFilter(NutsSession session) { public static NutsVersionFilter parse(String version, NutsSession session) { if (DefaultNutsVersion.isBlankVersion(version) || "*".equals(version)) { // if(session!=null){ - return session.version().filter().always(); + return NutsVersionFilters.of(session).always(); // } // return new NutsVersionFilterTrue(session.getWorkspace()); } @@ -217,7 +217,7 @@ void addNextValue(String sval) { if (min.equals("")) { dd.add(new DefaultNutsVersionInterval(false, false, min, null)); } else { - String max = session.version().parser().parse(min).inc(-1).getValue(); + String max = NutsVersion.of(min,session).inc(-1).getValue(); dd.add(new DefaultNutsVersionInterval(true, false, min, max)); } } else { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/InternalNutsVersionFilterManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/InternalNutsVersionFilters.java similarity index 63% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/InternalNutsVersionFilterManager.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/InternalNutsVersionFilters.java index 57da457b3..1144e5b62 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/InternalNutsVersionFilterManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/InternalNutsVersionFilters.java @@ -1,49 +1,18 @@ package net.thevpc.nuts.runtime.core.filters.version; import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; import net.thevpc.nuts.runtime.core.filters.InternalNutsTypedFilters; import java.util.List; import net.thevpc.nuts.runtime.core.filters.DefaultNutsFilterModel; +import net.thevpc.nuts.spi.NutsSupportLevelContext; -public class InternalNutsVersionFilterManager extends InternalNutsTypedFilters implements NutsVersionFilterManager { - -// private static class LocalModel { -// -// private NutsVersionFilterTrue nutsVersionFilterTrue; -// private NutsVersionFilterFalse nutsVersionFilterFalse; -// private NutsWorkspace ws; -// -// public LocalModel(NutsWorkspace ws) { -// this.ws = ws; -// } -// -// public NutsVersionFilter always() { -// if (nutsVersionFilterTrue == null) { -// nutsVersionFilterTrue = new NutsVersionFilterTrue(ws); -// } -// return nutsVersionFilterTrue; -// } -// -// public NutsVersionFilter never() { -// if (nutsVersionFilterFalse == null) { -// nutsVersionFilterFalse = new NutsVersionFilterFalse(ws); -// } -// return nutsVersionFilterFalse; -// } -// -// } -// private final LocalModel localModel; - - public InternalNutsVersionFilterManager(DefaultNutsFilterModel model) { - super(model, NutsVersionFilter.class); -// localModel = model.getShared(LocalModel.class, () -> new LocalModel(ws)); - } +public class InternalNutsVersionFilters extends InternalNutsTypedFilters implements NutsVersionFilters { - @Override - public NutsVersionFilterManager setSession(NutsSession session) { - super.setSession(session); - return this; + + public InternalNutsVersionFilters(NutsSession session) { + super(session, NutsVersionFilter.class); } public NutsVersionFilter byValue(String version) { @@ -69,15 +38,6 @@ public NutsVersionFilter not(NutsFilter other) { return new NutsVersionFilterNone(getSession(), (NutsVersionFilter) other); } - @Override - public NutsVersionFilter byExpression(String expression) { - checkSession(); - if (NutsBlankable.isBlank(expression)) { - return always(); - } - return NutsVersionJavascriptFilter.valueOf(expression, getSession()); - } - @Override public NutsVersionFilter as(NutsFilter a) { checkSession(); @@ -141,4 +101,9 @@ public NutsVersionFilter parse(String expression) { checkSession(); return new NutsVersionFilterParser(expression, getSession()).parse(); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/JsNutsVersionFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/JsNutsVersionFilter.java index 7bbf4a707..ee2244b5b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/JsNutsVersionFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/JsNutsVersionFilter.java @@ -1,42 +1,42 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
- * - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== -*/ -package net.thevpc.nuts.runtime.core.filters.version; - -/** - * Created by vpc on 1/5/17. - */ -public interface JsNutsVersionFilter { - - /** - * if convertible to javascript boolean expression return valid non null - * code. Return null in all other cases. - * - * @return if convertible to javascript boolean expression return valid non - * null code. Return null in all other cases. - */ - String toJsNutsVersionFilterExpr(); -} +///** +// * ==================================================================== +// * Nuts : Network Updatable Things Service +// * (universal package manager) +// *
+// * is a new Open Source Package Manager to help install packages +// * and libraries for runtime execution. Nuts is the ultimate companion for +// * maven (and other build managers) as it helps installing all package +// * dependencies at runtime. Nuts is not tied to java and is a good choice +// * to share shell scripts and other 'things' . Its based on an extensible +// * architecture to help supporting a large range of sub managers / repositories. +// * +// *
+// * +// * Copyright [2020] [thevpc] +// * Licensed under the Apache License, Version 2.0 (the "License"); you may +// * not use this file except in compliance with the License. You may obtain a +// * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// * either express or implied. See the License for the specific language +// * governing permissions and limitations under the License. +// *
+// * ==================================================================== +//*/ +//package net.thevpc.nuts.runtime.core.filters.version; +// +///** +// * Created by vpc on 1/5/17. +// */ +//public interface JsNutsVersionFilter { +// +// /** +// * if convertible to javascript boolean expression return valid non null +// * code. Return null in all other cases. +// * +// * @return if convertible to javascript boolean expression return valid non +// * null code. Return null in all other cases. +// */ +// String toJsNutsVersionFilterExpr(); +//} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/NutsVersionFilterParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/NutsVersionFilterParser.java index 2c646cc0a..32d263664 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/NutsVersionFilterParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/NutsVersionFilterParser.java @@ -9,8 +9,8 @@ public NutsVersionFilterParser(String str, NutsSession session) { } @Override - protected NutsVersionFilterManager getTManager() { - return getSession().filters().version(); + protected NutsVersionFilters getTManager() { + return NutsVersionFilters.of(getSession()); } protected NutsVersionFilter wordToPredicate(String word){ diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/NutsVersionJavascriptFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/NutsVersionJavascriptFilter.java index f4344f098..c30e6c665 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/NutsVersionJavascriptFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/filters/version/NutsVersionJavascriptFilter.java @@ -1,107 +1,107 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - *
- * - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== -*/ -package net.thevpc.nuts.runtime.core.filters.version; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.core.util.CoreStringUtils; -import net.thevpc.nuts.runtime.bundles.common.JavascriptHelper; -import net.thevpc.nuts.runtime.core.util.Simplifiable; - -import java.util.Objects; - -/** - * Created by vpc on 1/7/17. - */ -public class NutsVersionJavascriptFilter extends AbstractVersionFilter implements NutsVersionFilter, Simplifiable, JsNutsVersionFilter { - - private String code; - private JavascriptHelper engineHelper; - - public static NutsVersionFilter valueOf(String value, NutsSession session) { - if (NutsBlankable.isBlank(value)) { - return session.version().filter().always(); - } - return new NutsVersionJavascriptFilter(session,value); - } - - public NutsVersionJavascriptFilter(NutsSession session,String code) { - super(session, NutsFilterOp.CUSTOM); - this.code = code; - //check if valid -// accept(SAMPLE_DependencyNUTS_DESCRIPTOR); - } - - public String getCode() { - return code; - } - - @Override - public boolean acceptVersion(NutsVersion d, NutsSession session) { - JavascriptHelper engineHelper = new JavascriptHelper(code, "var dependency=x; var id=x.getId(); var version=id.getVersion();", null, null, session); - return engineHelper.accept(d); - } - - @Override - public NutsVersionFilter simplify() { - return this; - } - - @Override - public String toJsNutsVersionFilterExpr() { - return "util.matches(version,'" + CoreStringUtils.escapeQuoteStrings(code) + "')"; - } - - @Override - public int hashCode() { - int hash = 7; - hash = 53 * hash + Objects.hashCode(this.code); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - final NutsVersionJavascriptFilter other = (NutsVersionJavascriptFilter) obj; - if (!Objects.equals(this.code, other.code)) { - return false; - } - return true; - } - - @Override - public String toString() { - return "NutsVersionJavascriptFilter{" + code + '}'; - } - -} +///** +// * ==================================================================== +// * Nuts : Network Updatable Things Service +// * (universal package manager) +// *
+// * is a new Open Source Package Manager to help install packages +// * and libraries for runtime execution. Nuts is the ultimate companion for +// * maven (and other build managers) as it helps installing all package +// * dependencies at runtime. Nuts is not tied to java and is a good choice +// * to share shell scripts and other 'things' . Its based on an extensible +// * architecture to help supporting a large range of sub managers / repositories. +// *
+// * +// * Copyright [2020] [thevpc] +// * Licensed under the Apache License, Version 2.0 (the "License"); you may +// * not use this file except in compliance with the License. You may obtain a +// * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// * Unless required by applicable law or agreed to in writing, software +// * distributed under the License is distributed on an +// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +// * either express or implied. See the License for the specific language +// * governing permissions and limitations under the License. +// *
+// * ==================================================================== +//*/ +//package net.thevpc.nuts.runtime.core.filters.version; +// +//import net.thevpc.nuts.*; +//import net.thevpc.nuts.runtime.core.util.CoreStringUtils; +//import net.thevpc.nuts.runtime.bundles.common.JavascriptHelper; +//import net.thevpc.nuts.runtime.core.util.Simplifiable; +// +//import java.util.Objects; +// +///** +// * Created by vpc on 1/7/17. +// */ +//public class NutsVersionJavascriptFilter extends AbstractVersionFilter implements NutsVersionFilter, Simplifiable, JsNutsVersionFilter { +// +// private String code; +// private JavascriptHelper engineHelper; +// +// public static NutsVersionFilter valueOf(String value, NutsSession session) { +// if (NutsBlankable.isBlank(value)) { +// return NutsVersionFilters.of(session).always(); +// } +// return new NutsVersionJavascriptFilter(session,value); +// } +// +// public NutsVersionJavascriptFilter(NutsSession session,String code) { +// super(session, NutsFilterOp.CUSTOM); +// this.code = code; +// //check if valid +//// accept(SAMPLE_DependencyNUTS_DESCRIPTOR); +// } +// +// public String getCode() { +// return code; +// } +// +// @Override +// public boolean acceptVersion(NutsVersion d, NutsSession session) { +// JavascriptHelper engineHelper = new JavascriptHelper(code, "var dependency=x; var id=x.getId(); var version=id.getVersion();", null, null, session); +// return engineHelper.accept(d); +// } +// +// @Override +// public NutsVersionFilter simplify() { +// return this; +// } +// +// @Override +// public String toJsNutsVersionFilterExpr() { +// return "util.matches(version,'" + CoreStringUtils.escapeQuoteStrings(code) + "')"; +// } +// +// @Override +// public int hashCode() { +// int hash = 7; +// hash = 53 * hash + Objects.hashCode(this.code); +// return hash; +// } +// +// @Override +// public boolean equals(Object obj) { +// if (this == obj) { +// return true; +// } +// if (obj == null) { +// return false; +// } +// if (getClass() != obj.getClass()) { +// return false; +// } +// final NutsVersionJavascriptFilter other = (NutsVersionJavascriptFilter) obj; +// if (!Objects.equals(this.code, other.code)) { +// return false; +// } +// return true; +// } +// +// @Override +// public String toString() { +// return "NutsVersionJavascriptFilter{" + code + '}'; +// } +// +//} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/CoreNutsWorkspaceOptionsFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/CoreNutsWorkspaceOptionsFormat.java index 46b599632..05dc41328 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/CoreNutsWorkspaceOptionsFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/CoreNutsWorkspaceOptionsFormat.java @@ -262,7 +262,7 @@ public NutsCommandLine getBootCommandLine() { } } } - return session.commandLine().create(arguments.toArray(new String[0])); + return NutsCommandLine.of(arguments,session); } @Override @@ -606,7 +606,7 @@ public String toString() { public NutsVersion getApiVersionObj() { if (apiVersionObj == null) { if (apiVersion != null) { - apiVersionObj = session.version().parser().parse(apiVersion); + apiVersionObj = NutsVersion.of(apiVersion,session); } } return apiVersionObj; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultFormatBase.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultFormatBase.java index 6e926d4bb..35b74097a 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultFormatBase.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultFormatBase.java @@ -23,6 +23,9 @@ public abstract class DefaultFormatBase extends DefaultFor public DefaultFormatBase(NutsWorkspace ws, String name) { super(ws, name); } + public DefaultFormatBase(NutsSession session, String name) { + super(session, name); + } // @Override // public PrintWriter getValidPrintWriter(Writer out) { @@ -58,12 +61,12 @@ public NutsPrintStream getValidPrintStream() { @Override public NutsString format() { checkSession(); - NutsPrintStream out = getSession().io().createMemoryPrintStream(); + NutsPrintStream out = NutsMemoryPrintStream.of(getSession()); print(out); return isNtf() ? - getSession().text().parse(out.toString()) + NutsTexts.of(getSession()).parse(out.toString()) : - getSession().text().ofPlain(out.toString()) + NutsTexts.of(getSession()).ofPlain(out.toString()) ; } @@ -98,7 +101,7 @@ public void print(Writer out) { print(pout); pout.flush(); } else { - NutsPrintStream pout = getSession().io().createPrintStream(out); + NutsPrintStream pout = NutsPrintStream.of(out,getSession()); print(pout); pout.flush(); } @@ -109,7 +112,7 @@ public void print(OutputStream out) { checkSession(); NutsPrintStream p = out == null ? getValidPrintStream() : - getSession().io().createPrintStream(out); + NutsPrintStream.of(out,getSession()); print(p); p.flush(); } @@ -144,7 +147,7 @@ public void println(Writer w) { println(pout); pout.flush(); } else { - NutsPrintStream pout = getSession().io().createPrintStream(w); + NutsPrintStream pout = NutsPrintStream.of(w,getSession()); println(pout); pout.flush(); } @@ -167,7 +170,7 @@ public void println(OutputStream out) { println(pout); pout.flush(); } else { - NutsPrintStream pout = getSession().io().createPrintStream(out); + NutsPrintStream pout = NutsPrintStream.of(out,getSession()); println(pout); pout.flush(); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultFormatBase0.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultFormatBase0.java index 77460dbc0..d39f7bba6 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultFormatBase0.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultFormatBase0.java @@ -29,6 +29,11 @@ public DefaultFormatBase0(NutsWorkspace workspace, String name) { this.workspace = workspace; this.name = name; } + public DefaultFormatBase0(NutsSession session, String name) { + this.session = session; + this.workspace = session.getWorkspace(); + this.name = name; + } protected void checkSession() { NutsWorkspaceUtils.checkSession(getWorkspace(), getSession()); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsDependencyFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsDependencyFormat.java index 426bf1826..c543a92ee 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsDependencyFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsDependencyFormat.java @@ -5,6 +5,7 @@ import java.util.Set; import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsSupportLevelContext; public class DefaultNutsDependencyFormat extends DefaultFormatBase implements NutsDependencyFormat { @@ -19,8 +20,8 @@ public class DefaultNutsDependencyFormat extends DefaultFormatBase queryPropertiesOmitted = new HashSet<>(); - public DefaultNutsDependencyFormat(NutsWorkspace ws) { - super(ws, "dependency-format"); + public DefaultNutsDependencyFormat(NutsSession session) { + super(session, "dependency-format"); } public NutsDependencyFormat setNtf(boolean ntf) { @@ -137,7 +138,7 @@ public NutsString format() { } } } - NutsIdFormat id1 = getSession().id().formatter(); + NutsIdFormat id1 = NutsIdFormat.of(getSession()); for (String omitQueryProperty : getOmitQueryProperties()) { id1.setOmitProperty(omitQueryProperty,true); } @@ -317,4 +318,9 @@ public boolean configureFirst(NutsCommandLine cmdLine) { } return false; } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsDescriptorFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsDescriptorFormat.java index bc870eb2d..c5f852644 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsDescriptorFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsDescriptorFormat.java @@ -1,6 +1,7 @@ package net.thevpc.nuts.runtime.core.format; import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.*; @@ -9,8 +10,8 @@ public class DefaultNutsDescriptorFormat extends DefaultFormatBase context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsExecCommandFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsExecCommandFormat.java index f6fdbff60..5584f7a88 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsExecCommandFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsExecCommandFormat.java @@ -1,6 +1,7 @@ package net.thevpc.nuts.runtime.core.format; import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.*; import java.util.Map; @@ -20,8 +21,8 @@ public class DefaultNutsExecCommandFormat extends DefaultFormatBase context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsIdFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsIdFormat.java index 7cf164999..93b093e91 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsIdFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsIdFormat.java @@ -2,6 +2,7 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.standalone.util.NutsDependencyScopes; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.util.*; @@ -17,8 +18,8 @@ public class DefaultNutsIdFormat extends DefaultFormatBase impleme private Set omittedProperties = new HashSet<>(); private NutsId id; - public DefaultNutsIdFormat(NutsWorkspace ws) { - super(ws, "id-format"); + public DefaultNutsIdFormat(NutsSession session) { + super(session, "id-format"); } public NutsIdFormat setNtf(boolean ntf) { @@ -181,8 +182,8 @@ public NutsString format() { checkSession(); if (id == null) { return isNtf() ? - getSession().text().ofStyled("", NutsTextStyle.of(NutsTextStyleType.BOOLEAN)) - : getSession().text().ofPlain("") + NutsTexts.of(getSession()).ofStyled("", NutsTextStyle.of(NutsTextStyleType.BOOLEAN)) + : NutsTexts.of(getSession()).ofPlain("") ; } Map queryMap = id.getProperties(); @@ -199,7 +200,7 @@ public NutsString format() { idBuilder.setProperty(NutsConstants.IdProperties.FACE, null); } id = idBuilder.build(); - NutsTextBuilder sb = getSession().text().builder(); + NutsTextBuilder sb = NutsTexts.of(getSession()).builder(); if (!isOmitGroupId()) { if (!NutsBlankable.isBlank(id.getGroupId())) { boolean importedGroup2 = "net.thevpc.nuts".equals(id.getGroupId()); @@ -299,7 +300,7 @@ public NutsString format() { if (isNtf()) { return sb.immutable(); } else { - return getSession().text().ofPlain(sb.filteredText()); + return NutsTexts.of(getSession()).ofPlain(sb.filteredText()); } } @@ -390,4 +391,9 @@ public boolean configureFirst(NutsCommandLine cmdLine) { } return false; } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsInfoFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsInfoFormat.java index 9eabe7d83..bfb05f42f 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsInfoFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsInfoFormat.java @@ -12,10 +12,12 @@ import java.util.function.Supplier; import java.util.stream.Collectors; -import net.thevpc.nuts.runtime.standalone.solvers.NutsDependencySolvers; +import net.thevpc.nuts.runtime.standalone.solvers.NutsDependencySolverUtils; import net.thevpc.nuts.runtime.standalone.util.NutsJavaSdkUtils; import net.thevpc.nuts.runtime.core.util.CoreCommonUtils; import net.thevpc.nuts.runtime.core.util.CoreTimeUtils; +import net.thevpc.nuts.spi.NutsDependencySolver; +import net.thevpc.nuts.spi.NutsSupportLevelContext; /** * type: Command Class @@ -31,8 +33,8 @@ public class DefaultNutsInfoFormat extends DefaultFormatBase imp private Predicate filter = NutsPredicates.always(); private boolean lenient = false; - public DefaultNutsInfoFormat(NutsWorkspace ws) { - super(ws, "info"); + public DefaultNutsInfoFormat(NutsSession session) { + super(session, "info"); } @Override @@ -264,22 +266,23 @@ private Map buildWorkspaceMap(boolean deep) { } catch (URISyntaxException ex) { s = s.replace(":", "\\:"); } - runtimeClassPath.add(ws.io().path(s)); + runtimeClassPath.add(NutsPath.of(s,ws)); } } } + NutsTexts txt = NutsTexts.of(ws); props.put("nuts-runtime-classpath", - ws.text().builder().appendJoined(";",runtimeClassPath) + txt.builder().appendJoined(";",runtimeClassPath) ); - props.put("nuts-workspace-id", ws.text().ofStyled(stringValue(ws.getWorkspace().getUuid()),NutsTextStyle.path())); + props.put("nuts-workspace-id", txt.ofStyled(stringValue(ws.getWorkspace().getUuid()),NutsTextStyle.path())); props.put("nuts-store-layout", ws.locations().getStoreLocationLayout()); props.put("nuts-store-strategy", ws.locations().getStoreLocationStrategy()); props.put("nuts-repo-store-strategy", ws.locations().getRepositoryStoreLocationStrategy()); props.put("nuts-global", options.isGlobal()); - props.put("nuts-workspace", ws.io().path(ws.locations().getWorkspaceLocation())); + props.put("nuts-workspace", ws.locations().getWorkspaceLocation()); for (NutsStoreLocation folderType : NutsStoreLocation.values()) { - props.put("nuts-workspace-" + folderType.id(), ws.io().path(ws.locations().getStoreLocation(folderType))); + props.put("nuts-workspace-" + folderType.id(), ws.locations().getStoreLocation(folderType)); } props.put("nuts-open-mode", (options.getOpenMode() == null ? NutsOpenMode.OPEN_OR_CREATE : options.getOpenMode())); props.put("nuts-secure", (ws.security().isSecure())); @@ -293,38 +296,38 @@ private Map buildWorkspaceMap(boolean deep) { props.put("nuts-skip-companions", options.isSkipCompanions()); props.put("nuts-skip-welcome", options.isSkipWelcome()); props.put("nuts-skip-boot", options.isSkipBoot()); - String ds = NutsDependencySolvers.resolveSolverName(options.getDependencySolver()); - String[] allDs = ws.dependency().getSolverNames(); + String ds = NutsDependencySolverUtils.resolveSolverName(options.getDependencySolver()); + String[] allDs = NutsDependencySolver.getSolverNames(ws); props.put("nuts-solver", - ws.text().ofStyled( + txt.ofStyled( ds, - Arrays.stream(allDs).map(x->NutsDependencySolvers.resolveSolverName(x)) + Arrays.stream(allDs).map(x-> NutsDependencySolverUtils.resolveSolverName(x)) .anyMatch(x->x.equals(ds)) ?NutsTextStyle.keyword() : NutsTextStyle.error()) ); props.put("nuts-solver-list", - ws.text().builder().appendJoined(";", + txt.builder().appendJoined(";", Arrays.stream(allDs) - .map(x->ws.text().ofStyled(x,NutsTextStyle.keyword())) + .map(x-> txt.ofStyled(x,NutsTextStyle.keyword())) .collect(Collectors.toList()) ) ); - props.put("java-version", ws.version().parser().parse(System.getProperty("java.version"))); + props.put("java-version", NutsVersion.of(System.getProperty("java.version"),ws)); props.put("platform", ws.env().getPlatform()); - props.put("java-home", ws.io().path(System.getProperty("java.home"))); - props.put("java-executable", ws.io().path(NutsJavaSdkUtils.of(ws).resolveJavaCommandByHome(null, getSession()))); + props.put("java-home", NutsPath.of(System.getProperty("java.home"),ws)); + props.put("java-executable", NutsPath.of(NutsJavaSdkUtils.of(ws).resolveJavaCommandByHome(null, getSession()),ws)); props.put("java-classpath", - ws.text().builder().appendJoined(";", + txt.builder().appendJoined(";", Arrays.stream(System.getProperty("java.class.path").split(File.pathSeparator)) - .map(x->ws.io().path(x)) + .map(x->NutsPath.of(x,ws)) .collect(Collectors.toList()) ) ); props.put("java-library-path", - ws.text().builder().appendJoined(";", + txt.builder().appendJoined(";", Arrays.stream(System.getProperty("java.library.path").split(File.pathSeparator)) - .map(x->ws.io().path(x)) + .map(x->NutsPath.of(x,ws)) .collect(Collectors.toList()) ) ); @@ -336,16 +339,16 @@ private Map buildWorkspaceMap(boolean deep) { props.put("os-arch", ws.env().getArchFamily()); props.put("os-shell", ws.env().getShellFamily()); props.put("user-name", stringValue(System.getProperty("user.name"))); - props.put("user-home", ws.io().path(System.getProperty("user.home"))); - props.put("user-dir", ws.io().path(System.getProperty("user.dir"))); + props.put("user-home", NutsPath.of(System.getProperty("user.home"),ws)); + props.put("user-dir", NutsPath.of(System.getProperty("user.dir"),ws)); props.put("command-line-long", ws.boot().getBootOptions().formatter().setCompact(false).getBootCommandLine() ); props.put("command-line-short", ws.boot().getBootOptions().formatter().setCompact(true).getBootCommandLine()); props.put("inherited", ws.boot().getBootOptions().isInherited()); // nuts-boot-args must always be parsed in bash format - props.put("inherited-nuts-boot-args", ws.commandLine().setCommandlineFamily(NutsShellFamily.SH).parse(System.getProperty("nuts.boot.args")).format()); - props.put("inherited-nuts-args", ws.commandLine().parse(System.getProperty("nuts.args")) + props.put("inherited-nuts-boot-args", NutsCommandLine.parse(System.getProperty("nuts.boot.args"),NutsShellFamily.SH,ws).format()); + props.put("inherited-nuts-args", NutsCommandLine.parse(System.getProperty("nuts.args"),NutsShellFamily.SH,ws) .format() ); props.put("creation-started", Instant.ofEpochMilli(ws.boot().getCreationStartTimeMillis())); @@ -374,7 +377,7 @@ private Map buildRepoRepoMap(NutsRepository repo, boolean deep, props.put(key(prefix, "uuid"), stringValue(repo.getUuid())); props.put(key(prefix, "type"), //display as enum - ws.text().ofStyled(repo.config().getType(),NutsTextStyle.option()) + NutsTexts.of(ws).ofStyled(repo.config().getType(),NutsTextStyle.option()) ); props.put(key(prefix, "speed"), (repo.config().getSpeed())); props.put(key(prefix, "enabled"), (repo.config().isEnabled())); @@ -386,9 +389,9 @@ private Map buildRepoRepoMap(NutsRepository repo, boolean deep, } props.put(key(prefix, "deploy-order"), (repo.config().getDeployWeight())); props.put(key(prefix, "store-location-strategy"), (repo.config().getStoreLocationStrategy())); - props.put(key(prefix, "store-location"), getSession().io().path(repo.config().getStoreLocation())); + props.put(key(prefix, "store-location"), NutsPath.of(repo.config().getStoreLocation(),getSession())); for (NutsStoreLocation value : NutsStoreLocation.values()) { - props.put(key(prefix, "store-location-" + value.id()), getSession().io().path(repo.config().getStoreLocation(value))); + props.put(key(prefix, "store-location-" + value.id()), NutsPath.of(repo.config().getStoreLocation(value),getSession())); } props.put(key(prefix, "supported-mirroring"), (repo.config().isSupportedMirroring())); if (repo.config().isSupportedMirroring()) { @@ -413,7 +416,7 @@ private Map buildRepoRepoMap(NutsRepository repo, boolean deep, } private String stringValue(Object s) { - return getSession().text().builder().append(CoreCommonUtils.stringValue(s)).toString(); + return NutsTexts.of(getSession()).builder().append(CoreCommonUtils.stringValue(s)).toString(); } public boolean isLenient() { @@ -465,4 +468,9 @@ public Map build() { return data; } } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } + } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsObjectFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsObjectFormat.java index 1e403775c..d69129963 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsObjectFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsObjectFormat.java @@ -34,6 +34,7 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.NutsContentType; import net.thevpc.nuts.runtime.core.format.plain.NutsObjectFormatPlain; +import net.thevpc.nuts.spi.NutsSupportLevelContext; /** * @@ -44,8 +45,8 @@ public class DefaultNutsObjectFormat extends NutsObjectFormatBase { private NutsContentType outputFormat; // private NutsObjectFormat base; - public DefaultNutsObjectFormat(NutsWorkspace ws) { - super(ws, "object-format"); + public DefaultNutsObjectFormat(NutsSession session) { + super(session, "object-format"); } // public NutsContentType getOutputFormat() { @@ -80,12 +81,12 @@ public NutsObjectFormat getBase() { public NutsObjectFormat createObjectFormat() { checkSession(); - NutsSession ws = getSession(); + NutsSession session = getSession(); NutsContentType t = getSession().getOutputFormat(); if(t==null){ t = NutsContentType.PLAIN; Object v = getValue(); - Object vv = getSession().elem().destruct(v); + Object vv = NutsElements.of(getSession()).destruct(v); if(vv instanceof Map || vv instanceof List){ t = NutsContentType.JSON; } @@ -112,19 +113,19 @@ public NutsObjectFormat createObjectFormat() { case TSON: case YAML: { - return ws.elem().setContentType(t); + return NutsElements.of(session).setContentType(t); } case PROPS: { - return ws.formats().props(); + return session.formats().props(); } case TREE: { - return ws.formats().tree(); + return session.formats().tree(); } case TABLE: { - return ws.formats().table(); + return session.formats().table(); } case PLAIN: { - return new NutsObjectFormatPlain(ws.getWorkspace()); + return new NutsObjectFormatPlain(session); } } throw new NutsUnsupportedEnumException(getSession(), t); @@ -204,4 +205,9 @@ public void println(File file) { public boolean configureFirst(NutsCommandLine commandLine) { return getBase().configureFirst(commandLine); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultVersionFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsVersionFormat.java similarity index 88% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultVersionFormat.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsVersionFormat.java index 17d0af02b..555c63132 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultVersionFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/DefaultNutsVersionFormat.java @@ -1,6 +1,7 @@ package net.thevpc.nuts.runtime.core.format; import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.util.LinkedHashMap; import java.util.Map; @@ -12,14 +13,14 @@ * * @author thevpc */ -public class DefaultVersionFormat extends DefaultFormatBase implements NutsVersionFormat { +public class DefaultNutsVersionFormat extends DefaultFormatBase implements NutsVersionFormat { private final Map extraProperties = new LinkedHashMap<>(); private boolean all; private NutsVersion version; - public DefaultVersionFormat(NutsWorkspace ws) { - super(ws, "version"); + public DefaultNutsVersionFormat(NutsSession session) { + super(session, "version"); } @Override @@ -103,7 +104,7 @@ public void print(NutsPrintStream out) { if (isWorkspaceVersion()) { out.printf("%s/%s", getSession().getWorkspace().getApiVersion(), getSession().getWorkspace().getRuntimeId().getVersion()); } else { - out.printf("%s", getSession().text().ofStyled( + out.printf("%s", NutsTexts.of(getSession()).ofStyled( getVersion().toString(), NutsTextStyle.version() )); } @@ -112,7 +113,7 @@ public void print(NutsPrintStream out) { out.printf(buildProps()); } else { out.print( - getSession().text().ofStyled( + NutsTexts.of(getSession()).ofStyled( getVersion().toString(), NutsTextStyle.version() ) ); @@ -138,4 +139,9 @@ public Map buildProps() { } return props; } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsFetchDisplayOptions.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsFetchDisplayOptions.java index 159a6332a..d59444c72 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsFetchDisplayOptions.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsFetchDisplayOptions.java @@ -45,7 +45,7 @@ public class NutsFetchDisplayOptions { public NutsFetchDisplayOptions(NutsSession ws) { this.ws = ws; - this.idFormat = ws.id().formatter(); + this.idFormat = NutsIdFormat.of(ws); this.idFormat.setHighlightImportedGroupId(true); this.idFormat.setOmitOtherProperties(true); this.idFormat.setOmitFace(true); @@ -118,7 +118,7 @@ public boolean isRequireDefinition() { } public final NutsFetchDisplayOptions configure(boolean skipUnsupported, String... args) { - configure(false, ws.commandLine().create(args)); + configure(false, NutsCommandLine.of(args,ws)); return this; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsIdFormatHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsIdFormatHelper.java index 2b5d1ed28..d8b162957 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsIdFormatHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsIdFormatHelper.java @@ -110,7 +110,7 @@ public NutsIdFormatHelper(NutsDependency dep, NutsSession session) { } private NutsIdFormatHelper(NutsId id, NutsDescriptor desc, NutsDefinition def, NutsDependency dep, NutsSession session) { - LOG = session.log().of(NutsIdFormatHelper.class); + LOG = NutsLogger.of(NutsIdFormatHelper.class,session); if (id == null) { if (def != null) { id = def.getId(); @@ -299,7 +299,7 @@ public int maxUserNameSize() { public NutsString getSingleColumnRow(NutsFetchDisplayOptions oo) { NutsDisplayProperty[] a = oo.getDisplayProperties(); - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); NutsTextBuilder sb = txt.builder(); for (int j = 0; j < a.length; j++) { NutsString s = buildMain(oo, a[j]); @@ -339,7 +339,7 @@ public NutsString getSingleColumnRow(NutsFetchDisplayOptions oo) { public NutsString buildMain(NutsFetchDisplayOptions oo, NutsDisplayProperty dp) { NutsSession ws = session; - NutsTextManager text = ws.text(); + NutsTexts text =NutsTexts.of(ws); if (oo.isRequireDefinition()) { buildLong(); } @@ -502,7 +502,7 @@ public NutsString buildMain(NutsFetchDisplayOptions oo, NutsDisplayProperty dp) case EXEC_ENTRY: { if (def != null && def.getContent() != null && def.getContent().getPath() != null) { List results = new ArrayList(); - for (NutsExecutionEntry entry : session.apps().execEntries().parse(def.getContent().getFilePath())) { + for (NutsExecutionEntry entry : NutsExecutionEntries.of(session).parse(def.getContent().getFilePath())) { if (entry.isDefaultEntry()) { //should all mark? results.add(text.ofPlain(entry.getName())); @@ -721,7 +721,7 @@ private char buildComponentAppStatus() { } public NutsString getFormattedStatusString() { - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); if (dep != null) { return text.ofStyled("" + status_f // + status_obs @@ -752,7 +752,7 @@ private NutsString keywordArr2(String[] any) { } private NutsString keywordArr0(String[] any, NutsTextStyle style) { - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); if (any == null || any.length == 0) { return txt.ofBlank(); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsObjectFormatBase.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsObjectFormatBase.java index aff6a94ab..8896ea564 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsObjectFormatBase.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/NutsObjectFormatBase.java @@ -6,6 +6,7 @@ package net.thevpc.nuts.runtime.core.format; import net.thevpc.nuts.NutsObjectFormat; +import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.NutsWorkspace; import net.thevpc.nuts.NutsCommandLine; @@ -18,8 +19,8 @@ public abstract class NutsObjectFormatBase extends DefaultFormatBase curr, NutsWorkspace ws, NutsPrintStream out this.listFormat = session.getIterableOutput(); this.displayOptions = displayOptions; if (this.listFormat == null) { - this.listFormat = session.elem().setContentType(session.getOutputFormat()).iter(out); + this.listFormat = NutsElements.of(session).setContentType(session.getOutputFormat()).iter(out); } this.listFormat .configure(true, displayOptions.toCommandLineOptions()) diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsArrayElementBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsArrayElementBuilder.java index 834d60d0d..12e24a21d 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsArrayElementBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsArrayElementBuilder.java @@ -31,7 +31,7 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; -import net.thevpc.nuts.NutsElementFormat; +import net.thevpc.nuts.NutsElements; //import net.thevpc.nuts.NutsPrimitiveElementBuilder; import net.thevpc.nuts.NutsSession; @@ -271,8 +271,8 @@ private NutsElement denull(NutsElement e) { return e; } - private NutsElementFormat _elements() { - return session.elem().setSession(session); + private NutsElements _elements() { + return NutsElements.of(session).setSession(session); } // // private NutsPrimitiveElementBuilder _primitive() { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElementEntryBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElementEntryBuilder.java index 0bef10db1..66ef00826 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElementEntryBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElementEntryBuilder.java @@ -26,7 +26,7 @@ //import net.thevpc.nuts.NutsElement; //import net.thevpc.nuts.NutsElementEntry; //import net.thevpc.nuts.NutsElementEntryBuilder; -//import net.thevpc.nuts.NutsElementFormat; +//import net.thevpc.nuts.NutsElements; //import net.thevpc.nuts.NutsPrimitiveElementBuilder; //import net.thevpc.nuts.NutsSession; // @@ -80,8 +80,8 @@ // ); // } // -// private NutsElementFormat _element() { -// return session.elem(); +// private NutsElements _element() { +// return NutsElements.of(session); // } // //} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElementFactoryContext.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElementFactoryContext.java index 79737897a..0efa07c4e 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElementFactoryContext.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElementFactoryContext.java @@ -23,15 +23,14 @@ */ package net.thevpc.nuts.runtime.core.format.elem; -import net.thevpc.nuts.NutsElementFactoryContext; +import net.thevpc.nuts.*; + import java.lang.reflect.Type; import java.util.HashMap; import java.util.Map; import java.util.function.Predicate; -import net.thevpc.nuts.NutsElement; -import net.thevpc.nuts.NutsElementFormat; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsWorkspace; + +import net.thevpc.nuts.NutsElements; /** * @@ -39,10 +38,10 @@ */ public class DefaultNutsElementFactoryContext implements NutsElementFactoryContext { - private DefaultNutsElementFormat base; + private DefaultNutsElements base; private final Map properties = new HashMap<>(); - public DefaultNutsElementFactoryContext(DefaultNutsElementFormat base) { + public DefaultNutsElementFactoryContext(DefaultNutsElements base) { this.base = base; } @@ -57,7 +56,7 @@ public NutsWorkspace getWorkspace() { } @Override - public NutsElementFormat elem() { + public NutsElements elem() { return base; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElementFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElements.java similarity index 94% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElementFormat.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElements.java index b09ab8b92..17d05ba50 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElementFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsElements.java @@ -13,6 +13,7 @@ import java.util.Date; import java.util.function.Predicate; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; import net.thevpc.nuts.runtime.core.format.DefaultFormatBase; import net.thevpc.nuts.runtime.core.format.NutsFetchDisplayOptions; import net.thevpc.nuts.runtime.core.format.json.DefaultSearchFormatJson; @@ -23,8 +24,9 @@ import net.thevpc.nuts.runtime.core.format.tree.DefaultSearchFormatTree; import net.thevpc.nuts.runtime.core.format.xml.DefaultSearchFormatXml; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; -public class DefaultNutsElementFormat extends DefaultFormatBase implements NutsElementFormat { +public class DefaultNutsElements extends DefaultFormatBase implements NutsElements { // public static final NutsPrimitiveElement NULL = new DefaultNutsPrimitiveElement(NutsElementType.NULL, null); // public static final NutsPrimitiveElement TRUE = new DefaultNutsPrimitiveElement(NutsElementType.BOOLEAN, true); @@ -36,9 +38,9 @@ public class DefaultNutsElementFormat extends DefaultFormatBase destructTypeFilter; - public DefaultNutsElementFormat(DefaultNutsTextManagerModel model) { - super(model.getWorkspace(), "element-format"); - this.model = model; + public DefaultNutsElements(NutsSession session) { + super(session, "element-format"); + this.model = NutsWorkspaceExt.of(session).getModel().textModel; } @Override @@ -47,7 +49,12 @@ public NutsContentType getContentType() { } @Override - public NutsElementFormat setContentType(NutsContentType contentType) { + public NutsElements json() { + return setContentType(NutsContentType.JSON); + } + + @Override + public NutsElements setContentType(NutsContentType contentType) { // checkSession(); if (contentType == null) { this.contentType = NutsContentType.JSON; @@ -70,7 +77,7 @@ public boolean isCompact() { } @Override - public NutsElementFormat setCompact(boolean compact) { + public NutsElements setCompact(boolean compact) { this.compact = compact; return this; } @@ -204,7 +211,7 @@ public Object getValue() { } @Override - public NutsElementFormat setValue(Object value) { + public NutsElements setValue(Object value) { this.value = value; return this; } @@ -247,9 +254,9 @@ private void print(NutsPrintStream out, NutsElementStreamFormat format) { checkSession(); NutsElement elem = toElement(value); if (out.isNtf()) { - NutsPrintStream bos = getSession().io().createMemoryPrintStream(); + NutsPrintStream bos = NutsMemoryPrintStream.of(getSession()); format.printElement(elem, bos, compact, createFactoryContext()); - out.print(getSession().text().ofCode(getContentType().id(), bos.toString())); + out.print(NutsTexts.of(getSession()).ofCode(getContentType().id(), bos.toString())); } else { format.printElement(elem, out, compact, createFactoryContext()); } @@ -431,7 +438,7 @@ public Predicate getDestructTypeFilter() { return destructTypeFilter; } - public NutsElementFormat setDestructTypeFilter(Predicate destructTypeFilter) { + public NutsElements setDestructTypeFilter(Predicate destructTypeFilter) { this.destructTypeFilter = destructTypeFilter; return this; } @@ -547,4 +554,9 @@ public NutsElement parse(Path file) { public NutsElement parse(File file) { return parse(file,NutsElement.class); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsObjectElement.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsObjectElement.java index 335b3ed42..74254c151 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsObjectElement.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsObjectElement.java @@ -29,7 +29,7 @@ public Iterator iterator() { @Override public NutsElement get(String s) { - DefaultNutsElementFormat element = (DefaultNutsElementFormat) this.session.elem(); + DefaultNutsElements element = (DefaultNutsElements) NutsElements.of(session); return values.get(element.forString(s));//no need for session } @@ -41,7 +41,7 @@ public NutsElement get(NutsElement s) { @Override public NutsElement getSafe(String key) { NutsElement a = get(key); - return a == null ? this.session.elem().forNull() : a; + return a == null ? NutsElements.of(session).forNull() : a; } @Override @@ -68,7 +68,7 @@ public String getSafeString(String key, String def) { @Override public NutsElement getSafe(NutsElement key) { NutsElement a = get(key); - return a == null ? this.session.elem().forNull() : a; + return a == null ? NutsElements.of(session).forNull() : a; } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsObjectElementBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsObjectElementBuilder.java index 3b689d2cd..7ea070a68 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsObjectElementBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/DefaultNutsObjectElementBuilder.java @@ -206,7 +206,7 @@ private NutsElement denull(NutsElement e) { return e; } - private NutsElementFormat _elements() { - return session.elem().setSession(session); + private NutsElements _elements() { + return NutsElements.of(session).setSession(session); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/NutsElementPathFilter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/NutsElementPathFilter.java index 735f3d88e..dca5e8522 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/NutsElementPathFilter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/NutsElementPathFilter.java @@ -168,11 +168,11 @@ public String toString() { private static class ArrItemCollectorJsonPath implements NutsElementPath { private NutsSession session; - private NutsElementFormat builder; + private NutsElements builder; public ArrItemCollectorJsonPath(NutsSession session) { this.session = session; - builder = session.elem().setSession(session); + builder = NutsElements.of(session).setSession(session); } @Override @@ -631,7 +631,7 @@ public boolean matches(NutsElement value, int index, int len, Map(); matchContext.put("unique", u); } - String v = session.elem().setSession(session).setContentType(NutsContentType.JSON).setNtf(false).setValue(value).format() + String v = NutsElements.of(session).setSession(session).json().setNtf(false).setValue(value).format() .filteredText() ; if (u.contains(v)) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperCommandLine.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperCommandLine.java index 667b91697..f8b74fdda 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperCommandLine.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperCommandLine.java @@ -1,9 +1,6 @@ package net.thevpc.nuts.runtime.core.format.elem.mappers; -import net.thevpc.nuts.NutsCommandLine; -import net.thevpc.nuts.NutsElement; -import net.thevpc.nuts.NutsElementFactoryContext; -import net.thevpc.nuts.NutsElementMapper; +import net.thevpc.nuts.*; import java.lang.reflect.Type; @@ -22,6 +19,7 @@ public NutsElement createElement(NutsCommandLine o, Type typeOfSrc, NutsElementF @Override public NutsCommandLine createObject(NutsElement o, Type to, NutsElementFactoryContext context) { String[] i = context.defaultElementToObject(o, String[].class); - return context.getSession().commandLine().create(i); + NutsSession session = context.getSession(); + return NutsCommandLine.of(i,session); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperFile.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperFile.java index f734d4b96..c239e39b1 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperFile.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperFile.java @@ -15,11 +15,11 @@ public Object destruct(File src, Type typeOfSrc, NutsElementFactoryContext conte @Override public NutsElement createElement(File o, Type typeOfSrc, NutsElementFactoryContext context) { if (context.elem().isNtf()) { - NutsSession ws = context.getSession(); + NutsSession session = context.getSession(); // NutsText n = ws.text().forStyled(o.toString(), NutsTextStyle.path()); // return ws.elem().forPrimitive().buildNutsString(n); - NutsText n = ws.text().ofStyled(o.toString(), NutsTextStyle.path()); - return ws.elem().forString(n.toString()); + NutsText n = NutsTexts.of(session).ofStyled(o.toString(), NutsTextStyle.path()); + return NutsElements.of(session).forString(n.toString()); } else { return context.defaultObjectToElement(o.toString(), null); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsDependency.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsDependency.java index d7be8ff58..6381b15e3 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsDependency.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsDependency.java @@ -9,18 +9,20 @@ public class NutsElementMapperNutsDependency implements NutsElementMapper { @Override public Object destruct(NutsId o, Type typeOfSrc, NutsElementFactoryContext context) { if (context.elem().isNtf()) { - return context.getSession().id().formatter(o).setNtf(true).format(); + return o.formatter().setNtf(true).format(); } else { return o.toString(); } @@ -21,8 +21,8 @@ public NutsElement createElement(NutsId o, Type typeOfSrc, NutsElementFactoryCon // NutsWorkspace ws = context.getSession().getWorkspace(); // NutsText n = ws.text().toText(ws.id().formatter(o).setNtf(true).format()); // return ws.elem().forPrimitive().buildNutsString(n); - NutsSession ws = context.getSession(); - return ws.elem().forString(ws.id().formatter(o).setNtf(true).format().toString()); + NutsSession session = context.getSession(); + return NutsElements.of(session).forString(o.formatter().setNtf(true).format().toString()); } else { return context.defaultObjectToElement(o.toString(), null); } @@ -30,7 +30,8 @@ public NutsElement createElement(NutsId o, Type typeOfSrc, NutsElementFactoryCon @Override public NutsId createObject(NutsElement o, Type typeOfResult, NutsElementFactoryContext context) { - return context.getSession().id().parser().parse(o.asPrimitive().getString()); + NutsSession session = context.getSession(); + return NutsId.of(o.asPrimitive().getString(),session); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsIdLocation.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsIdLocation.java index 0155a64c8..4b041e9cc 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsIdLocation.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsIdLocation.java @@ -4,26 +4,30 @@ import net.thevpc.nuts.NutsElementFactoryContext; import net.thevpc.nuts.NutsElementMapper; import net.thevpc.nuts.NutsIdLocation; -import net.thevpc.nuts.runtime.standalone.config.DefaultNutsIdLocationBuilder; import java.lang.reflect.Type; +import java.util.Map; public class NutsElementMapperNutsIdLocation implements NutsElementMapper { @Override public Object destruct(NutsIdLocation src, Type typeOfSrc, NutsElementFactoryContext context) { - return context.defaultDestruct(new DefaultNutsIdLocationBuilder(context.getSession()).set(src), null); + return context.defaultDestruct(src, null); } @Override public NutsElement createElement(NutsIdLocation o, Type typeOfSrc, NutsElementFactoryContext context) { - return context.defaultObjectToElement(new DefaultNutsIdLocationBuilder(context.getSession()).set(o), null); + return context.defaultObjectToElement(o, null); } @Override public NutsIdLocation createObject(NutsElement o, Type typeOfResult, NutsElementFactoryContext context) { - DefaultNutsIdLocationBuilder builder = (DefaultNutsIdLocationBuilder) context.defaultElementToObject(o, DefaultNutsIdLocationBuilder.class); - return builder.build(); + Map builder = context.defaultElementToObject(o, Map.class); + return new NutsIdLocation( + (String) builder.get("url"), + (String) builder.get("region"), + (String) builder.get("classifier") + ); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsPath.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsPath.java index 38c5d3b70..dd90e814a 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsPath.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsPath.java @@ -22,6 +22,6 @@ public NutsElement createElement(NutsPath o, Type typeOfSrc, NutsElementFactoryC @Override public NutsPath createObject(NutsElement o, Type to, NutsElementFactoryContext context) { String i = context.defaultElementToObject(o, String.class); - return context.getSession().io().path(i); + return NutsPath.of(i,context.getSession()); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsPlatformLocation.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsPlatformLocation.java index 03b77e33f..9414475d5 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsPlatformLocation.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsPlatformLocation.java @@ -19,7 +19,7 @@ public NutsElement createElement(NutsPlatformLocation o, Type typeOfSrc, NutsEle @Override public NutsPlatformLocation createObject(NutsElement o, Type typeOfResult, NutsElementFactoryContext context) { NutsObjectElement obj = o.asObject(); - NutsElementFormat _prm = context.elem(); + NutsElements _prm = context.elem(); NutsId id = context.elementToObject(obj.get(_prm.forString("id")), NutsId.class); String product = context.elementToObject(obj.get(_prm.forString("product")), String.class); String name = context.elementToObject(obj.get(_prm.forString("name")), String.class); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsString.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsString.java index 8a3fe6575..97ce54b40 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsString.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsString.java @@ -1,9 +1,6 @@ package net.thevpc.nuts.runtime.core.format.elem.mappers; -import net.thevpc.nuts.NutsElement; -import net.thevpc.nuts.NutsElementFactoryContext; -import net.thevpc.nuts.NutsElementMapper; -import net.thevpc.nuts.NutsString; +import net.thevpc.nuts.*; import java.lang.reflect.Type; @@ -22,6 +19,6 @@ public NutsElement createElement(NutsString o, Type typeOfSrc, NutsElementFactor @Override public NutsString createObject(NutsElement o, Type to, NutsElementFactoryContext context) { String i = context.defaultElementToObject(o, String.class); - return context.getSession().text().parse(i); + return NutsTexts.of(context.getSession()).parse(i); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsText.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsText.java index 3f0c32f5e..4fb0811c5 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsText.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsText.java @@ -1,9 +1,6 @@ package net.thevpc.nuts.runtime.core.format.elem.mappers; -import net.thevpc.nuts.NutsElement; -import net.thevpc.nuts.NutsElementFactoryContext; -import net.thevpc.nuts.NutsElementMapper; -import net.thevpc.nuts.NutsText; +import net.thevpc.nuts.*; import java.lang.reflect.Type; @@ -22,7 +19,7 @@ public NutsElement createElement(NutsText o, Type typeOfSrc, NutsElementFactoryC @Override public NutsText createObject(NutsElement o, Type to, NutsElementFactoryContext context) { String i = context.defaultElementToObject(o, String.class); - //return context.getSession().text().parse(i).toText(); - return context.getSession().text().ofPlain(i).toText(); + //return NutsTexts.of(context.getSession()).parse(i).toText(); + return NutsTexts.of(context.getSession()).ofPlain(i).toText(); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsVersion.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsVersion.java index 34496225c..91923552f 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsVersion.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/elem/mappers/NutsElementMapperNutsVersion.java @@ -10,7 +10,7 @@ public class NutsElementMapperNutsVersion implements NutsElementMapper= 'A' && current <= 'F'; } - public NutsElementFormat builder() { + public NutsElements builder() { if (ebuilder == null) { - ebuilder = context.getSession().elem(); + ebuilder = NutsElements.of(context.getSession()); } return ebuilder; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/json/DefaultSearchFormatJson.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/json/DefaultSearchFormatJson.java index d7047a5c9..da6955b2e 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/json/DefaultSearchFormatJson.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/json/DefaultSearchFormatJson.java @@ -17,13 +17,13 @@ public class DefaultSearchFormatJson extends DefaultSearchFormatBase { private boolean compact; - NutsTextManager factory; + NutsTexts factory; private NutsCodeHighlighter codeFormat; public DefaultSearchFormatJson(NutsSession session, NutsPrintStream writer, NutsFetchDisplayOptions options) { super(session, writer, NutsContentType.JSON, options); - factory = session.text(); - codeFormat = session.text().setSession(session).getCodeHighlighter("json"); + factory = NutsTexts.of(session); + codeFormat = NutsTexts.of(session).setSession(session).getCodeHighlighter("json"); } @Override @@ -67,8 +67,8 @@ public void next(Object object, long index) { }else{ getWriter().print(" "); } - String json = getSession().elem() - .setContentType(NutsContentType.JSON).setValue(object).setCompact(isCompact()) + String json = NutsElements.of(getSession()) + .json().setValue(object).setCompact(isCompact()) .format() .filteredText() ; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/plain/NutsObjectFormatPlain.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/plain/NutsObjectFormatPlain.java index 169825210..18c6b87a8 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/plain/NutsObjectFormatPlain.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/plain/NutsObjectFormatPlain.java @@ -7,9 +7,9 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.format.NutsObjectFormatBase; -import net.thevpc.nuts.runtime.core.format.props.DefaultPropertiesFormat; -import net.thevpc.nuts.runtime.core.format.tree.DefaultNutsFormatDestructTypePredicate; +import net.thevpc.nuts.runtime.core.format.props.DefaultNutsPropertiesFormat; import net.thevpc.nuts.runtime.core.format.xml.NutsXmlUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -28,8 +28,8 @@ public class NutsObjectFormatPlain extends NutsObjectFormatBase { private final List extraConfig = new ArrayList<>(); private final Map multilineProperties = new HashMap<>(); - public NutsObjectFormatPlain(NutsWorkspace ws) { - super(ws, NutsContentType.PLAIN.id() + "-format"); + public NutsObjectFormatPlain(NutsSession session) { + super(session, NutsContentType.PLAIN.id() + "-format"); } @Override @@ -38,7 +38,7 @@ public boolean configureFirst(NutsCommandLine commandLine) { if (n != null) { NutsArgument a; boolean enabled = n.isEnabled(); - if ((a = commandLine.nextString(DefaultPropertiesFormat.OPTION_MULTILINE_PROPERTY)) != null) { + if ((a = commandLine.nextString(DefaultNutsPropertiesFormat.OPTION_MULTILINE_PROPERTY)) != null) { if (enabled) { NutsArgument i = NutsArgument.of(a.getValue().getString(),getSession()); extraConfig.add(a.getString()); @@ -72,11 +72,11 @@ private String getFormattedPrimitiveValue(NutsElement value) { public void print(NutsPrintStream w) { checkSession(); Object value = getValue(); - NutsSession ws = getSession(); + NutsSession session = getSession(); if (value instanceof NutsTableModel) { - ws.formats().table(value).configure(true, extraConfig.toArray(new String[0])).print(w); + session.formats().table(value).configure(true, extraConfig.toArray(new String[0])).print(w); } else if (value instanceof NutsTreeModel) { - ws.formats().tree(value).configure(true, extraConfig.toArray(new String[0])).print(w); + session.formats().tree(value).configure(true, extraConfig.toArray(new String[0])).print(w); // } else if (value instanceof Map) { // ws.props().setModel(((Map) value)).configure(true, extraConfig.toArray(new String[0])).print(w); } else if (value instanceof org.w3c.dom.Document) { @@ -87,10 +87,10 @@ public void print(NutsPrintStream w) { doc.appendChild(doc.importNode(elem, true)); NutsXmlUtils.writeDocument(doc, new StreamResult(w.asPrintStream()), false, false, getSession()); } else { - NutsElementFormat element = ws.elem(); + NutsElements element = NutsElements.of(session); element .setNtf(true) - .setDestructTypeFilter(DefaultNutsFormatDestructTypePredicate.INSTANCE); + .setDestructTypeFilter(NutsElements.DEFAULT_FORMAT_DESTRUCTOR); printElement(w, element .destruct(value)); } @@ -159,4 +159,9 @@ public void printElement(NutsPrintStream w, Object value) { // private String formatObject(Object any) { // return CoreCommonUtils.stringValueFormatted(any, false, getValidSession()); // } +@Override +public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; +} + } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/DefaultPropertiesFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/DefaultNutsPropertiesFormat.java similarity index 89% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/DefaultPropertiesFormat.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/DefaultNutsPropertiesFormat.java index ccf9ee229..7ae1e7d4d 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/DefaultPropertiesFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/DefaultNutsPropertiesFormat.java @@ -8,8 +8,9 @@ import net.thevpc.nuts.runtime.core.util.CoreStringUtils; import net.thevpc.nuts.runtime.core.util.CoreIOUtils; import net.thevpc.nuts.runtime.core.util.CoreCommonUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; -public class DefaultPropertiesFormat extends DefaultFormatBase implements NutsPropertiesFormat { +public class DefaultNutsPropertiesFormat extends DefaultFormatBase implements NutsPropertiesFormat { public static final String OPTION_MULTILINE_PROPERTY = "--multiline-property"; private boolean sorted; @@ -22,8 +23,8 @@ public class DefaultPropertiesFormat extends DefaultFormatBase multilineProperties = new HashMap<>(); - public DefaultPropertiesFormat(NutsWorkspace ws) { - super(ws, "props-format"); + public DefaultNutsPropertiesFormat(NutsSession session) { + super(session, "props-format"); } @Override @@ -54,13 +55,13 @@ public boolean configureFirst(NutsCommandLine commandLine) { return false; } - public DefaultPropertiesFormat addMultilineProperty(String property, String separator) { + public DefaultNutsPropertiesFormat addMultilineProperty(String property, String separator) { multilineProperties.put(property, separator); return this; } public Map buildModel() { - Object value = getSession().elem().destruct(getValue()); + Object value = NutsElements.of(getSession()).setDestructTypeFilter(NutsElements.DEFAULT_FORMAT_DESTRUCTOR).destruct(getValue()); LinkedHashMap map = new LinkedHashMap<>(); fillMap(NutsString.parse((rootName==null?"":rootName),getSession()), value, map); return map; @@ -114,7 +115,7 @@ public boolean isSorted() { // return table; // } // -// public DefaultPropertiesFormat setTable(boolean table) { +// public DefaultNutsPropertiesFormat setTable(boolean table) { // this.table = table; // return this; // } @@ -122,12 +123,12 @@ public String getSeparator() { return separator; } - public DefaultPropertiesFormat setSeparator(String separator) { + public DefaultNutsPropertiesFormat setSeparator(String separator) { this.separator = separator; return this; } - public DefaultPropertiesFormat setSorted(boolean sort) { + public DefaultNutsPropertiesFormat setSorted(boolean sort) { this.sorted = sort; return this; } @@ -154,7 +155,7 @@ public void print(NutsPrintStream w) { if (javaProps) { CoreIOUtils.storeProperties(ObjectOutputFormatWriterHelper.explodeMap(mm), w.asPrintStream(), sorted); } else { - printMap(out, getSession().text().ofBlank(), mm); + printMap(out, NutsTexts.of(getSession()).ofBlank(), mm); } } @@ -211,7 +212,7 @@ private void printKeyValue(NutsPrintStream out, NutsString prefix, int len, Nuts } private void printKeyValue(NutsPrintStream out, NutsString prefix, int len, String fancySep, NutsString key, NutsString value) { - NutsTextManager txt = getSession().text(); + NutsTexts txt = NutsTexts.of(getSession()); if (prefix == null) { prefix = txt.ofBlank(); } @@ -264,7 +265,7 @@ private NutsString stringValue(Object o) { if (escapeText) { return CoreCommonUtils.stringValueFormatted(o, escapeText, getSession()); } else { - return getSession().text().toText(o); + return NutsTexts.of(getSession()).toText(o); } } @@ -278,4 +279,9 @@ public NutsPropertiesFormat setValue(Object value) { this.value = value; return this; } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/DefaultSearchFormatProps.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/DefaultSearchFormatProps.java index a4a9939ae..c0b4f388a 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/DefaultSearchFormatProps.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/DefaultSearchFormatProps.java @@ -45,7 +45,7 @@ public void complete(long count) { public void next(Object object, long index) { Map p = new LinkedHashMap<>(); NutsFormatUtils.putAllInProps(String.valueOf(index + 1), p, - getSession().elem() + NutsElements.of(getSession()) .toElement(object) ); CoreIOUtils.storeProperties(p, getWriter().asPrintStream(), false); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/NutsObjectFormatProps.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/NutsObjectFormatProps.java index e338dd7f1..5ecdff053 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/NutsObjectFormatProps.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/props/NutsObjectFormatProps.java @@ -44,7 +44,7 @@ // NutsArgument n = commandLine.peek(); // if (n != null) { // NutsArgument a; -// if ((a = commandLine.nextString(DefaultPropertiesFormat.OPTION_MULTILINE_PROPERTY)) != null) { +// if ((a = commandLine.nextString(DefaultNutsPropertiesFormat.OPTION_MULTILINE_PROPERTY)) != null) { // NutsArgument i = a.getArgumentValue(); // if(a.isEnabled()) { // extraConfig.add(a.getString()); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultSearchFormatTable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultSearchFormatTable.java index d0a5e7c58..963d4980f 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultSearchFormatTable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultSearchFormatTable.java @@ -41,7 +41,7 @@ public NutsTableFormat getTable(NutsSession ws) { if (getSession() != null && getSession().getOutputFormatOptions() != null) { for (String outputFormatOption : getSession().getOutputFormatOptions()) { if (outputFormatOption != null) { - table.configure(true, ws.commandLine().parse(outputFormatOption)); + table.configure(true, NutsCommandLine.parse(outputFormatOption,ws)); } } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultTableFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultTableFormat.java index 4707e2de2..0e6559527 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultTableFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultTableFormat.java @@ -27,9 +27,9 @@ import net.thevpc.nuts.runtime.bundles.common.CorePlatformUtils; import net.thevpc.nuts.runtime.bundles.string.StringBuilder2; import net.thevpc.nuts.runtime.core.format.DefaultFormatBase; -import net.thevpc.nuts.runtime.core.format.tree.DefaultNutsFormatDestructTypePredicate; import net.thevpc.nuts.runtime.core.util.CoreCommonUtils; import net.thevpc.nuts.runtime.core.util.CoreStringUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.ByteArrayOutputStream; import java.io.File; @@ -95,11 +95,11 @@ public class DefaultTableFormat extends DefaultFormatBase imple */ private NutsTableBordersFormat border = CorePlatformUtils.SUPPORTS_UTF_ENCODING ? UNICODE_BORDER : SIMPLE_BORDER; private Object model; - private List visibleColumns = new ArrayList<>(); + private final List visibleColumns = new ArrayList<>(); private boolean visibleHeader = true; - public DefaultTableFormat(NutsWorkspace ws) { - super(ws, "table-format"); + public DefaultTableFormat(NutsSession session) { + super(session, "table-format"); } public static Set getAvailableTableBorders() { @@ -141,7 +141,7 @@ public static NutsTableBordersFormat parseTableBorders(String borderName) { return null; } - public static void formatAndHorizontalAlign(StringBuilder sb, NutsPositionType a, int columns, NutsTextManager tf, NutsSession session) { + public static void formatAndHorizontalAlign(StringBuilder sb, NutsPositionType a, int columns, NutsTexts tf, NutsSession session) { int length = tf.setSession(session).parse(sb.toString()).textLength(); switch (a) { case FIRST: { @@ -223,6 +223,16 @@ public DefaultTableFormat setBorder(NutsTableBordersFormat border) { return this; } + @Override + public NutsTableFormat setBorder(String borderName) { + NutsTableBordersFormat n = parseTableBorders(borderName); + if (n == null) { + throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("unsupported border. use one of : %s", getAvailableTableBorders())); + } + setBorder(n); + return this; + } + public DefaultTableFormat setVisibleColumn(int col, Boolean visible) { if (visible == null) { if (col >= 0 && col < visibleColumns.size()) { @@ -246,16 +256,6 @@ public Boolean getVisibleColumn(int col) { return null; } - @Override - public NutsTableFormat setBorder(String borderName) { - NutsTableBordersFormat n = parseTableBorders(borderName); - if (n == null) { - throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("unsupported border. use one of : %s", getAvailableTableBorders())); - } - setBorder(n); - return this; - } - public NutsTableFormat setCellFormat(NutsTableCellFormat formatter) { defaultCellFormatter = formatter == null ? DefaultTableCellFormat.INSTANCE : formatter; return this; @@ -271,6 +271,11 @@ public NutsMutableTableModel createModel() { return new DefaultNutsMutableTableModel(); } + @Override + public NutsTableFormat setValue(Object value) { + this.model = value; + return this; + } private String getSeparator(NutsTableSeparator id) { String s = border.format(id); @@ -300,7 +305,7 @@ public void print(NutsPrintStream w) { DefaultCell cell = cells.get(i); String B = getSeparator(NutsTableSeparator.FIRST_ROW_LINE); String s = cell.rendered.toString(); - line.write(CoreStringUtils.fillString(B, ws.text().setSession(getSession()).parse(s).textLength())); + line.write(CoreStringUtils.fillString(B, NutsTexts.of(ws).parse(s).textLength())); } line.write(getSeparator(NutsTableSeparator.FIRST_ROW_END)); @@ -322,7 +327,7 @@ public void print(NutsPrintStream w) { DefaultCell cell = cells.get(i); String B = getSeparator(NutsTableSeparator.MIDDLE_ROW_LINE); String s = cell.rendered.toString(); - line.write(CoreStringUtils.fillString(B, ws.text().setSession(getSession()).parse(s).textLength())); + line.write(CoreStringUtils.fillString(B, NutsTexts.of(ws).parse(s).textLength())); } line.write(getSeparator(NutsTableSeparator.MIDDLE_ROW_END)); @@ -364,7 +369,7 @@ public void print(NutsPrintStream w) { DefaultCell cell = cells.get(i); String B = getSeparator(NutsTableSeparator.LAST_ROW_LINE); String s = cell.rendered.toString(); - line.write(CoreStringUtils.fillString(B, ws.text().setSession(getSession()).parse(s).textLength())); + line.write(CoreStringUtils.fillString(B, NutsTexts.of(ws).parse(s).textLength())); } line.write(getSeparator(NutsTableSeparator.LAST_ROW_END)); } @@ -384,7 +389,7 @@ public String toString() { } catch (IOException ex) { throw new NutsIOException(getSession(), ex); } - return new String(out.toByteArray()); + return out.toString(); } private NutsTableCellFormat getTableCellFormat(DefaultCell dc) { @@ -547,9 +552,7 @@ private boolean isVisibleColumn(int col, boolean p, boolean n) { return false; } else if (!p && n) { return true; - } else if (p && n) { - return false; - } + } else return !p || !n; } return true; } @@ -566,7 +569,7 @@ private NutsTableModel createTableModel(Object o) { a.add(_elems().toElement(o)); return createTableModel(_elems().toElement(a)); } - o=_elems().setDestructTypeFilter(DefaultNutsFormatDestructTypePredicate.INSTANCE).destruct(o); + o = _elems().setDestructTypeFilter(NutsElements.DEFAULT_FORMAT_DESTRUCTOR).destruct(o); if (o instanceof Collection) { NutsMutableTableModel model = createModel(); LinkedHashSet columns = new LinkedHashSet<>(); @@ -648,7 +651,7 @@ private NutsTableModel createTableModel(Object o) { for (String column : columns) { model.addHeaderCell(column); } - for (Map.Entry eoelem2 : ((Map) o).entrySet()) { + for (Map.Entry eoelem2 : ((Map) o).entrySet()) { model.newRow(); model.addCell(formatObject(eoelem2.getKey())); model.addCell(formatObject(eoelem2.getValue())); @@ -766,8 +769,8 @@ public void resolveColumns(Object obj, LinkedHashSet columns) { } } - private NutsElementFormat _elems() { - return getSession().elem().setSession(getSession()); + private NutsElements _elems() { + return NutsElements.of(getSession()).setSession(getSession()); } @Override @@ -775,12 +778,6 @@ public Object getValue() { return model; } - @Override - public NutsTableFormat setValue(Object value) { - this.model = value; - return this; - } - @Override public boolean configureFirst(NutsCommandLine cmdLine) { NutsArgument a; @@ -834,6 +831,11 @@ private NutsString formatObject(Object any) { return CoreCommonUtils.stringValueFormatted(any, false, getSession()); } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } + public static class Row { List cells = new ArrayList<>(); @@ -845,7 +847,7 @@ public static class RenderedCell { int rows; int columns; NutsTableCellFormat formatter; - NutsTextManager metrics; + NutsTexts metrics; NutsPositionType valign; NutsPositionType halign; NutsWorkspace ws; @@ -860,7 +862,7 @@ public RenderedCell(int c, int r, Object o, String str, NutsTableCellFormat form this.session = session; this.ws = session.getWorkspace(); this.formatter = formatter; - this.metrics = session.text().setSession(session); + this.metrics = NutsTexts.of(session).setSession(session); this.valign = valign; this.halign = halign; if (str == null) { @@ -1440,4 +1442,5 @@ public int evalRowSize(int row, int rowspan) { } } + } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultTableHeaderFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultTableHeaderFormat.java index 9fc59bfc3..b29d9c264 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultTableHeaderFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/DefaultTableHeaderFormat.java @@ -1,9 +1,6 @@ package net.thevpc.nuts.runtime.core.format.table; -import net.thevpc.nuts.NutsPositionType; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsTableCellFormat; -import net.thevpc.nuts.NutsTextStyle; +import net.thevpc.nuts.*; /** * @@ -19,7 +16,7 @@ public DefaultTableHeaderFormat() { @Override public String format(int row, int col, Object value, NutsSession session) { - return session.text().builder().append(String.valueOf(value), + return NutsTexts.of(session).builder().append(String.valueOf(value), NutsTextStyle.primary1() ).toString(); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/NutsObjectFormatTable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/NutsObjectFormatTable.java index 81ba70a1d..32e7836f8 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/NutsObjectFormatTable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/table/NutsObjectFormatTable.java @@ -7,7 +7,7 @@ // //import net.thevpc.nuts.*; //import net.thevpc.nuts.runtime.core.format.NutsObjectFormatBase; -//import net.thevpc.nuts.runtime.core.format.props.DefaultPropertiesFormat; +//import net.thevpc.nuts.runtime.core.format.props.DefaultNutsPropertiesFormat; //import net.thevpc.nuts.runtime.core.util.CoreCommonUtils; // //import java.io.PrintStream; @@ -44,7 +44,7 @@ // NutsArgument n = commandLine.peek(); // if (n != null) { // NutsArgument a; -// if ((a = commandLine.nextString(DefaultPropertiesFormat.OPTION_MULTILINE_PROPERTY)) != null) { +// if ((a = commandLine.nextString(DefaultNutsPropertiesFormat.OPTION_MULTILINE_PROPERTY)) != null) { // NutsArgument i = a.getArgumentValue(); // if(a.isEnabled()) { // extraConfig.add(a.getString()); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/AnsiPrintStreamSupport.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/AnsiPrintStreamSupport.java index 62c0f442e..2d893b8a2 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/AnsiPrintStreamSupport.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/AnsiPrintStreamSupport.java @@ -1,13 +1,5 @@ package net.thevpc.nuts.runtime.core.format.text; -import net.thevpc.nuts.NutsTerminalMode; -import net.thevpc.nuts.NutsWorkspace; -import net.thevpc.nuts.runtime.standalone.io.DefaultNutsIOManager; - -import java.io.*; -import java.util.Locale; -import net.thevpc.nuts.NutsSession; - public final class AnsiPrintStreamSupport { private AnsiPrintStreamSupport() { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/DefaultNutsTextManagerModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/DefaultNutsTextManagerModel.java index 1e8877a24..b5bac60cc 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/DefaultNutsTextManagerModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/DefaultNutsTextManagerModel.java @@ -27,7 +27,7 @@ import net.thevpc.nuts.runtime.core.format.elem.DefaultNutsElementFactoryService; import net.thevpc.nuts.runtime.core.format.elem.NutsElementFactoryService; import net.thevpc.nuts.runtime.core.format.elem.NutsElementStreamFormat; -import net.thevpc.nuts.runtime.core.format.json.SimpleJson; +import net.thevpc.nuts.runtime.core.format.json.DefaultJsonElementFormat; import net.thevpc.nuts.runtime.core.format.text.highlighters.*; import net.thevpc.nuts.runtime.core.format.text.stylethemes.DefaultNutsTextFormatTheme; import net.thevpc.nuts.runtime.core.format.text.stylethemes.NutsTextFormatPropertiesTheme; @@ -220,7 +220,7 @@ public NutsElementFactoryService getElementFactoryService(NutsSession session) { public NutsElementStreamFormat getJsonMan(NutsSession session) { if (jsonMan == null) { - jsonMan = new SimpleJson(ws); + jsonMan = new DefaultJsonElementFormat(ws); } return jsonMan; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/DefaultNutsTextNodeBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/DefaultNutsTextNodeBuilder.java index d1ed2a9ba..4987a9943 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/DefaultNutsTextNodeBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/DefaultNutsTextNodeBuilder.java @@ -15,13 +15,13 @@ public class DefaultNutsTextNodeBuilder implements NutsTextBuilder { private final List children = new ArrayList<>(); private final NutsSession session; - NutsTextManager text1; + NutsTexts text1; private NutsTextWriteConfiguration writeConfiguration; private NutsTextStyleGenerator styleGenerator; public DefaultNutsTextNodeBuilder(NutsSession session) { this.session = session; - text1 = session.text(); + text1 = NutsTexts.of(session); } @Override @@ -99,9 +99,9 @@ public NutsTextBuilder append(Object text, NutsTextStyle style) { public NutsTextBuilder append(Object text, NutsTextStyles styles) { if (text != null) { if (styles.size() == 0) { - children.add(session.text().toText(text)); + children.add(NutsTexts.of(session).toText(text)); } else { - children.add(text1.ofStyled(session.text().toText(text), styles)); + children.add(text1.ofStyled(NutsTexts.of(session).toText(text), styles)); } } return this; @@ -110,7 +110,7 @@ public NutsTextBuilder append(Object text, NutsTextStyles styles) { @Override public NutsTextBuilder append(Object node) { if (node != null) { - return append(session.text().toText(node)); + return append(NutsTexts.of(session).toText(node)); } return this; } @@ -237,25 +237,25 @@ public NutsText subChildren(int from, int to) { to=size()-1; } if(to<=from){ - return session.text().ofPlain(""); + return NutsTexts.of(session).ofPlain(""); } - return session.text().builder().appendAll(children.subList(from,to)).build(); + return NutsTexts.of(session).builder().appendAll(children.subList(from,to)).build(); } public NutsText substring(int from, int to) { if(to<=from){ - return session.text().ofPlain(""); + return NutsTexts.of(session).ofPlain(""); } int firstIndex = ensureCut(from); if(firstIndex<0){ - return session.text().ofPlain(""); + return NutsTexts.of(session).ofPlain(""); } int secondIndex = ensureCut(to); if(secondIndex<0){ //the cut is till the end - return session.text().builder().appendAll(children.subList(firstIndex,children.size())).build(); + return NutsTexts.of(session).builder().appendAll(children.subList(firstIndex,children.size())).build(); } - return session.text().builder().appendAll(children.subList(firstIndex,secondIndex)).build(); + return NutsTexts.of(session).builder().appendAll(children.subList(firstIndex,secondIndex)).build(); // int index=0; // List ok=new ArrayList<>(); // for (NutsText child : p) { @@ -280,7 +280,7 @@ public NutsText substring(int from, int to) { // } // } // if(ok.isEmpty()){ -// return session.text().ofPlain(""); +// return NutsTexts.of(session).ofPlain(""); // } // if(ok.size()==1){ // return ok.get(0); @@ -293,21 +293,21 @@ public NutsText substring(int from, int to) { // from=0; // } // if(to<=from){ -// return session.text().ofPlain(""); +// return NutsTexts.of(session).ofPlain(""); // } // switch (t.getType()){ // case PLAIN:{ // NutsTextPlain p=(NutsTextPlain) t; // String text = p.getText(); // int x=Math.min(to, text.length()); -// return session.text().ofPlain(text.substring(from,x)); +// return NutsTexts.of(session).ofPlain(text.substring(from,x)); // } // case STYLED:{ // NutsTextStyled p=(NutsTextStyled) t; // NutsTextPlain pp=(NutsTextPlain) p.getChild(); // String text = pp.getText(); // int x=Math.min(to, text.length()); -// return session.text().ofStyled(text.substring(from,to),p.getStyles()); +// return NutsTexts.of(session).ofStyled(text.substring(from,to),p.getStyles()); // } // case LIST:{ // NutsTextList p=(NutsTextList) t; @@ -330,7 +330,7 @@ public int ensureCut(int at) { if(at<=0){ return 0; } - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); int charPos=0; int index=0; while (index= 0) { return factory0.createCode("```", lang, "\n", "```", text @@ -290,14 +293,14 @@ public NutsTextFormatTheme getTheme() { } @Override - public NutsTextManager setTheme(NutsTextFormatTheme theme) { + public NutsTexts setTheme(NutsTextFormatTheme theme) { checkSession(); shared.setTheme(theme, getSession()); return this; } @Override - public NutsTextManager setTheme(String theme) { + public NutsTexts setTheme(String theme) { checkSession(); shared.setTheme(theme, getSession()); return this; @@ -310,14 +313,14 @@ public NutsCodeHighlighter getCodeHighlighter(String kind) { } @Override - public NutsTextManager addCodeHighlighter(NutsCodeHighlighter format) { + public NutsTexts addCodeHighlighter(NutsCodeHighlighter format) { checkSession(); shared.addCodeHighlighter(format, getSession()); return this; } @Override - public NutsTextManager removeCodeHighlighter(String id) { + public NutsTexts removeCodeHighlighter(String id) { checkSession(); shared.removeCodeHighlighter(id, getSession()); return this; @@ -445,7 +448,7 @@ private String expandAlias(String ss) { public NutsTextStyled createStyled(NutsText child, NutsTextStyles textStyles, boolean completed) { NutsText curr = child; - if (textStyles == null || textStyles.isNone()) { + if (textStyles == null || textStyles.isPlain()) { return createStyled("", "", child, textStyles, completed); } for (int i = textStyles.size() - 1; i >= 0; i--) { @@ -507,7 +510,7 @@ public NutsTextStyled createStyled(NutsText child, NutsTextStyles textStyles, bo public NutsTextStyled createStyled(String start, String end, NutsText child, NutsTextStyles textStyle, boolean completed) { if (textStyle == null) { - textStyle = NutsTextStyles.NONE; + textStyle = NutsTextStyles.PLAIN; } checkSession(); return new DefaultNutsTextStyled(getSession(), start, end, child, completed, textStyle); @@ -538,4 +541,8 @@ public NutsText createTitle(String start, int level, NutsText child, boolean com return new DefaultNutsTextTitle(getSession(), start, level, child); } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/ExtendedFormatAwarePrintWriter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/ExtendedFormatAwarePrintWriter.java index cf4329830..f8719c2d8 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/ExtendedFormatAwarePrintWriter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/ExtendedFormatAwarePrintWriter.java @@ -99,7 +99,7 @@ public PrintWriter format(String format, Object... args) { @Override public ExtendedFormatAwarePrintWriter format(Locale l, String format, Object... args) { if(l==null){ - print(session.text().setSession(session).toText( + print(NutsTexts.of(session).setSession(session).toText( NutsMessage.cstyle( format, args ) @@ -107,7 +107,7 @@ public ExtendedFormatAwarePrintWriter format(Locale l, String format, Object... }else{ NutsSession s2 = this.session.copy().setLocale(l.toString()); print( - s2.text().setSession(s2).toText( + NutsTexts.of(s2).toText( NutsMessage.cstyle( format, args ) diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsImmutableString.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsImmutableString.java index ba57457d7..ef2e72df2 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsImmutableString.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsImmutableString.java @@ -74,7 +74,7 @@ public NutsImmutableString immutable() { @Override public String filteredText() { - return session.text(). + return NutsTexts.of(session). parser().filterText(value); } @@ -83,7 +83,7 @@ public int textLength() { } public NutsText toText() { - return session.text().parser().parse(new StringReader(value)); + return NutsTexts.of(session).parser().parse(new StringReader(value)); } @Override @@ -93,7 +93,7 @@ public boolean isEmpty() { @Override public NutsTextBuilder builder() { - return session.text().builder().append(this); + return NutsTexts.of(session).builder().append(this); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeCollector.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeCollector.java index 7edbee8e3..4ca0e95f9 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeCollector.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeCollector.java @@ -1,12 +1,9 @@ package net.thevpc.nuts.runtime.core.format.text; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsWorkspace; +import net.thevpc.nuts.*; import java.util.ArrayList; import java.util.List; -import net.thevpc.nuts.NutsText; -import net.thevpc.nuts.NutsTextVisitor; public class NutsTextNodeCollector implements NutsTextVisitor { private List all = new ArrayList<>(); @@ -24,10 +21,10 @@ public NutsText getRootOrNull() { if (all.isEmpty()) { return null; } - return ws.text().ofList(all).simplify(); + return NutsTexts.of(ws).ofList(all).simplify(); } public NutsText getRootOrEmpty() { - return ws.text().ofList(all).simplify(); + return NutsTexts.of(ws).ofList(all).simplify(); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterRaw.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterRaw.java index 790ac318b..4f9374ccc 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterRaw.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterRaw.java @@ -52,10 +52,10 @@ private void flattenNode(NutsText node, NutsTextWriteConfiguration ctx, NutsText for (String line : CoreStringUtils.splitOnNewlines(text)) { boolean newline = line.startsWith("\n") || line.startsWith("\r"); - if (newline || ctx.isFiltered() || style == null || style.isNone()) { - items.add(session.text().ofPlain(line)); + if (newline || ctx.isFiltered() || style == null || style.isPlain()) { + items.add(NutsTexts.of(session).ofPlain(line)); } else { - items.add(session.text().ofStyled(line, style)); + items.add(NutsTexts.of(session).ofStyled(line, style)); } } break; @@ -84,12 +84,12 @@ private void flattenNode(NutsText node, NutsTextWriteConfiguration ctx, NutsText if (ctx.isTitleNumberEnabled()) { NutsTextNumbering seq = ctx.getTitleNumberSequence(); if (seq == null) { - seq = session.text().ofNumbering(); + seq = NutsTexts.of(session).ofNumbering(); ctx.setTitleNumberSequence(seq); } NutsTextNumbering a = seq.newLevel(s.getTextStyleCode().length()); String ts = a.toString() + " "; - flattenNode(session.text().ofPlain(ts), ctx, NutsTextStyles.of(NutsTextStyle.title(s.getLevel()))); + flattenNode(NutsTexts.of(session).ofPlain(ts), ctx, NutsTextStyles.of(NutsTextStyle.title(s.getLevel()))); } flattenNode(s.getChild(), ctx, NutsTextStyles.of(NutsTextStyle.title(s.getLevel()))); break; @@ -117,7 +117,7 @@ private void flattenNode(NutsText node, NutsTextWriteConfiguration ctx, NutsText if (!ctx.isFiltered()) { flattenNode(s.highlight(session), ctx, null); } else { - flattenNode(session.text().ofPlain(s.getText()), ctx, style); + flattenNode(NutsTexts.of(session).ofPlain(s.getText()), ctx, style); } break; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterRenderer.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterRenderer.java index 048c330eb..465311c30 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterRenderer.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterRenderer.java @@ -109,25 +109,25 @@ private void writeNode(AnsiEscapeCommand[] formats, NutsText node, NutsTextWrite case STYLED: { DefaultNutsTextStyled s = (DefaultNutsTextStyled) node; NutsTextStyles styles = s.getStyles(); - NutsTextStyles format = session.text().getTheme().toBasicStyles(styles, session); + NutsTextStyles format = NutsTexts.of(session).getTheme().toBasicStyles(styles, session); AnsiEscapeCommand[] s2 = _appendFormats(formats, format); writeNode(s2, s.getChild(), ctx); break; } case TITLE: { DefaultNutsTextTitle s = (DefaultNutsTextTitle) node; - DefaultNutsTextManager factory0 = (DefaultNutsTextManager) session.text(); - AnsiEscapeCommand[] s2 = _appendFormats(formats, session.text().getTheme().toBasicStyles(NutsTextStyles.of(NutsTextStyle.title(s.getLevel())), session + DefaultNutsTexts factory0 = (DefaultNutsTexts) NutsTexts.of(session); + AnsiEscapeCommand[] s2 = _appendFormats(formats, NutsTexts.of(session).getTheme().toBasicStyles(NutsTextStyles.of(NutsTextStyle.title(s.getLevel())), session )); if (ctx.isTitleNumberEnabled()) { NutsTextNumbering seq = ctx.getTitleNumberSequence(); if (seq == null) { - seq = session.text().ofNumbering(); + seq = NutsTexts.of(session).ofNumbering(); ctx.setTitleNumberSequence(seq); } NutsTextNumbering a = seq.newLevel(s.getLevel()); NutsText sWithTitle = factory0.ofList( - session.text().ofPlain(a.toString() + " "), + NutsTexts.of(session).ofPlain(a.toString() + " "), s.getChild() ); writeNode(s2, sWithTitle, ctx); @@ -154,7 +154,7 @@ private void writeNode(AnsiEscapeCommand[] formats, NutsText node, NutsTextWrite } case LINK: { //ignore!! - DefaultNutsTextManager factory0 = (DefaultNutsTextManager) session.text(); + DefaultNutsTexts factory0 = (DefaultNutsTexts) NutsTexts.of(session); writeNode( formats, factory0.createStyled(((NutsTextLink) node).getChild(), diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterStringer.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterStringer.java index a06b746ec..2be94278d 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterStringer.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/NutsTextNodeWriterStringer.java @@ -90,7 +90,7 @@ public void writeNode(NutsText node, NutsTextWriteConfiguration ctx) { writeNode(s.getChild(), ctx); } else { writeNode( - ws.text().ofStyled(s.getChild(), s.getStyles().removeFirst()), + NutsTexts.of(ws).ofStyled(s.getChild(), s.getStyles().removeFirst()), ctx); } writeRaw(s.getEnd()); @@ -102,7 +102,7 @@ public void writeNode(NutsText node, NutsTextWriteConfiguration ctx) { writeNode(s.getChild(), ctx); } else { writeNode( - ws.text().ofStyled(s.getChild(), s.getStyles().removeFirst()), + NutsTexts.of(ws).ofStyled(s.getChild(), s.getStyles().removeFirst()), ctx); } writeRaw("}##");//complex format always uses ## @@ -119,7 +119,7 @@ public void writeNode(NutsText node, NutsTextWriteConfiguration ctx) { if (ctx.isTitleNumberEnabled()) { NutsTextNumbering seq = ctx.getTitleNumberSequence(); if (seq == null) { - seq = ws.text().ofNumbering(); + seq = NutsTexts.of(ws).ofNumbering(); ctx.setTitleNumberSequence(seq); } NutsTextNumbering a = seq.newLevel(s.getTextStyleCode().length()); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/PrintStreamExt.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/PrintStreamExt.java index 4afdd9633..aa5417059 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/PrintStreamExt.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/PrintStreamExt.java @@ -95,7 +95,7 @@ // @Override // public NutsPrintStream format(Locale l, String format, Object... args) { // if(l==null){ -// NutsText s = session.text().setSession(session).toText( +// NutsText s = NutsTexts.of(session).setSession(session).toText( // NutsMessage.cstyle( // format, args // ) diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/UnescapeOutputStream.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/UnescapeOutputStream.java index d95e80e42..42580a671 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/UnescapeOutputStream.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/UnescapeOutputStream.java @@ -31,7 +31,7 @@ public OutputStream getOut() { } private String filterThanEscape(String b) throws IOException { - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); String filtered = txt.builder().append(b).filteredText(); return txt.ofPlain(filtered).toString(); // return ws.text().escapeText( diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/BashCodeHighlighter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/BashCodeHighlighter.java index 067d355d1..610817eef 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/BashCodeHighlighter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/BashCodeHighlighter.java @@ -20,11 +20,11 @@ public class BashCodeHighlighter implements NutsCodeHighlighter { private NutsWorkspace ws; - private NutsTextManager factory; + private NutsTexts factory; public BashCodeHighlighter(NutsWorkspace ws) { this.ws = ws; - factory = NutsWorkspaceUtils.defaultSession(ws).text(); + factory = NutsTexts.of(NutsWorkspaceUtils.defaultSession(ws)); } @Override @@ -175,7 +175,7 @@ private static NutsText[] parseCommandLine_readAntiSlash(StringReaderExt ar, Nut if (ar.hasNext()) { sb2.append(ar.nextChar()); } - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); return new NutsText[]{factory.ofStyled(sb2.toString(), NutsTextStyle.separator())}; } @@ -740,7 +740,7 @@ public NutsText stringToText(String text, NutsSession session) { public NutsText next(StringReaderExt reader, boolean exitOnClosedCurlBrace, boolean exitOnClosedPar, boolean exitOnDblQuote, boolean exitOnAntiQuote, NutsSession session) { boolean lineStart = true; List all = new ArrayList<>(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); boolean exit = false; while (!exit && reader.hasNext()) { switch (reader.peekChar()) { @@ -1090,7 +1090,7 @@ public NutsText next(StringReaderExt reader, boolean exitOnClosedCurlBrace, bool } private NutsText nextDollar(StringReaderExt reader, NutsSession session) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (reader.isAvailable(2)) { char c = reader.peekChar(1); switch (c) { @@ -1149,7 +1149,7 @@ private NutsText nextDollar(StringReaderExt reader, NutsSession session) { public NutsText nextDoubleQuotes(StringReaderExt reader, NutsSession session) { List all = new ArrayList<>(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); boolean exit = false; StringBuilder sb = new StringBuilder(); sb.append(reader.nextChar()); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/CustomStyleCodeHighlighter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/CustomStyleCodeHighlighter.java index 46d42c747..410cc694d 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/CustomStyleCodeHighlighter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/CustomStyleCodeHighlighter.java @@ -1,23 +1,20 @@ package net.thevpc.nuts.runtime.core.format.text.highlighters; +import net.thevpc.nuts.*; import net.thevpc.nuts.spi.NutsSupportLevelContext; -import net.thevpc.nuts.NutsTextStyle; import net.thevpc.nuts.spi.NutsComponent; -import net.thevpc.nuts.NutsCodeHighlighter; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsTextManager; -import net.thevpc.nuts.NutsText; +import net.thevpc.nuts.NutsTexts; public class CustomStyleCodeHighlighter implements NutsCodeHighlighter { private NutsSession session; private NutsTextStyle style; - private NutsTextManager factory; + private NutsTexts factory; public CustomStyleCodeHighlighter(NutsTextStyle style, NutsSession session) { this.session = session; this.style = style; - factory = session.text(); + factory = NutsTexts.of(session); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/FishCodeHighlighter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/FishCodeHighlighter.java index af1953f2b..3de507a21 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/FishCodeHighlighter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/FishCodeHighlighter.java @@ -18,11 +18,11 @@ public class FishCodeHighlighter implements NutsCodeHighlighter { private NutsWorkspace ws; - private NutsTextManager factory; + private NutsTexts factory; public FishCodeHighlighter(NutsWorkspace ws) { this.ws = ws; - factory = NutsWorkspaceUtils.defaultSession(ws).text(); + factory = NutsTexts.of(NutsWorkspaceUtils.defaultSession(ws)); } @Override @@ -164,7 +164,7 @@ private static NutsText[] parseCommandLine_readAntiSlash(StringReaderExt ar, Nut if (ar.hasNext()) { sb2.append(ar.nextChar()); } - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); return new NutsText[]{factory.ofStyled(sb2.toString(), NutsTextStyle.separator())}; } @@ -729,7 +729,7 @@ public NutsText stringToText(String text, NutsSession session) { public NutsText next(StringReaderExt reader, boolean exitOnClosedCurlBrace, boolean exitOnClosedPar, boolean exitOnDblQuote, boolean exitOnAntiQuote, NutsSession session) { boolean lineStart = true; List all = new ArrayList<>(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); boolean exit = false; while (!exit && reader.hasNext()) { switch (reader.peekChar()) { @@ -1079,7 +1079,7 @@ public NutsText next(StringReaderExt reader, boolean exitOnClosedCurlBrace, bool } private NutsText nextDollar(StringReaderExt reader, NutsSession session) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (reader.isAvailable(2)) { char c = reader.peekChar(1); switch (c) { @@ -1138,7 +1138,7 @@ private NutsText nextDollar(StringReaderExt reader, NutsSession session) { public NutsText nextDoubleQuotes(StringReaderExt reader, NutsSession session) { List all = new ArrayList<>(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); boolean exit = false; StringBuilder sb = new StringBuilder(); sb.append(reader.nextChar()); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/HadraCodeHighlighter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/HadraCodeHighlighter.java index 8d7bb39fb..4177d1ff1 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/HadraCodeHighlighter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/HadraCodeHighlighter.java @@ -36,7 +36,7 @@ public class HadraCodeHighlighter implements NutsCodeHighlighter { ) ); private NutsWorkspace ws; - NutsTextManager factory; + NutsTexts factory; @Override public String getId() { @@ -45,7 +45,7 @@ public String getId() { public HadraCodeHighlighter(NutsWorkspace ws) { this.ws = ws; - factory = NutsWorkspaceUtils.defaultSession(ws).text(); + factory = NutsTexts.of(NutsWorkspaceUtils.defaultSession(ws)); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/JavaCodeHighlighter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/JavaCodeHighlighter.java index 08e0d4e8d..4ad01d0ff 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/JavaCodeHighlighter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/JavaCodeHighlighter.java @@ -26,11 +26,11 @@ public class JavaCodeHighlighter implements NutsCodeHighlighter { ) ); private NutsWorkspace ws; - private NutsTextManager factory; + private NutsTexts factory; public JavaCodeHighlighter(NutsWorkspace ws) { this.ws = ws; - factory = NutsWorkspaceUtils.defaultSession(ws).text(); + factory = NutsTexts.of(NutsWorkspaceUtils.defaultSession(ws)); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/JsonCodeHighlighter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/JsonCodeHighlighter.java index 260fd4b81..9ec27397f 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/JsonCodeHighlighter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/JsonCodeHighlighter.java @@ -14,11 +14,11 @@ public class JsonCodeHighlighter implements NutsCodeHighlighter { private NutsWorkspace ws; - private NutsTextManager factory; + private NutsTexts factory; public JsonCodeHighlighter(NutsWorkspace ws) { this.ws = ws; - factory = NutsWorkspaceUtils.defaultSession(ws).text(); + factory = NutsTexts.of(NutsWorkspaceUtils.defaultSession(ws)); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/NtfCodeHighlighter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/NtfCodeHighlighter.java index 567e1c855..dbaf79682 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/NtfCodeHighlighter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/NtfCodeHighlighter.java @@ -3,6 +3,7 @@ import net.thevpc.nuts.NutsCodeHighlighter; import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.NutsText; +import net.thevpc.nuts.NutsTexts; import net.thevpc.nuts.spi.NutsSupportLevelContext; public class NtfCodeHighlighter implements NutsCodeHighlighter { @@ -18,11 +19,11 @@ public int getSupportLevel(NutsSupportLevelContext context) { @Override public NutsText stringToText(String text, NutsSession session) { - return session.text().parse(text); + return NutsTexts.of(session).parse(text); } @Override public NutsText tokenToText(String text, String tokenType, NutsSession session) { - return session.text().parse(text); + return NutsTexts.of(session).parse(text); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/PlainCodeHighlighter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/PlainCodeHighlighter.java index 3d60da0c7..9f2af0c75 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/PlainCodeHighlighter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/PlainCodeHighlighter.java @@ -1,22 +1,19 @@ package net.thevpc.nuts.runtime.core.format.text.highlighters; +import net.thevpc.nuts.*; import net.thevpc.nuts.spi.NutsSupportLevelContext; -import net.thevpc.nuts.NutsWorkspace; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; import net.thevpc.nuts.spi.NutsComponent; -import net.thevpc.nuts.NutsCodeHighlighter; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsTextManager; -import net.thevpc.nuts.NutsText; +import net.thevpc.nuts.NutsTexts; public class PlainCodeHighlighter implements NutsCodeHighlighter { NutsWorkspace ws; - private NutsTextManager factory; + private NutsTexts factory; public PlainCodeHighlighter(NutsWorkspace ws) { this.ws = ws; - factory = NutsWorkspaceUtils.defaultSession(ws).text(); + factory = NutsTexts.of(NutsWorkspaceUtils.defaultSession(ws)); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/StringReaderExtUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/StringReaderExtUtils.java index 3395374b1..bd7d78722 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/StringReaderExtUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/StringReaderExtUtils.java @@ -6,13 +6,13 @@ import java.util.ArrayList; import java.util.List; import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsTextManager; +import net.thevpc.nuts.NutsTexts; import net.thevpc.nuts.NutsText; public class StringReaderExtUtils { public static NutsText[] readSpaces(NutsSession session, StringReaderExt ar) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); StringBuilder sb = new StringBuilder(); while (ar.hasNext() && ar.peekChar() <= 32) { sb.append(ar.nextChar()); @@ -23,7 +23,7 @@ public static NutsText[] readSpaces(NutsSession session, StringReaderExt ar) { } public static NutsText[] readSlashSlashComments(NutsSession session, StringReaderExt ar) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); StringBuilder sb = new StringBuilder(); if (!ar.peekChars("//")) { return null; @@ -52,7 +52,7 @@ public static NutsText[] readSlashSlashComments(NutsSession session, StringReade } public static NutsText[] readSlashStarComments(NutsSession session, StringReaderExt ar) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); StringBuilder sb = new StringBuilder(); if (!ar.peekChars("/*")) { return null; @@ -81,7 +81,7 @@ public static NutsText[] readSlashStarComments(NutsSession session, StringReader } public static NutsText[] readJSDoubleQuotesString(NutsSession session, StringReaderExt ar) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); List all = new ArrayList<>(); boolean inLoop = true; StringBuilder sb = new StringBuilder(); @@ -131,7 +131,7 @@ public static NutsText[] readJSDoubleQuotesString(NutsSession session, StringRea } public static NutsText[] readJSSimpleQuotes(NutsSession session, StringReaderExt ar) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); List all = new ArrayList<>(); boolean inLoop = true; StringBuilder sb = new StringBuilder(); @@ -181,7 +181,7 @@ public static NutsText[] readJSSimpleQuotes(NutsSession session, StringReaderExt } public static NutsText[] readJSIdentifier(NutsSession session, StringReaderExt ar) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); List all = new ArrayList<>(); StringBuilder sb = new StringBuilder(); if (!ar.hasNext() || !Character.isJavaIdentifierStart(ar.peekChar())) { @@ -201,7 +201,7 @@ public static NutsText[] readJSIdentifier(NutsSession session, StringReaderExt a } public static NutsText[] readNumber(NutsSession session, StringReaderExt ar) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); boolean nbrVisited = false; boolean minusVisited = false; boolean EminusVisited = false; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/WinCmdBlocTextHighlighter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/WinCmdBlocTextHighlighter.java index 88a15277c..57a3a0691 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/WinCmdBlocTextHighlighter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/WinCmdBlocTextHighlighter.java @@ -19,11 +19,11 @@ public class WinCmdBlocTextHighlighter implements NutsCodeHighlighter { private NutsWorkspace ws; - private NutsTextManager factory; + private NutsTexts factory; public WinCmdBlocTextHighlighter(NutsWorkspace ws) { this.ws = ws; - factory = NutsWorkspaceUtils.defaultSession(ws).text(); + factory = NutsTexts.of(NutsWorkspaceUtils.defaultSession(ws)); } @Override @@ -172,7 +172,7 @@ private static NutsText[] parseCommandLine_readAntiSlash(StringReaderExt ar, Nut if (ar.hasNext()) { sb2.append(ar.nextChar()); } - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); return new NutsText[]{factory.ofStyled(sb2.toString(), NutsTextStyle.separator())}; } @@ -707,7 +707,7 @@ public NutsText stringToText(String text, NutsSession session) { public NutsText next(StringReaderExt reader, boolean exitOnClosedCurlBrace, boolean exitOnClosedPar, boolean exitOnDblQuote, boolean exitOnAntiQuote, NutsSession session) { boolean lineStart = true; List all = new ArrayList<>(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); boolean exit = false; while (!exit && reader.hasNext()) { switch (reader.peekChar()) { @@ -1057,7 +1057,7 @@ public NutsText next(StringReaderExt reader, boolean exitOnClosedCurlBrace, bool } private NutsText nextDollar(StringReaderExt reader, NutsSession session) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (reader.isAvailable(2)) { char c = reader.peekChar(1); switch (c) { @@ -1116,7 +1116,7 @@ private NutsText nextDollar(StringReaderExt reader, NutsSession session) { public NutsText nextDoubleQuotes(StringReaderExt reader, NutsSession session) { List all = new ArrayList<>(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); boolean exit = false; StringBuilder sb = new StringBuilder(); sb.append(reader.nextChar()); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/XmlCodeHighlighter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/XmlCodeHighlighter.java index f611b25b0..527f47cbd 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/XmlCodeHighlighter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/highlighters/XmlCodeHighlighter.java @@ -3,23 +3,22 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.bundles.collections.EvictingQueue; import net.thevpc.nuts.runtime.bundles.parsers.StreamTokenizerExt; +import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsComponent; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.StringReader; import java.util.ArrayList; import java.util.List; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; -import net.thevpc.nuts.spi.NutsComponent; -import net.thevpc.nuts.spi.NutsSupportLevelContext; - public class XmlCodeHighlighter implements NutsCodeHighlighter { - private NutsWorkspace ws; - NutsTextManager factory; + NutsTexts factory; + private final NutsWorkspace ws; public XmlCodeHighlighter(NutsWorkspace ws) { this.ws = ws; - factory = NutsWorkspaceUtils.defaultSession(ws).text(); + factory = NutsTexts.of(NutsWorkspaceUtils.defaultSession(ws)); } @Override @@ -33,39 +32,6 @@ public int getSupportLevel(NutsSupportLevelContext context) { return "xml".equals(s) ? NutsComponent.DEFAULT_SUPPORT : NutsComponent.NO_SUPPORT; } - public NutsText tokenToText(String text, String nodeType,NutsSession session) { - factory.setSession(session); - switch (NutsUtilStrings.trim(nodeType).toLowerCase()) { - case "name": - return formatNodeName(text); - case "attribute": - return formatNodeName(text); - case "string": - return formatNodeString(text); - case "<": - case "": - case "&": - case "=": - case "separator": - return formatNodeSeparator(text); - } - return factory.ofPlain(text); - } - - public NutsText formatNodeName(String text) { - return factory.ofStyled(factory.ofPlain(text), NutsTextStyle.keyword()); - } - - public NutsText formatNodeString(String text) { - return factory.ofStyled(factory.ofPlain(text), NutsTextStyle.string()); - } - - public NutsText formatNodeSeparator(String text) { - return factory.ofStyled(factory.ofPlain(text), NutsTextStyle.separator()); - } - @Override public NutsText stringToText(String text, NutsSession session) { factory.setSession(session); @@ -133,4 +99,37 @@ public NutsText stringToText(String text, NutsSession session) { } return factory.ofList(nodes).simplify(); } + + public NutsText tokenToText(String text, String nodeType, NutsSession session) { + factory.setSession(session); + switch (NutsUtilStrings.trim(nodeType).toLowerCase()) { + case "name": + return formatNodeName(text); + case "attribute": + return formatNodeName(text); + case "string": + return formatNodeString(text); + case "<": + case "": + case "&": + case "=": + case "separator": + return formatNodeSeparator(text); + } + return factory.ofPlain(text); + } + + public NutsText formatNodeName(String text) { + return factory.ofStyled(factory.ofPlain(text), NutsTextStyle.keyword()); + } + + public NutsText formatNodeString(String text) { + return factory.ofStyled(factory.ofPlain(text), NutsTextStyle.string()); + } + + public NutsText formatNodeSeparator(String text) { + return factory.ofStyled(factory.ofPlain(text), NutsTextStyle.separator()); + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/AbstractNutsText.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/AbstractNutsText.java index cbb80cb31..3ca118c51 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/AbstractNutsText.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/AbstractNutsText.java @@ -28,7 +28,7 @@ public String toString() { @Override public NutsString immutable() { - return session.text().builder().append(this).immutable(); + return NutsTexts.of(session).builder().append(this).immutable(); } @Override @@ -58,7 +58,7 @@ public boolean isBlank() { @Override public NutsTextBuilder builder() { - return session.text().builder().append(this); + return NutsTexts.of(session).builder().append(this); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/DefaultNutsTextCode.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/DefaultNutsTextCode.java index 30efa648a..62cfbfb9b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/DefaultNutsTextCode.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/DefaultNutsTextCode.java @@ -27,12 +27,8 @@ package net.thevpc.nuts.runtime.core.format.text.parser; -import net.thevpc.nuts.NutsTextCode; -import net.thevpc.nuts.NutsTextType; -import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTextManager; -import net.thevpc.nuts.NutsCodeHighlighter; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsText; +import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTexts; import java.util.Objects; @@ -60,7 +56,7 @@ public boolean isEmpty() { @Override public NutsText highlight(NutsSession session) { - NutsCodeHighlighter t = ((DefaultNutsTextManager) session.text()) + NutsCodeHighlighter t = ((DefaultNutsTexts) NutsTexts.of(session)) .setSession(session) .resolveCodeHighlighter(getKind()); return t.stringToText(text, session); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/DefaultNutsTextNodeResourceParserHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/DefaultNutsTextNodeResourceParserHelper.java index 9cbd7a9a4..f61249311 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/DefaultNutsTextNodeResourceParserHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/DefaultNutsTextNodeResourceParserHelper.java @@ -117,7 +117,7 @@ private NutsText processHelp(String s, NutsTextFormatLoader classLoader, boolean try { other = parseResource(e, classLoader); } catch (Throwable t) { - other = session.text(). + other = NutsTexts.of(session). builder().append("NOT FOUND", NutsTextStyle.error()) .append(" <" + e + ">").toText(); } @@ -132,8 +132,8 @@ private NutsText processHelp(String s, NutsTextFormatLoader classLoader, boolean if (vars) { help = StringPlaceHolderParser.replaceDollarPlaceHolders(help, pathExpansionConverter); } -// NutsTextParser p = session.text().parser().parse()new DefaultNutsTextNodeParser(session); - NutsText node = session.text().parser().parse(new StringReader(help)); +// NutsTextParser p = NutsTexts.of(session).parser().parse()new DefaultNutsTextNodeParser(session); + NutsText node = NutsTexts.of(session).parser().parse(new StringReader(help)); if (anchor != null) { List ok = new ArrayList<>(); boolean start = false; @@ -149,7 +149,7 @@ private NutsText processHelp(String s, NutsTextFormatLoader classLoader, boolean } } if (start) { - node = session.text().ofList(ok).simplify(); + node = NutsTexts.of(session).ofList(ok).simplify(); } return node; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/AntiQuote3ParserStep.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/AntiQuote3ParserStep.java index 8e69e7c3e..b6108c589 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/AntiQuote3ParserStep.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/AntiQuote3ParserStep.java @@ -2,7 +2,8 @@ import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.NutsTerminalCommand; -import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTextManager; +import net.thevpc.nuts.NutsTexts; +import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTexts; import net.thevpc.nuts.runtime.core.format.text.parser.*; import net.thevpc.nuts.runtime.core.util.CoreStringUtils; import net.thevpc.nuts.NutsText; @@ -130,7 +131,7 @@ public void appendChild(ParserStep tt) { public NutsText toText() { char[] dst = new char[value.length()]; value.getChars(0,value.length(), dst,0 ); - DefaultNutsTextManager factory0 = (DefaultNutsTextManager) session.text(); + DefaultNutsTexts factory0 = (DefaultNutsTexts) NutsTexts.of(session); int i=0; int endOffset=-1; if(dst.length>0 && dst[i]=='!') { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/NewLineParserStep.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/NewLineParserStep.java index bff59c27c..619a40445 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/NewLineParserStep.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/NewLineParserStep.java @@ -1,12 +1,9 @@ package net.thevpc.nuts.runtime.core.format.text.parser.steps; -import net.thevpc.nuts.NutsIllegalArgumentException; -import net.thevpc.nuts.NutsMessage; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTextManager; +import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTexts; import net.thevpc.nuts.runtime.core.format.text.parser.DefaultNutsTextNodeParser; import net.thevpc.nuts.runtime.core.util.CoreStringUtils; -import net.thevpc.nuts.NutsText; public class NewLineParserStep extends ParserStep { @@ -41,7 +38,7 @@ public void appendChild(ParserStep tt) { @Override public NutsText toText() { - DefaultNutsTextManager factory0 = (DefaultNutsTextManager) session.text(); + DefaultNutsTexts factory0 = (DefaultNutsTexts) NutsTexts.of(session); return factory0.ofPlain(start.toString()); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/PlainParserStep.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/PlainParserStep.java index 3c091c63e..7774613fd 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/PlainParserStep.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/PlainParserStep.java @@ -1,6 +1,7 @@ package net.thevpc.nuts.runtime.core.format.text.parser.steps; import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.NutsTexts; import net.thevpc.nuts.runtime.core.format.text.parser.DefaultNutsTextNodeParser; import net.thevpc.nuts.runtime.bundles.string.StringBuilder2; @@ -278,7 +279,7 @@ public void appendChild(ParserStep tt) { public NutsText toText() { String t = value.toString(); // String q = NutsTextNodeWriterStringer.removeEscapes(t); - return session.text().ofPlain(t); + return NutsTexts.of(session).ofPlain(t); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/RootParserStep.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/RootParserStep.java index 63d502e90..1d6d07821 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/RootParserStep.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/RootParserStep.java @@ -2,6 +2,7 @@ import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.NutsTextPlain; +import net.thevpc.nuts.NutsTexts; import net.thevpc.nuts.runtime.core.format.text.parser.DefaultNutsTextNodeParser; import java.util.ArrayList; @@ -69,7 +70,7 @@ public NutsText toText() { all.add(n); } } - return session.text().ofList(all).simplify(); + return NutsTexts.of(session).ofList(all).simplify(); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/StyledParserStep.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/StyledParserStep.java index 0f74d4050..6ba30b0de 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/StyledParserStep.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/StyledParserStep.java @@ -70,7 +70,7 @@ public StyledParserStep(String c, boolean lineStart, NutsSession session, Defaul public void consume(char c, DefaultNutsTextNodeParser.State state, boolean wasNewLine) { charQueue.add(c); - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); switch (curState) { case EMPTY: { throw new IllegalArgumentException("unexpected"); @@ -586,7 +586,7 @@ public void appendChild(ParserStep tt) { @Override public NutsText toText() { List childrenTextNodes2 = new ArrayList<>(children); - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); if (!content.isEmpty()) { childrenTextNodes2.add(text.ofPlain(content.toString())); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/StyledParserStepCommandParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/StyledParserStepCommandParser.java index 835579d6c..ae1bcf75f 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/StyledParserStepCommandParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/StyledParserStepCommandParser.java @@ -45,7 +45,7 @@ public NutsTextStyles parse(String atStr) { } else { return null; } - return NutsTextStyles.NONE.append(parsedStyles.toArray(new NutsTextStyle[0])); + return NutsTextStyles.PLAIN.append(parsedStyles.toArray(new NutsTextStyle[0])); } private boolean isHexChar(char c) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/TitleParserStep.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/TitleParserStep.java index 5bbb5a947..e2636ae98 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/TitleParserStep.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/parser/steps/TitleParserStep.java @@ -1,7 +1,8 @@ package net.thevpc.nuts.runtime.core.format.text.parser.steps; import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTextManager; +import net.thevpc.nuts.NutsTexts; +import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTexts; import net.thevpc.nuts.runtime.core.format.text.parser.*; import net.thevpc.nuts.runtime.core.util.CoreStringUtils; @@ -38,8 +39,8 @@ public void appendChild(ParserStep tt) { @Override public NutsText toText() { String s = start.toString(); -// NutsTextManager text = ws.text(); - DefaultNutsTextManager factory0 = (DefaultNutsTextManager) session.text(); +// NutsTexts text = ws.text(); + DefaultNutsTexts factory0 = (DefaultNutsTexts) NutsTexts.of(session); String s0=s.trim(); NutsText child=null; if (children.size() == 1) { @@ -49,7 +50,7 @@ public NutsText toText() { for (ParserStep a : children) { all.add(a.toText()); } - child= session.text().ofList(all).simplify(); + child= NutsTexts.of(session).ofList(all).simplify(); } return factory0.createTitle(s,s0.length()-1 ,child,isComplete()); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/DefaultNutsTextFormatTheme.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/DefaultNutsTextFormatTheme.java index 40c8ce12e..bf67d8527 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/DefaultNutsTextFormatTheme.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/DefaultNutsTextFormatTheme.java @@ -48,7 +48,7 @@ public DefaultNutsTextFormatTheme(NutsWorkspace ws) { @Override public NutsTextStyles toBasicStyles(NutsTextStyles styles, NutsSession session) { - NutsTextStyles ret = NutsTextStyles.NONE; + NutsTextStyles ret = NutsTextStyles.PLAIN; if (styles != null) { for (NutsTextStyle style : styles) { ret = ret.append(toBasicStyles(style)); @@ -65,7 +65,7 @@ public NutsTextStyles toBasicStyles(NutsTextStyles styles, NutsSession session) */ public NutsTextStyles toBasicStyles(NutsTextStyle style) { if (style == null) { - return NutsTextStyles.NONE; + return NutsTextStyles.PLAIN; } switch (style.getType()) { case FORE_COLOR: //will be called by recursion diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/NutsTextFormatPropertiesTheme.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/NutsTextFormatPropertiesTheme.java index 595acb962..4b7d6f2db 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/NutsTextFormatPropertiesTheme.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/NutsTextFormatPropertiesTheme.java @@ -21,7 +21,7 @@ public class NutsTextFormatPropertiesTheme implements NutsTextFormatTheme { public NutsTextFormatPropertiesTheme(String name, ClassLoader cls, NutsSession session) { this.session = session; if (name.indexOf('/') >= 0 || name.indexOf('\\') >= 0) { - try (InputStream is = session.io().path(name).getInputStream()) { + try (InputStream is = NutsPath.of(name,session).getInputStream()) { props.load(is); } catch (IOException e) { throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("invalid theme: %s", name), e); @@ -48,7 +48,7 @@ public NutsTextFormatPropertiesTheme(String name, ClassLoader cls, NutsSession s } } else { Path themeFile = Paths.get(session.locations().getStoreLocation( - session.id().parser().parse("net.thevpc.nuts:nuts-runtime#SHARED"), + NutsId.of("net.thevpc.nuts:nuts-runtime#SHARED",session), NutsStoreLocation.CONFIG )).resolve("themes").resolve(name); if (Files.isRegularFile(themeFile)) { @@ -76,7 +76,7 @@ public String getName() { @Override public NutsTextStyles toBasicStyles(NutsTextStyles styles, NutsSession session) { - NutsTextStyles ret = NutsTextStyles.NONE; + NutsTextStyles ret = NutsTextStyles.PLAIN; if (styles != null) { for (NutsTextStyle style : styles) { ret = ret.append(toBasicStyles(style, session)); @@ -144,9 +144,9 @@ public NutsTextStyles toBasicStyles(NutsTextStyle style, NutsSession session, in } String s = getProp(style.getType(), style.getVariant()); if (s == null) { - return NutsTextStyles.NONE; + return NutsTextStyles.PLAIN; } - NutsTextStyles ret = NutsTextStyles.NONE; + NutsTextStyles ret = NutsTextStyles.PLAIN; for (String v : s.split(",")) { NutsTextStyles ss = toBasicStyles(v, style.getVariant(), session, maxLoop - 1); ret = ret.append(ss); @@ -171,264 +171,43 @@ public NutsTextStyles toBasicStyles(String v, int defaultVariant, NutsSession se if (n.equals("*") || n.isEmpty()) { n = "" + defaultVariant; } - switch (k.toLowerCase()) { - case "foreground": - case "foregroundcolor": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return NutsTextStyles.of( - NutsTextStyle.foregroundColor(ii) - ); - } - case "plain": { - return NutsTextStyles.NONE; - } - case "foregroundtruecolor": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return NutsTextStyles.of( - NutsTextStyle.foregroundTrueColor(ii) - ); - } - case "background": - case "backgroundcolor": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return NutsTextStyles.of( - NutsTextStyle.backgroundColor(ii) - ); - } - case "backgroundtruecolor": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return NutsTextStyles.of( - NutsTextStyle.backgroundTrueColor(ii) - ); - } - - case "primary": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.primary(ii), session, maxLoop); - } - case "secondary": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.secondary(ii), session, maxLoop); - } - case "underlined": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.underlined(), session, maxLoop); - } - case "bold": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.bold(), session, maxLoop); - } - case "bool": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.bool(ii), session, maxLoop); - } - case "blink": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.blink(), session, maxLoop); - } - case "comments": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.comments(ii), session, maxLoop); - } - case "config": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.config(ii), session, maxLoop); - } - case "danger": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.danger(ii), session, maxLoop); - } - case "date": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.date(ii), session, maxLoop); - } - case "number": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.number(ii), session, maxLoop); - } - case "error": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.error(ii), session, maxLoop); - } - case "warn": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.warn(ii), session, maxLoop); - } - case "version": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.version(ii), session, maxLoop); - } - case "variable": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.variable(ii), session, maxLoop); - } - case "input": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.input(ii), session, maxLoop); - } - case "title": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.title(ii), session, maxLoop); - } - case "success": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.success(ii), session, maxLoop); - } - case "string": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.string(ii), session, maxLoop); - } - case "striked": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.striked(ii), session, maxLoop); - } - case "separator": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.separator(ii), session, maxLoop); - } - case "reversed": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.reversed(ii), session, maxLoop); - } - case "path": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.path(ii), session, maxLoop); - } - case "option": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.option(ii), session, maxLoop); - } - case "pale": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.pale(ii), session, maxLoop); - } - case "operator": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.operator(ii), session, maxLoop); - } - case "keyword": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); + NutsTextStyleType st = NutsTextStyleType.parseLenient(k, null); + if(st==null){ + if(NutsBlankable.isBlank(n)){ + return NutsTextStyles.PLAIN; + }else { + String z = props.getProperty(n); + if (z != null) { + if (maxLoop < 0) { + return null; + } + return toBasicStyles(z, defaultVariant, session, maxLoop - 1); } - return toBasicStyles(NutsTextStyle.keyword(ii), session, maxLoop); + return NutsTextStyles.PLAIN; } - case "italic": { - Integer ii = CoreNumberUtils.convertToInteger(n, null); - if (ii == null) { - ii = getVarValAsInt(n); - } - return toBasicStyles(NutsTextStyle.italic(ii), session, maxLoop); + } + switch (st){ + case PLAIN:{ + return NutsTextStyles.of(NutsTextStyle.of(st,0)); } - case "info": { + case FORE_COLOR: + case FORE_TRUE_COLOR: + case BACK_COLOR: + case BACK_TRUE_COLOR:{ Integer ii = CoreNumberUtils.convertToInteger(n, null); if (ii == null) { ii = getVarValAsInt(n); } - return toBasicStyles(NutsTextStyle.info(ii), session, maxLoop); + return NutsTextStyles.of(NutsTextStyle.of(st,ii)); } - case "fail": { + default: + { Integer ii = CoreNumberUtils.convertToInteger(n, null); if (ii == null) { ii = getVarValAsInt(n); } - return toBasicStyles(NutsTextStyle.fail(ii), session, maxLoop); + return toBasicStyles(NutsTextStyle.of(st,ii), session, maxLoop); } } - String z = props.getProperty(n); - if(z!=null){ - return toBasicStyles(z, defaultVariant, session, maxLoop-1); - } - return NutsTextStyles.NONE; } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/NutsTextFormatThemeWrapper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/NutsTextFormatThemeWrapper.java index 537c54032..254b7b445 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/NutsTextFormatThemeWrapper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/text/stylethemes/NutsTextFormatThemeWrapper.java @@ -22,7 +22,7 @@ public String getName() { @Override public NutsTextStyles toBasicStyles(NutsTextStyles styles, NutsSession session) { - NutsTextStyles ret = NutsTextStyles.NONE; + NutsTextStyles ret = NutsTextStyles.PLAIN; if (styles != null) { for (NutsTextStyle style : styles) { ret = ret.append(toBasicStyles(style,session)); @@ -33,14 +33,14 @@ public NutsTextStyles toBasicStyles(NutsTextStyles styles, NutsSession session) public NutsTextStyles toBasicStyles(NutsTextStyle style,NutsSession session) { if (style == null) { - return NutsTextStyles.NONE; + return NutsTextStyles.PLAIN; } if (style.getType().basic()) { return NutsTextStyles.of(style); } NutsTextStyles t = other.toBasicStyles(NutsTextStyles.of(style), session); if (t == null) { - return NutsTextStyles.NONE; + return NutsTextStyles.PLAIN; } List rr = new ArrayList<>(); for (NutsTextStyle s : t) { @@ -50,6 +50,6 @@ public NutsTextStyles toBasicStyles(NutsTextStyle style,NutsSession session) { //ignore... } } - return NutsTextStyles.NONE.append(rr.toArray(new NutsTextStyle[0])); + return NutsTextStyles.PLAIN.append(rr.toArray(new NutsTextStyle[0])); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultNutsFormatDestructTypePredicate.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultNutsFormatDestructTypePredicate.java deleted file mode 100644 index 9d4bc5f77..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultNutsFormatDestructTypePredicate.java +++ /dev/null @@ -1,25 +0,0 @@ -package net.thevpc.nuts.runtime.core.format.tree; - -import net.thevpc.nuts.*; - -import java.lang.reflect.Type; -import java.util.function.Predicate; - -public class DefaultNutsFormatDestructTypePredicate implements Predicate { - public static final Predicate INSTANCE=new DefaultNutsFormatDestructTypePredicate(); - @Override - public boolean test(Type x) { - if (x instanceof Class) { - Class c = (Class) x; - return !( -// NutsId.class.isAssignableFrom(c) -// || NutsDependency.class.isAssignableFrom(c) - NutsString.class.isAssignableFrom(c) - || NutsElement.class.isAssignableFrom(c) - || NutsFormattable.class.isAssignableFrom(c) - || NutsMessage.class.isAssignableFrom(c) - ); - } - return false; - } -} \ No newline at end of file diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultTreeFormat.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultNutsTreeFormat.java similarity index 86% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultTreeFormat.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultNutsTreeFormat.java index ed490e975..dd1799c56 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultTreeFormat.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultNutsTreeFormat.java @@ -7,10 +7,11 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.bundles.common.CorePlatformUtils; import net.thevpc.nuts.runtime.core.format.DefaultFormatBase; -import net.thevpc.nuts.runtime.core.format.props.DefaultPropertiesFormat; +import net.thevpc.nuts.runtime.core.format.props.DefaultNutsPropertiesFormat; import net.thevpc.nuts.runtime.core.util.CoreCommonUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; -public class DefaultTreeFormat extends DefaultFormatBase implements NutsTreeFormat { +public class DefaultNutsTreeFormat extends DefaultFormatBase implements NutsTreeFormat { public static final NutsTreeLinkFormat LINK_ASCII_FORMATTER = new AsciiTreeLinkFormat(); public static final NutsTreeLinkFormat LINK_SPACE_FORMATTER = new SpaceTreeLinkFormat(); @@ -21,7 +22,7 @@ public class DefaultTreeFormat extends DefaultFormatBase impleme public final NutsTreeNodeFormat TO_STRING_FORMATTER = new NutsTreeNodeFormat() { @Override public NutsString format(Object o, int depth, NutsSession session) { - return session.text().builder().append(o).immutable(); + return NutsTexts.of(session).builder().append(o).immutable(); } }; private NutsTreeNodeFormat formatter; @@ -33,7 +34,7 @@ public NutsString format(Object o, int depth, NutsSession session) { private XNodeFormatter xNodeFormatter = new XNodeFormatter() { @Override public NutsString[] getMultilineArray(NutsString key, Object value, NutsSession session) { - return DefaultTreeFormat.this.getMultilineArray(key, value); + return DefaultNutsTreeFormat.this.getMultilineArray(key, value); } @Override @@ -43,17 +44,17 @@ public NutsString stringValue(Object o, NutsSession session) { }; - public DefaultTreeFormat(NutsWorkspace ws) { - super(ws, "tree-format"); + public DefaultNutsTreeFormat(NutsSession session) { + super(session, "tree-format"); formatter = TO_STRING_FORMATTER; linkFormatter = CorePlatformUtils.SUPPORTS_UTF_ENCODING ? LINK_UNICODE_FORMATTER : LINK_ASCII_FORMATTER; } - public DefaultTreeFormat(NutsWorkspace ws, NutsTreeModel tree) { + public DefaultNutsTreeFormat(NutsSession ws, NutsTreeModel tree) { this(ws, tree, null, null); } - public DefaultTreeFormat(NutsWorkspace ws, NutsTreeModel tree, NutsTreeNodeFormat formatter, NutsTreeLinkFormat linkFormatter) { + public DefaultNutsTreeFormat(NutsSession ws, NutsTreeModel tree, NutsTreeNodeFormat formatter, NutsTreeLinkFormat linkFormatter) { super(ws, "tree"); if (formatter == null) { formatter = TO_STRING_FORMATTER; @@ -75,7 +76,7 @@ public NutsTreeNodeFormat getNodeFormat() { } @Override - public DefaultTreeFormat setNodeFormat(NutsTreeNodeFormat formatter) { + public DefaultNutsTreeFormat setNodeFormat(NutsTreeNodeFormat formatter) { if (formatter == null) { formatter = TO_STRING_FORMATTER; } @@ -89,7 +90,7 @@ public NutsTreeLinkFormat getLinkFormat() { } @Override - public DefaultTreeFormat setLinkFormat(NutsTreeLinkFormat linkFormatter) { + public DefaultNutsTreeFormat setLinkFormat(NutsTreeLinkFormat linkFormatter) { if (linkFormatter == null) { linkFormatter = LINK_ASCII_FORMATTER; } @@ -104,9 +105,9 @@ public NutsTreeModel getModel() { // if(tree instanceof NutsTreeModel){ return (NutsTreeModel) tree; } - Object destructredObject = getSession().elem() + Object destructredObject = NutsElements.of(getSession()) .setNtf(true) - .setDestructTypeFilter(DefaultNutsFormatDestructTypePredicate.INSTANCE) + .setDestructTypeFilter(NutsElements.DEFAULT_FORMAT_DESTRUCTOR) .destruct(tree); return new NutsElementTreeModel( XNode.root(destructredObject, rootName, getSession(), xNodeFormatter) @@ -114,7 +115,7 @@ public NutsTreeModel getModel() { } @Override - public DefaultTreeFormat setValue(Object value) { + public DefaultNutsTreeFormat setValue(Object value) { this.tree = value; return this; } @@ -137,7 +138,7 @@ public void setOmitRoot(boolean hideRoot) { @Override public String toString() { ByteArrayOutputStream b = new ByteArrayOutputStream(); - NutsPrintStream out = getSession().io().createPrintStream(b); + NutsPrintStream out = NutsPrintStream.of(b,getSession()); NutsTreeModel tree = getModel(); print(tree, "", NutsPositionType.FIRST, tree.getRoot(), out, isEffectiveOmitRoot(), 0, false); out.flush(); @@ -265,7 +266,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { } return true; } - case DefaultPropertiesFormat.OPTION_MULTILINE_PROPERTY: { + case DefaultNutsPropertiesFormat.OPTION_MULTILINE_PROPERTY: { NutsArgument i = cmdLine.nextString(); if (enabled) { addMultilineProperty(i.getKey().getString(), i.getValue().getString()); @@ -281,7 +282,7 @@ public Object getValue() { return tree; } - public DefaultTreeFormat addMultilineProperty(String property, String separator) { + public DefaultNutsTreeFormat addMultilineProperty(String property, String separator) { multilineProperties.put(property, separator); return this; } @@ -295,7 +296,7 @@ private NutsString[] getMultilineArray(NutsString key, Object value) { if (vv.length == 0 || vv.length == 1) { return null; } - return Arrays.stream(vv).map(x -> getSession().text().toText(x)).toArray(NutsString[]::new); + return Arrays.stream(vv).map(x -> NutsTexts.of(getSession()).toText(x)).toArray(NutsString[]::new); } private String getMultilineSeparator(NutsString key) { @@ -306,4 +307,8 @@ private String getMultilineSeparator(NutsString key) { return sep; } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultSearchFormatTree.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultSearchFormatTree.java index 290f70566..afe2eeddf 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultSearchFormatTree.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/DefaultSearchFormatTree.java @@ -30,7 +30,7 @@ public NutsString format(Object o, int depth, NutsSession session) { if (o instanceof XNode) { return ((XNode) o).toNutsString(); } - return getSession().text().builder().append(o).immutable(); + return NutsTexts.of(getSession()).builder().append(o).immutable(); } } }; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/XNode.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/XNode.java index f673b068b..ed8159de9 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/XNode.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/tree/XNode.java @@ -28,9 +28,8 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsString; -import net.thevpc.nuts.NutsWorkspace; + +import net.thevpc.nuts.*; /** * @@ -85,14 +84,19 @@ public NutsString toNutsString() { return keyAsElement; } NutsString _title = resolveTitle(); - NutsString titleOrValueAsElement = format.stringValue(_title != null ? _title : value, session); + NutsString titleOrValueAsElement = null; + if(getChildren()==null || getChildren().isEmpty()){ + titleOrValueAsElement = format.stringValue(_title != null ? _title : value, session); + }else{ + titleOrValueAsElement = format.stringValue(_title, session); + } if (key == null) { return titleOrValueAsElement; } else { if (value instanceof List || value instanceof Map) { - return session.text().builder().append(keyAsElement); + return NutsTexts.of(session).builder().append(keyAsElement); } else { - return session.text().builder().append(keyAsElement).append("=").append(titleOrValueAsElement); + return NutsTexts.of(session).builder().append(keyAsElement).append("=").append(titleOrValueAsElement); } } } @@ -168,7 +172,7 @@ private List getAsList(Object value) { if (map == null) { all.add(entryNode(keyStr, me.getValue(), session, format)); } else { - all.add(entryNode(keyStr, session.elem() + all.add(entryNode(keyStr, NutsElements.of(session) .toElement(Arrays.asList(map)), session, format)); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/xml/DefaultSearchFormatXml.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/xml/DefaultSearchFormatXml.java index eecd7e8dd..05af00c3c 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/xml/DefaultSearchFormatXml.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/xml/DefaultSearchFormatXml.java @@ -25,7 +25,7 @@ public class DefaultSearchFormatXml extends DefaultSearchFormatBase { public DefaultSearchFormatXml(NutsSession session, NutsPrintStream writer, NutsFetchDisplayOptions options) { super(session, writer, NutsContentType.XML, options); - codeFormat = session.text().setSession(session).getCodeHighlighter("xml"); + codeFormat = NutsTexts.of(session).setSession(session).getCodeHighlighter("xml"); } public String getRootName() { @@ -34,7 +34,7 @@ public String getRootName() { @Override public void start() { - NutsTextBuilder builder = getSession().text().builder(); + NutsTextBuilder builder = NutsTexts.of(getSession()).builder(); NutsSession session = getSession(); builder.append(codeFormat.tokenToText("=0){ // elem.setAttribute("index",CoreCommonUtils.stringValue(elemIndex)); // } -// NutsElement elem2 = session.elem().convert(o,NutsElement.class); +// NutsElement elem2 = NutsElements.of(session).convert(o,NutsElement.class); // switch (elem2.type()){ // case STRING:{ // elem.setAttribute("type", "string"); @@ -242,21 +242,21 @@ public static DocumentBuilder createDocumentBuilder(boolean safe, NutsSession se b.setErrorHandler(new ErrorHandler() { @Override public void warning(SAXParseException exception) throws SAXException { - session.log().of(NutsXmlUtils.class).with().session(session) + NutsLoggerOp.of(NutsXmlUtils.class,session) .level(Level.FINEST).verb(NutsLogVerb.WARNING) .log(NutsMessage.jstyle("{0}",exception)); } @Override public void error(SAXParseException exception) throws SAXException { - session.log().of(NutsXmlUtils.class).with().session(session) + NutsLoggerOp.of(NutsXmlUtils.class,session) .level(Level.FINEST).verb(NutsLogVerb.WARNING) .log(NutsMessage.jstyle("{0}",exception)); } @Override public void fatalError(SAXParseException exception) throws SAXException { - session.log().of(NutsXmlUtils.class).with().session(session) + NutsLoggerOp.of(NutsXmlUtils.class,session) .level(Level.FINEST).verb(NutsLogVerb.WARNING) .log(NutsMessage.jstyle("{0}",exception)); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/yaml/SimpleYaml.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/yaml/SimpleYaml.java index 6deb3f0dc..69db14147 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/yaml/SimpleYaml.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/format/yaml/SimpleYaml.java @@ -101,7 +101,7 @@ private static class ElementParser { private BufferedReader reader; private NutsElementFactoryContext context; - private NutsElementFormat ebuilder; + private NutsElements ebuilder; private int fileOffset; private int lineNumber; private int lineOffset; @@ -199,9 +199,9 @@ private void readerReset() { } } - public NutsElementFormat builder() { + public NutsElements builder() { if (ebuilder == null) { - ebuilder = context.getSession().elem().setSession(context.getSession()); + ebuilder = NutsElements.of(context.getSession()).setSession(context.getSession()); } return ebuilder; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/DefaultPathBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/DefaultPathBuilder.java index cebf16be0..56cf9f436 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/DefaultPathBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/DefaultPathBuilder.java @@ -14,7 +14,7 @@ public class DefaultPathBuilder implements NutsPathBuilder { EffectiveResolver effectiveResolver; private Function resolver; private NutsSession session; - private String baseDir; + private NutsPath baseDir; private NutsPath base; private boolean expandVars = true; @@ -48,20 +48,20 @@ public NutsPathBuilder withWorkspaceBaseDir() { @Override public NutsPathBuilder withAppBaseDir() { - setBaseDir(System.getProperty("user.dir")); + setBaseDir(NutsPath.of(System.getProperty("user.dir"),session)); return this; } @Override - public String getBaseDir() { + public NutsPath getBaseDir() { if (baseDir == null) { - return System.getProperty("user.dir"); + return NutsPath.of(System.getProperty("user.dir"),session); } return baseDir; } @Override - public NutsPathBuilder setBaseDir(String baseDir) { + public NutsPathBuilder setBaseDir(NutsPath baseDir) { this.baseDir = baseDir; return this; } @@ -96,13 +96,11 @@ public String toString() { } private NutsPath expandVars(NutsPath path) { - NutsIOManager io = session.io(); - return io.path(StringPlaceHolderParser.replaceDollarPlaceHolders(path.toString(), effectiveResolver)); + return NutsPath.of(StringPlaceHolderParser.replaceDollarPlaceHolders(path.toString(), effectiveResolver),session); } private NutsPath expandFile(NutsPath npath) { Path fp = npath.toFile(); - NutsIOManager io = session.io(); if (fp != null && fp.toString().length() > 0) { Path ppath = fp; String path = fp.toString(); @@ -113,36 +111,36 @@ private NutsPath expandFile(NutsPath npath) { NutsWorkspaceLocationManager locations = session.locations(); if (path.equals("~~")) { Path nutsHome = Paths.get(locations.getHomeLocation(NutsStoreLocation.CONFIG)); - return io.path(nutsHome.normalize().toString()); + return NutsPath.of(nutsHome.normalize(),session); } else if (path.startsWith("~~") && path.length() > 2 && (path.charAt(2) == '/' || path.charAt(2) == '\\')) { Path nutsHome = Paths.get(locations.getHomeLocation(NutsStoreLocation.CONFIG)); - return io.path(nutsHome.resolve(path.substring(3)).normalize().toString()); + return NutsPath.of(nutsHome.resolve(path.substring(3)).normalize(),session); } else if (path.equals("~")) { - return io.path(System.getProperty("user.home")); + return NutsPath.of(System.getProperty("user.home"),session); } else if (path.startsWith("~") && path.length() > 1 && (path.charAt(1) == '/' || path.charAt(1) == '\\')) { - return io.path(System.getProperty("user.home") + File.separator + path.substring(2)); + return NutsPath.of(System.getProperty("user.home") + File.separator + path.substring(2),session); } else if (baseDir != null) { - if (CoreIOUtils.isURL(baseDir)) { - return io.path(baseDir + "/" + path); + if (baseDir.isURL()) { + return baseDir.resolve(path); } - return io.path(Paths.get(baseDir).resolve(path).toAbsolutePath().normalize()); + return baseDir.resolve(path).toAbsolute().normalize(); } else { if (CoreIOUtils.isURL(path)) { - return io.path(path); + return NutsPath.of(path,session); } - return io.path(ppath.toAbsolutePath().normalize()); + return NutsPath.of(ppath.toAbsolutePath().normalize(),session); } } else if (path.equals(".") || path.equals("..")) { - return io.path(ppath.toAbsolutePath().normalize()); + return NutsPath.of(ppath.toAbsolutePath().normalize(),session); } else if (ppath.isAbsolute()) { - return io.path(ppath.normalize()); + return NutsPath.of(ppath.normalize(),session); } else if (baseDir != null) { - if (CoreIOUtils.isURL(baseDir)) { - return io.path(baseDir + "/" + path); + if (baseDir.isURL()) { + return baseDir.resolve( path); } - return io.path(Paths.get(baseDir).resolve(path).toAbsolutePath().normalize()); + return baseDir.resolve(path).toAbsolute().normalize(); } else { - return io.path(ppath.toAbsolutePath().normalize()); + return NutsPath.of(ppath.toAbsolutePath().normalize(),session); } } return npath; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/FilePath.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/FilePath.java index bba6a12ad..a9bda6055 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/FilePath.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/FilePath.java @@ -38,7 +38,7 @@ private NutsPath toNutsPathInstance() { public NutsPath[] getChildren() { if (Files.isDirectory(value)) { try { - return Files.list(value).map(x -> getSession().io().path(x)).toArray(NutsPath[]::new); + return Files.list(value).map(x -> NutsPath.of(x,getSession())).toArray(NutsPath[]::new); } catch (IOException e) { // } @@ -69,7 +69,7 @@ public NutsPath resolve(String other) { for (String s : others) { value2 = value2.resolve(s); } - return getSession().io().path(value2); + return NutsPath.of(value2,getSession()); } return toNutsPathInstance(); } @@ -256,7 +256,7 @@ public NutsPath getParent() { if (p == null) { return null; } - return getSession().io().path(p); + return NutsPath.of(p,getSession()); } @Override @@ -470,7 +470,7 @@ public MyPathFormat(FilePath p) { } public NutsString asFormattedString() { - return p.getSession().text().toText(p.value); + return NutsTexts.of(p.getSession()).toText(p.value); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsCompressedPath.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsCompressedPath.java index ec1ca0653..d05e4e9c6 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsCompressedPath.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsCompressedPath.java @@ -4,6 +4,7 @@ import net.thevpc.nuts.runtime.bundles.io.InputStreamMetadataAwareImpl; import net.thevpc.nuts.runtime.bundles.io.URLBuilder; import net.thevpc.nuts.runtime.core.format.DefaultFormatBase; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.File; import java.io.InputStream; @@ -26,7 +27,7 @@ public NutsCompressedPath(NutsPath base) { super(base.getSession()); this.base = base; this.compressedForm = compressUrl(base.toString()); - this.formattedCompressedForm = base.getSession().text().ofStyled(compressedForm, NutsTextStyle.path()); + this.formattedCompressedForm = NutsTexts.of(base.getSession()).ofStyled(compressedForm, NutsTextStyle.path()); } public NutsCompressedPath(NutsPath base, String compressedForm, NutsString formattedCompressedForm) { @@ -295,12 +296,12 @@ private static class MyPathFormat extends DefaultFormatBase { private final NutsCompressedPath p; public MyPathFormat(NutsCompressedPath p) { - super(p.getSession().getWorkspace(), "path"); + super(p.getSession(), "path"); this.p = p; } public NutsString asFormattedString() { - return p.base.getSession().text().ofStyled(p.compressedForm, NutsTextStyle.path()); + return NutsTexts.of(p.base.getSession()).ofStyled(p.compressedForm, NutsTextStyle.path()); } @Override @@ -312,6 +313,11 @@ public void print(NutsPrintStream out) { public boolean configureFirst(NutsCommandLine commandLine) { return false; } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsPathBase.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsPathBase.java index 392b0b426..7fe1122b1 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsPathBase.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsPathBase.java @@ -2,6 +2,7 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.format.DefaultFormatBase; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.BufferedReader; import java.io.IOException; @@ -61,7 +62,7 @@ public String getFullExtension() { @Override public NutsString getFormattedName() { - return getSession().text().ofStyled(getName(),NutsTextStyle.path()); + return NutsTexts.of(getSession()).ofStyled(getName(),NutsTextStyle.path()); } @Override @@ -97,7 +98,7 @@ public Path asFilePath() { public NutsString toNutsString() { - return session.text().ofPlain(toString()); + return NutsTexts.of(session).ofPlain(toString()); } @Override @@ -111,19 +112,24 @@ private static class PathFormat extends DefaultFormatBase { private NutsPathBase p; public PathFormat(NutsPathBase p) { - super(p.session.getWorkspace(), "path"); + super(p.session, "path"); this.p = p; } @Override public void print(NutsPrintStream out) { - out.print(p.session.text().ofStyled(p.toNutsString(), NutsTextStyle.path())); + out.print(NutsTexts.of(p.session).ofStyled(p.toNutsString(), NutsTextStyle.path())); } @Override public boolean configureFirst(NutsCommandLine commandLine) { return false; } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsPathFromSPI.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsPathFromSPI.java index bddf173a0..6262f6806 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsPathFromSPI.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsPathFromSPI.java @@ -6,6 +6,7 @@ import net.thevpc.nuts.runtime.core.util.CoreIOUtils; import net.thevpc.nuts.spi.NutsFormatSPI; import net.thevpc.nuts.spi.NutsPathSPI; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.InputStream; import java.io.OutputStream; @@ -109,8 +110,7 @@ public NutsPath[] getChildren() { return p; } } catch (Exception ex) { - getSession().log().of(NutsPathFromSPI.class) - .with() + NutsLoggerOp.of(NutsPathFromSPI.class,getSession()) .verb(NutsLogVerb.WARNING) .level(Level.WARNING) .error(ex) @@ -245,7 +245,7 @@ public NutsPath toAbsolute() { @Override public NutsPath toAbsolute(String basePath) { - return toAbsolute(basePath==null?null:getSession().io().path(basePath)); + return toAbsolute(basePath==null?null:NutsPath.of(basePath,getSession())); } @Override @@ -275,7 +275,7 @@ public Set getPermissions() { public NutsFormat formatter() { NutsFormatSPI fspi = base.getFormatterSPI(); if (fspi != null) { - return new DefaultFormatBase(getSession().getWorkspace(), "path") { + return new DefaultFormatBase(getSession(), "path") { @Override public void print(NutsPrintStream out) { fspi.print(out); @@ -285,7 +285,12 @@ public void print(NutsPrintStream out) { public boolean configureFirst(NutsCommandLine commandLine) { return fspi.configureFirst(commandLine); } - }.setSession(getSession()); + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } + }; } return super.formatter(); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsResourcePath.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsResourcePath.java index bb65f2751..80a612b4f 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsResourcePath.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/NutsResourcePath.java @@ -46,7 +46,7 @@ public NutsResourcePath(String path, NutsSession session) { } else { throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("invalid path %s", path)); } - NutsIdParser nutsIdParser = session.id().parser().setLenient(false); + NutsIdParser nutsIdParser = NutsIdParser.of(session); this.ids = Arrays.stream(idsStr.split(";")).map(x -> { x = x.trim(); if (x.length() > 0) { @@ -82,7 +82,7 @@ public NutsPath toURLPath() { this.ids.toArray(new NutsId[0]) ).setLatest(true).setContent(true).setDependencies(true) .setDependencyFilter( - getSession().filters().dependency() + NutsDependencyFilters.of(getSession()) .byScope(NutsDependencyScopePattern.RUN) ) .setOptional(false).getResultClassLoader(); @@ -93,7 +93,7 @@ public NutsPath toURLPath() { } URL resource = resultClassLoader.getResource(loc); if (resource != null) { - urlPath = getSession().io().path(resource); + urlPath = NutsPath.of(resource,getSession()); } } catch (Exception e) { //e.printStackTrace(); @@ -264,7 +264,7 @@ public NutsPath getParent() { if(ppath==null){ return null; } - return session.io().path(rebuildURL(ppath,ids.toArray(new NutsId[0]))); + return NutsPath.of(rebuildURL(ppath,ids.toArray(new NutsId[0])),getSession()); } @Override @@ -344,7 +344,7 @@ public MyPathFormat(NutsResourcePath p) { public NutsString asFormattedString() { String path = p.path; - NutsTextManager text = p.getSession().text(); + NutsTexts text = NutsTexts.of(p.getSession()); NutsTextBuilder tb = text.builder(); tb.append("nuts-resource://", NutsTextStyle.primary1()); if (path.startsWith("nuts-resource://(")) { @@ -352,9 +352,9 @@ public NutsString asFormattedString() { int x = path.indexOf(')'); if (x > 0) { String idsStr = path.substring("nuts-resource://(".length(), x); - NutsIdParser nutsIdParser = p.getSession().id().parser().setLenient(false); + NutsIdParser nutsIdParser = NutsIdParser.of(p.getSession()); tb.appendJoined( - p.getSession().text().ofStyled(";",NutsTextStyle.separator()), + NutsTexts.of(p.getSession()).ofStyled(";",NutsTextStyle.separator()), Arrays.stream(idsStr.split(";")).map(xi -> { xi = xi.trim(); if (xi.length() > 0) { @@ -375,7 +375,7 @@ public NutsString asFormattedString() { int x = path.indexOf('/', "nuts-resource://".length()); if (x > 0) { String sid = path.substring("nuts-resource://".length(), x); - NutsId ii = p.getSession().id().parser().setLenient(true).parse(sid); + NutsId ii = NutsId.of(sid,p.getSession()); if(ii==null) { tb.append(sid); }else{ diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/URLPath.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/URLPath.java index 2cdf71b64..da115e565 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/URLPath.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/io/URLPath.java @@ -137,7 +137,7 @@ public Path toFile() { public NutsPath[] getChildren() { try { Path f = toFile(); - return getSession().io().path(f).getChildren(); + return NutsPath.of(f,session).getChildren(); } catch (Exception e) { // } @@ -145,7 +145,7 @@ public NutsPath[] getChildren() { } private NutsPath wrapperNutsPath(){ - return getSession().io().path(url); + return NutsPath.of(url,getSession()); } public InputStream getInputStream() { @@ -269,7 +269,7 @@ public NutsPath getParent() { try { File f = CoreIOUtils.toFile(toURL()); if (f != null) { - return getSession().io().path(f.toPath().getParent()); + return NutsPath.of(f.toPath().getParent(),getSession()); } String ppath = CoreIOUtils.getURLParentPath(url.getPath()); if(ppath==null){ @@ -284,14 +284,14 @@ public NutsPath getParent() { this.url.getRef() ) ); - return getSession().io().path(url); + return NutsPath.of(url,getSession()); } catch (IOException e) { return null; } } protected NutsPath rebuildURLPath(String other) { - return session.io().path(other); + return NutsPath.of(other,session); } protected String rebuildURLString(String protocol, String authority, String file, String ref) { @@ -336,9 +336,9 @@ public MyPathFormat(URLPath p) { public NutsString asFormattedString() { if (p.url == null) { - return p.getSession().text().ofPlain(""); + return NutsTexts.of(p.getSession()).ofPlain(""); } - return p.getSession().text().toText(p.url); + return NutsTexts.of(p.getSession()).toText(p.url); } @Override @@ -369,7 +369,7 @@ public boolean isAbsolute() { public NutsPath asFilePath() { File f = CoreIOUtils.toFile(toURL()); - return (f != null) ?session.io().path(f):null; + return (f != null) ?NutsPath.of(f,getSession()):null; } public boolean isSymbolicLink() { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogManager.java index eaa1ea313..faa8bf551 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogManager.java @@ -1,107 +1,109 @@ package net.thevpc.nuts.runtime.core.log; -import net.thevpc.nuts.*; +import net.thevpc.nuts.NutsLogger; +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.NutsWorkspace; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; +import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.spi.NutsLogManager; +import net.thevpc.nuts.spi.NutsSupportLevelContext; + import java.util.logging.Handler; import java.util.logging.Level; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class DefaultNutsLogManager implements NutsLogManager { - private DefaultNutsLogModel model; - private NutsSession session; + private final DefaultNutsLogModel model; + private final NutsWorkspace ws; - public DefaultNutsLogManager(DefaultNutsLogModel model) { - this.model = model; + public DefaultNutsLogManager(NutsWorkspace ws) { + this.ws = ws; + this.model = ((NutsWorkspaceExt) ws).getModel().logModel; } @Override - public Handler[] getHandlers() { - checkSession(); + public Handler[] getHandlers(NutsSession session) { + checkSession(session); return model.getHandlers(); } @Override - public NutsLogManager removeHandler(Handler handler) { - checkSession(); + public NutsLogManager removeHandler(Handler handler, NutsSession session) { + checkSession(session); model.removeHandler(handler); return this; } @Override - public NutsLogManager addHandler(Handler handler) { - checkSession(); + public NutsLogManager addHandler(Handler handler, NutsSession session) { + checkSession(session); model.addHandler(handler); return this; } @Override - public Handler getTermHandler() { - checkSession(); + public Handler getTermHandler(NutsSession session) { + checkSession(session); return model.getTermHandler(); } @Override - public Handler getFileHandler() { - checkSession(); + public Handler getFileHandler(NutsSession session) { + checkSession(session); return model.getFileHandler(); } @Override - public NutsLogger of(String name) { - checkSession(); - return model.of(name,getSession()); + public NutsLogger createLogger(String name, NutsSession session) { + checkSession(session); + return model.createLogger(name, session); } @Override - public NutsLogger of(Class clazz) { - checkSession(); - return model.of(clazz,getSession()); + public NutsLogger createLogger(Class clazz, NutsSession session) { + checkSession(session); + return model.createLogger(clazz, session); } @Override - public Level getTermLevel() { - checkSession(); + public Level getTermLevel(NutsSession session) { + checkSession(session); return model.getTermLevel(); } @Override - public NutsLogManager setTermLevel(Level level) { - checkSession(); + public NutsLogManager setTermLevel(Level level, NutsSession session) { + checkSession(session); model.setTermLevel(level, session); return this; } @Override - public Level getFileLevel() { - checkSession(); + public Level getFileLevel(NutsSession session) { + checkSession(session); return model.getFileLevel(); } @Override - public NutsLogManager setFileLevel(Level level) { - checkSession(); + public NutsLogManager setFileLevel(Level level, NutsSession session) { + checkSession(session); model.setFileLevel(level, session); return this; } - private void checkSession() { + private void checkSession(NutsSession session) { NutsWorkspaceUtils.checkSession(model.getWorkspace(), session); } - @Override - public NutsSession getSession() { - return this.session; - } - - @Override - public NutsLogManager setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(model.getWorkspace(), session); - return this; - } - public DefaultNutsLogModel getModel() { return model; } - + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogModel.java index 3bafaa0f6..a8c02898c 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogModel.java @@ -25,8 +25,8 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.AbstractNutsWorkspace; -import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; +import net.thevpc.nuts.runtime.standalone.boot.DefaultNutsBootManager; import java.nio.file.Path; import java.nio.file.Paths; @@ -70,7 +70,7 @@ public DefaultNutsLogModel(NutsWorkspace ws, NutsWorkspaceInitInformation option logConfig.setLogFileBase(lc.getLogFileBase()); logConfig.setLogFileSize(lc.getLogFileSize()); } - out = NutsWorkspaceUtils.defaultSession(workspace).io().stderr(); + out = (((DefaultNutsBootManager)(ws.boot()))).getModel().stderr(); } public NutsSession getDefaultSession() { @@ -112,7 +112,7 @@ public Handler getFileHandler() { } - public NutsLogger of(String name, NutsSession session) { + public NutsLogger createLogger(String name, NutsSession session) { NutsLogger y = loaded.get(name); if (y == null) { if (session == null) { @@ -125,7 +125,7 @@ public NutsLogger of(String name, NutsSession session) { } - public NutsLogger of(Class clazz, NutsSession session) { + public NutsLogger createLogger(Class clazz, NutsSession session) { NutsLogger y = loaded.get(clazz.getName()); if (y == null) { if (session == null) { @@ -208,7 +208,7 @@ public void updateTermHandler(LogRecord record) { } } else { consoleHandler = new NutsLogConsoleHandler(out, false, - ((AbstractNutsWorkspace) workspace).defaultSession() + NutsWorkspaceExt.of(workspace).defaultSession() ); consoleHandler.setLevel(logConfig.getLogTermLevel()); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogger.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogger.java index a8ac28cf3..3533bf53e 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogger.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/DefaultNutsLogger.java @@ -1,6 +1,7 @@ package net.thevpc.nuts.runtime.core.log; import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsLogManager; import java.util.Iterator; import java.util.LinkedList; @@ -53,14 +54,13 @@ private boolean isLoggable(Level level, Level current) { } public boolean isLoggable(Level level) { - NutsLogManager _log = getSession().log(); - if (isLoggable(level, _log.getTermLevel())) { + if (isLoggable(level, NutsLogger.getTermLevel(getSession()))) { return true; } - if (isLoggable(level, _log.getFileLevel())) { + if (isLoggable(level, NutsLogger.getFileLevel(getSession()))) { return true; } - for (Handler handler : _log.getHandlers()) { + for (Handler handler : NutsLogger.getHandlers(getSession())) { if (isLoggable(level, handler.getLevel())) { return true; } @@ -148,7 +148,7 @@ public void suspendTerminal() { * @param record the LogRecord to be published */ private void log0(LogRecord record) { - DefaultNutsLogManager logManager = (DefaultNutsLogManager) getSession().log(); + DefaultNutsLogManager logManager = (DefaultNutsLogManager) NutsLogManager.of(getSession()); logManager.getModel().updateHandlers(record); Handler ch = logManager.getModel().getTermHandler(); if (ch != null) { @@ -183,8 +183,8 @@ private void log0(LogRecord record) { public void resumeTerminal(NutsSession session) { suspendTerminalMode = false; - DefaultNutsLogManager logManager = (DefaultNutsLogManager) session.log().setSession(session); - Handler ch = logManager.getTermHandler(); + Handler ch = NutsLogger.getTermHandler(session); + DefaultNutsLogManager logManager = (DefaultNutsLogManager) NutsLogManager.of(session); for (Iterator iterator = suspendedTerminalRecords.iterator(); iterator.hasNext(); ) { LogRecord r = iterator.next(); iterator.remove(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogPlainFormatter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogPlainFormatter.java index 0bd2512d5..0a352da29 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogPlainFormatter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogPlainFormatter.java @@ -50,7 +50,7 @@ // parameters2 = new Object[0]; // } // String msgStr = null; -// NutsTextManager text = wRecord.getSession().text(); +// NutsTexts text = NutsTexts.of(wRecord.getSession()); // if (wRecord.isFormatted()) { // msgStr = (text.setSession(wRecord.getSession()).toText( // new NutsMessage( diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogRecord.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogRecord.java index 84e83cd9c..f8876db8f 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogRecord.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogRecord.java @@ -51,7 +51,7 @@ public void setSession(NutsSession session) { // public NutsLogRecord filter(){ // if(isFormatted()) { // NutsLogRecord r = new NutsLogRecord(session,getLevel(), verb, -// session.text().builder().append(getMessage()).filteredText() +// NutsTexts.of(session).builder().append(getMessage()).filteredText() // ,getParameters(),false,time,formatStyle); // r.setSequenceNumber(this.getSequenceNumber()); // r.setThreadID(this.getThreadID()); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogRichFormatter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogRichFormatter.java index ab78e744a..fc8e988b3 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogRichFormatter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogRichFormatter.java @@ -23,7 +23,7 @@ public NutsLogRichFormatter(NutsSession session, boolean filtered) { @Override public String format(LogRecord record) { NutsLogRecord wRecord = NutsLogUtils.toNutsLogRecord(record, session); - NutsTextManager tf = wRecord.getSession().text().setSession(wRecord.getSession()); + NutsTexts tf = NutsTexts.of(wRecord.getSession()).setSession(wRecord.getSession()); NutsTextBuilder sb = tf.builder(); String date = CoreNutsUtils.DEFAULT_DATE_TIME_FORMATTER.format(Instant.ofEpochMilli(wRecord.getMillis())); @@ -140,7 +140,7 @@ public String format(LogRecord record) { NutsMessage message = wRecord.getNutsMessage(); NutsString msgStr = - wRecord.getSession().text() + NutsTexts.of(wRecord.getSession()) .toText(message); sb.append(msgStr); if (wRecord.getTime() > 0) { @@ -152,7 +152,7 @@ public String format(LogRecord record) { lastMillis = wRecord.getMillis(); if (wRecord.getThrown() != null) { sb.append( - wRecord.getSession().text().ofPlain( + NutsTexts.of(wRecord.getSession()).ofPlain( NutsLogUtils.stacktrace(wRecord.getThrown()) ).toString() ); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogUtils.java index 5d84af66d..53cbc9974 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/log/NutsLogUtils.java @@ -2,6 +2,7 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.AbstractNutsWorkspace; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; import java.io.PrintWriter; import java.io.StringWriter; @@ -172,7 +173,7 @@ public static final NutsSession resolveSession(LogRecord record,NutsWorkspace ws session=((NutsLogRecord) record).getSession(); } if(session==null){ - session=((AbstractNutsWorkspace)ws).defaultSession(); + session=NutsWorkspaceExt.of(ws).defaultSession(); } return session; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/AbstractNutsDescriptor.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/AbstractNutsDescriptor.java index 01f65928f..d34cd2027 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/AbstractNutsDescriptor.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/AbstractNutsDescriptor.java @@ -27,6 +27,7 @@ import net.thevpc.nuts.NutsDescriptor; import net.thevpc.nuts.NutsDescriptorBuilder; +import net.thevpc.nuts.NutsDescriptorFormat; import net.thevpc.nuts.NutsSession; /** @@ -41,7 +42,11 @@ public AbstractNutsDescriptor(NutsSession session) { @Override public NutsDescriptorBuilder builder() { - return session.descriptor().descriptorBuilder().setAll(this); + return NutsDescriptorBuilder.of(session).setAll(this); } + @Override + public NutsDescriptorFormat formatter() { + return NutsDescriptorFormat.of(session).setValue(this); + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/CoreNutsWorkspaceOptions.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/CoreNutsWorkspaceOptions.java index 4b9ec0d20..4f829647d 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/CoreNutsWorkspaceOptions.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/CoreNutsWorkspaceOptions.java @@ -1476,9 +1476,10 @@ public NutsWorkspaceOptionsBuilder setAll(NutsWorkspaceOptions other) { @Override public NutsWorkspaceOptionsBuilder parseCommandLine(String commandLine) { - return parseArguments(session.commandLine() - .setCommandlineFamily(NutsShellFamily.SH) - .parse(commandLine).toStringArray()); + return parseArguments( + NutsCommandLine.parse(commandLine,NutsShellFamily.SH,session) + .toStringArray() + ); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsArtifactCall.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsArtifactCall.java index 0ed0b3699..d17605df1 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsArtifactCall.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsArtifactCall.java @@ -136,4 +136,13 @@ public int hashCode() { result = 31 * result + Arrays.hashCode(arguments); return result; } + + @Override + public String toString() { + return "DefaultNutsArtifactCall{" + + "id=" + id + + ", arguments=" + Arrays.toString(arguments) + + ", properties=" + properties + + '}'; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsArtifactCallBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsArtifactCallBuilder.java index 1116d54e8..55ffce372 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsArtifactCallBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsArtifactCallBuilder.java @@ -29,6 +29,7 @@ import net.thevpc.nuts.NutsArtifactCallBuilder; import net.thevpc.nuts.NutsId; import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.Serializable; import java.util.*; @@ -147,4 +148,9 @@ public int hashCode() { public NutsArtifactCall build() { return new DefaultNutsArtifactCall(id, arguments, properties); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDependency.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDependency.java index 6ef318dd4..547422e3b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDependency.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDependency.java @@ -63,7 +63,7 @@ public DefaultNutsDependency(String repository, String groupId, String artifactI this.repository = NutsUtilStrings.trimToNull(repository); this.groupId = NutsUtilStrings.trimToNull(groupId); this.artifactId = NutsUtilStrings.trimToNull(artifactId); - this.version = version == null ? session.version().parser().parse("") : version; + this.version = version == null ? NutsVersion.of("",session) : version; this.classifier = NutsUtilStrings.trimToNull(classifier); this.scope = NutsDependencyScope.parseLenient(scope,NutsDependencyScope.API,NutsDependencyScope.OTHER).id(); @@ -145,7 +145,7 @@ public NutsId toId() { } m.put(NutsConstants.IdProperties.EXCLUSIONS, String.join(",", ex)); } - return session.id().builder() + return NutsIdBuilder.of(session) .setGroupId(getGroupId()) .setArtifactId(getArtifactId()) .setVersion(getVersion()) @@ -299,7 +299,7 @@ public Map getProperties() { @Override public NutsDependencyFormat formatter() { - return session.dependency().formatter().setValue(this); + return NutsDependencyFormat.of(session).setValue(this); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDependencyBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDependencyBuilder.java index 85e1e3721..1c630a923 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDependencyBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDependencyBuilder.java @@ -30,6 +30,7 @@ import java.util.*; import net.thevpc.nuts.runtime.core.util.CoreNutsDependencyUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; /** * Created by vpc on 1/5/17. @@ -266,7 +267,7 @@ public NutsId toId() { } m.put(NutsConstants.IdProperties.EXCLUSIONS, String.join(",", ex)); } - return session.id().builder() + return NutsIdBuilder.of(session) .setRepository(getRepository()) .setGroupId(getGroupId()) .setArtifactId(getArtifactId()) @@ -335,13 +336,13 @@ public NutsVersion getVersion() { @Override public NutsDependencyBuilder setVersion(NutsVersion version) { - this.version = version == null ? session.version().parser().parse("") : version; + this.version = version == null ? NutsVersion.of("",session) : version; return this; } @Override - public NutsDependencyBuilder setVersion(String classifier) { - this.version = session.version().parser().parse(classifier); + public NutsDependencyBuilder setVersion(String version) { + this.version = NutsVersion.of(version,session); return this; } @@ -435,7 +436,7 @@ public NutsDependencyBuilder setExclusions(String exclusions) { exclusions = ""; } List ids = new ArrayList<>(); - NutsIdParser parser = session.id().parser(); + NutsIdParser parser = NutsIdParser.of(session); for (String s : exclusions.split("[;,]")) { NutsId ii = parser.parse(s.trim()); if (ii != null) { @@ -450,4 +451,9 @@ public NutsDependencyBuilder setExclusions(String exclusions) { public String toString() { return build().toString(); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDescriptorBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDescriptorBuilder.java index ca6ba2f9d..776481c4d 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDescriptorBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDescriptorBuilder.java @@ -30,6 +30,7 @@ import net.thevpc.nuts.runtime.bundles.common.MapToFunction; import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; import net.thevpc.nuts.runtime.core.util.CoreStringUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.util.*; import java.util.function.Function; @@ -97,7 +98,7 @@ public NutsDescriptorBuilder setId(NutsId id) { @Override public NutsDescriptorBuilder setId(String id) { - this.id = session.id().parser().setLenient(false).parse(id); + this.id = NutsId.of(id,session); return this; } @@ -308,7 +309,7 @@ public NutsDescriptorBuilder addLocation(NutsIdLocation location) { @Override public NutsDescriptorBuilder setProperty(String name, String value) { - NutsDescriptorProperty pp = session.descriptor().propertyBuilder() + NutsDescriptorProperty pp = NutsDescriptorPropertyBuilder.of(session) .setName(name) .setValue(value) .build(); @@ -523,7 +524,7 @@ public NutsDescriptorBuilder applyParents(NutsDescriptor[] parentDescriptors) { if (properties != null) { n_props.addAll(Arrays.asList(properties)); } - NutsEnvConditionBuilder b = session.descriptor().envConditionBuilder(); + NutsEnvConditionBuilder b = NutsEnvConditionBuilder.of(session); LinkedHashSet n_deps = new LinkedHashSet<>(); LinkedHashSet n_sdeps = new LinkedHashSet<>(); @@ -854,7 +855,7 @@ private NutsEnvCondition applyNutsConditionProperties(NutsEnvCondition child, Fu } private NutsId applyNutsIdProperties(NutsId child, Function properties) { - return session.id().builder() + return NutsIdBuilder.of(session) .setRepository(CoreNutsUtils.applyStringProperties(child.getRepository(), properties)) .setGroupId(CoreNutsUtils.applyStringProperties(child.getGroupId(), properties)) .setArtifactId(CoreNutsUtils.applyStringProperties(child.getArtifactId(), properties)) @@ -871,7 +872,7 @@ private NutsDependency applyNutsDependencyProperties(NutsDependency child, Funct for (int i = 0; i < exclusions.length; i++) { exclusions[i] = applyNutsIdProperties(exclusions[i], properties); } - return session.dependency().builder() + return NutsDependencyBuilder.of(session) .setRepository(CoreNutsUtils.applyStringProperties(child.getRepository(), properties)) .setGroupId(CoreNutsUtils.applyStringProperties(child.getGroupId(), properties)) .setArtifactId(CoreNutsUtils.applyStringProperties(child.getArtifactId(), properties)) @@ -914,4 +915,9 @@ public boolean equals(Object o) { && Objects.equals(solver, that.solver) && Objects.equals(session, that.session); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDescriptorPropertyBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDescriptorPropertyBuilder.java index 60677bc67..607132cb7 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDescriptorPropertyBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsDescriptorPropertyBuilder.java @@ -27,6 +27,7 @@ package net.thevpc.nuts.runtime.core.model; import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsSupportLevelContext; public class DefaultNutsDescriptorPropertyBuilder implements NutsDescriptorPropertyBuilder { @@ -42,7 +43,7 @@ public DefaultNutsDescriptorPropertyBuilder() { public DefaultNutsDescriptorPropertyBuilder(NutsSession session) { this.session = session; - this.condition = session.descriptor().envConditionBuilder(); + this.condition = NutsEnvConditionBuilder.of(session); } @Override @@ -117,4 +118,8 @@ public NutsDescriptorProperty build() { return new DefaultNutsDescriptorProperty(getName(), getValue(), getCondition().build(), session); } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsEnvCondition.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsEnvCondition.java index 3adf747bc..8163d7747 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsEnvCondition.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsEnvCondition.java @@ -41,7 +41,7 @@ public class DefaultNutsEnvCondition implements NutsEnvCondition { @Override public NutsEnvConditionBuilder builder() { - return session.descriptor().envConditionBuilder().setAll(this); + return NutsEnvConditionBuilder.of(session).setAll(this); } private String[] arch; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsEnvConditionBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsEnvConditionBuilder.java index 622ef256b..4f17b89c2 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsEnvConditionBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsEnvConditionBuilder.java @@ -30,6 +30,7 @@ import net.thevpc.nuts.runtime.bundles.common.MapToFunction; import net.thevpc.nuts.runtime.core.util.CoreArrayUtils; import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.util.*; import java.util.function.Function; @@ -308,4 +309,9 @@ public NutsEnvConditionBuilder applyProperties(Map properties) { this.setDesktopEnvironment(CoreNutsUtils.applyStringProperties(getDesktopEnvironment(), map)); return this; } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsId.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsId.java index 7fd31b25a..a9f0f65eb 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsId.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsId.java @@ -48,7 +48,7 @@ public DefaultNutsId(String groupId, String artifactId, NutsVersion version, Str this.session = session; this.groupId = NutsUtilStrings.trimToNull(groupId); this.artifactId = NutsUtilStrings.trimToNull(artifactId); - this.version = version == null ? this.session.version().parser().parse("") : version; + this.version = version == null ? NutsVersion.of("",session) : version; String c0 = NutsUtilStrings.trimToNull(classifier); String c1 = null; if(properties!=null) { @@ -82,7 +82,7 @@ public DefaultNutsId(String groupId, String artifactId, NutsVersion version, Str @Override public NutsFormat formatter() { - return session.id().formatter().setValue(this); + return NutsIdFormat.of(session).setValue(this); } @Override @@ -257,7 +257,7 @@ public String getPackaging() { @Override public NutsEnvCondition getCondition() { - NutsEnvConditionBuilder c = session.descriptor().envConditionBuilder(); + NutsEnvConditionBuilder c = NutsEnvConditionBuilder.of(session); Map properties = getProperties(); c.setOs( Arrays.stream( @@ -438,12 +438,12 @@ public NutsDependency toDependency() { } List a=new ArrayList<>(); for (String s : exc.split("[;,]")) { - NutsId n = session.id().parser().parse(s); + NutsId n = NutsId.of(s,session); if(n!=null){ a.add(n); } } - return session.dependency().builder() + return NutsDependencyBuilder.of(session) .setRepository(getRepository()) .setArtifactId(getArtifactId()) .setGroupId(getGroupId()) diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsIdBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsIdBuilder.java index 78ac26216..0d27a557f 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsIdBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsIdBuilder.java @@ -30,6 +30,7 @@ import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; import net.thevpc.nuts.runtime.bundles.parsers.QueryStringParser; import net.thevpc.nuts.runtime.core.util.CoreStringUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.util.LinkedHashMap; import java.util.Map; @@ -85,12 +86,12 @@ public class DefaultNutsIdBuilder implements NutsIdBuilder { public DefaultNutsIdBuilder(NutsSession session) { this.session=session; - this.condition=session.descriptor().envConditionBuilder(); + this.condition=NutsEnvConditionBuilder.of(session); } public DefaultNutsIdBuilder(NutsId id,NutsSession session) { this.session=session; - this.condition=session.descriptor().envConditionBuilder(); + this.condition=NutsEnvConditionBuilder.of(session); setGroupId(id.getGroupId()); setArtifactId(id.getArtifactId()); setVersion(id.getVersion()); @@ -100,10 +101,10 @@ public DefaultNutsIdBuilder(NutsId id,NutsSession session) { public DefaultNutsIdBuilder(String groupId, String artifactId, NutsVersion version, String classifier,String propertiesQuery,NutsSession session) { this.session=session; - this.condition=session.descriptor().envConditionBuilder(); + this.condition=NutsEnvConditionBuilder.of(session); this.groupId = NutsUtilStrings.trimToNull(groupId); this.artifactId = NutsUtilStrings.trimToNull(artifactId); - this.version = version == null ? session.version().parser().parse("") : version; + this.version = version == null ? NutsVersion.of("",session) : version; String c0 = NutsUtilStrings.trimToNull(classifier); String c1 = null; @@ -168,13 +169,13 @@ public NutsIdBuilder setRepository(String value) { @Override public NutsIdBuilder setVersion(NutsVersion value) { - this.version = value == null ? session.version().parser().parse("") : value; + this.version = value == null ? NutsVersion.of("",session) : value; return this; } @Override public NutsIdBuilder setVersion(String value) { - this.version = session.version().parser().parse(value); + this.version = NutsVersion.of(value,session); return this; } @@ -262,8 +263,12 @@ public NutsIdBuilder setCondition(NutsEnvCondition c) { @Override public NutsEnvConditionBuilder getCondition() { - return session.descriptor().envConditionBuilder() + return NutsEnvConditionBuilder.of(session) .setOs(CoreStringUtils.parseAndTrimToDistinctArray(getProperties().get(NutsConstants.IdProperties.OS))) + .setArch(CoreStringUtils.parseAndTrimToDistinctArray(getProperties().get(NutsConstants.IdProperties.ARCH))) + .setOsDist(CoreStringUtils.parseAndTrimToDistinctArray(getProperties().get(NutsConstants.IdProperties.OS_DIST))) + .setPlatform(CoreStringUtils.parseAndTrimToDistinctArray(getProperties().get(NutsConstants.IdProperties.PLATFORM))) + .setDesktopEnvironment(CoreStringUtils.parseAndTrimToDistinctArray(getProperties().get(NutsConstants.IdProperties.DESKTOP_ENVIRONMENT))) ; } @@ -522,4 +527,8 @@ public NutsId build() { ); } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsVersion.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsVersion.java index 8425c1bbb..df2c86943 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsVersion.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/model/DefaultNutsVersion.java @@ -73,7 +73,7 @@ public boolean isBlank() { @Override public NutsFormat formatter() { - return session.version().formatter().setVersion(this); + return NutsVersionFormat.of(session).setVersion(this); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsDependencyParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsDependencyParser.java index 66dab4bb7..8988e3bdc 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsDependencyParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsDependencyParser.java @@ -6,31 +6,33 @@ import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; + import net.thevpc.nuts.runtime.bundles.parsers.StringMapParser; +import net.thevpc.nuts.spi.NutsSupportLevelContext; public class DefaultNutsDependencyParser implements NutsDependencyParser { - private static final StringMapParser QPARSER = new StringMapParser("=","&"); - private NutsSession session; - private boolean lenient=false; public static final Pattern DEPENDENCY_NUTS_DESCRIPTOR_PATTERN = Pattern.compile("^(?[a-zA-Z0-9_.${}-]+)(:(?[a-zA-Z0-9_.${}-]+))?(#(?[^?]+))?(\\?(?.+))?$"); + private static final StringMapParser QPARSER = new StringMapParser("=", "&"); + private final NutsSession session; + private boolean lenient = false; public DefaultNutsDependencyParser(NutsSession session) { this.session = session; } @Override - public NutsDependencyParser setLenient(boolean lenient) { - this.lenient=lenient; - return this; + public boolean isLenient() { + return lenient; } @Override - public boolean isLenient() { - return lenient; + public NutsDependencyParser setLenient(boolean lenient) { + this.lenient = lenient; + return this; } @Override - public NutsDependency parseDependency(String dependency) { + public NutsDependency parse(String dependency) { if (dependency == null) { return null; } @@ -45,7 +47,7 @@ public NutsDependency parseDependency(String dependency) { name = group; group = null; } - return session.dependency().builder() + return NutsDependencyBuilder.of(session) .setGroupId(group) .setArtifactId(name) .setVersion(version) @@ -59,10 +61,7 @@ public NutsDependency parseDependency(String dependency) { } @Override - public boolean parseOptional(String optional) { - if(NutsBlankable.isBlank(optional)){ - return false; - } - return "true".equals(optional.trim()); + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsDescriptorParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsDescriptorParser.java index b0c901c7f..a6e5f6b57 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsDescriptorParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsDescriptorParser.java @@ -7,6 +7,7 @@ import net.thevpc.nuts.runtime.core.util.CoreStringUtils; import net.thevpc.nuts.runtime.standalone.bridges.maven.MavenUtils; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.*; import java.net.URL; @@ -24,14 +25,15 @@ public class DefaultNutsDescriptorParser implements NutsDescriptorParser { private NutsDescriptorStyle descriptorStyle; private String format; - public DefaultNutsDescriptorParser(NutsWorkspace ws) { - this.ws = ws; + public DefaultNutsDescriptorParser(NutsSession session) { + this.session = session; + this.ws = session.getWorkspace(); } @Override public NutsDescriptor parse(URL url) { checkSession(); - return parse(getSession().io().path(url)); + return parse(NutsPath.of(url, getSession())); } @Override @@ -42,7 +44,7 @@ public NutsDescriptor parse(byte[] bytes) { @Override public NutsDescriptor parse(Path path) { checkSession(); - return parse(getSession().io().path(path)); + return parse(NutsPath.of(path, getSession())); } @Override @@ -126,14 +128,14 @@ private void checkSession() { } private NutsDescriptor parse(InputStream in, boolean closeStream) { - if(isLenient()){ - try{ - return parseNonLenient(in,closeStream); - }catch (Exception ex){ + if (isLenient()) { + try { + return parseNonLenient(in, closeStream); + } catch (Exception ex) { return null; } } - return parseNonLenient(in,closeStream); + return parseNonLenient(in, closeStream); } private NutsDescriptor parseNonLenient(InputStream in, boolean closeStream) { @@ -151,7 +153,7 @@ private NutsDescriptor parseNonLenient(InputStream in, boolean closeStream) { try { in.close(); } catch (IOException ex) { - throw new NutsIOException(getSession(),ex); + throw new NutsIOException(getSession(), ex); } } } @@ -159,15 +161,15 @@ private NutsDescriptor parseNonLenient(InputStream in, boolean closeStream) { case NUTS: { try { Reader rr = new InputStreamReader(in); - return getSession().elem() + return NutsElements.of(getSession()) .setSession(session) - .setContentType(NutsContentType.JSON).parse(rr, NutsDescriptor.class); + .json().parse(rr, NutsDescriptor.class); } finally { if (closeStream) { try { in.close(); } catch (IOException ex) { - throw new NutsIOException(getSession(),ex); + throw new NutsIOException(getSession(), ex); } } } @@ -177,9 +179,11 @@ private NutsDescriptor parseNonLenient(InputStream in, boolean closeStream) { try { Manifest manifest = new Manifest(in); Attributes attrs = manifest.getMainAttributes(); - String groupAndArtifact = null; + String automaticModuleName = null; String mainVersion = null; String mainClass = null; + String implVendorId = null; + String implVendorTitle = null; Set deps = new LinkedHashSet<>(); NutsId explicitId = null; Map all = new HashMap<>(); @@ -189,13 +193,19 @@ private NutsDescriptor parseNonLenient(InputStream in, boolean closeStream) { mainClass = (NutsUtilStrings.trimToNull(attrs.getValue(attrName))); } if ("Automatic-Module-Name".equals(attrName.toString())) { - groupAndArtifact = NutsUtilStrings.trimToNull(attrs.getValue(attrName)); + automaticModuleName = NutsUtilStrings.trimToNull(attrs.getValue(attrName)); } if ("Implementation-Version".equals(attrName.toString())) { mainVersion = NutsUtilStrings.trimToNull(attrs.getValue(attrName)); } + if ("Implementation-Vendor-Id".equals(attrName.toString())) { + implVendorId = NutsUtilStrings.trimToNull(attrs.getValue(attrName)); + } + if ("Implementation-Vendor-Title".equals(attrName.toString())) { + implVendorTitle = NutsUtilStrings.trimToNull(attrs.getValue(attrName)); + } if ("Nuts-Id".equals(attrName.toString())) { - explicitId = getSession().id().parser().setLenient(true).parse(NutsUtilStrings.trimToNull(attrs.getValue(attrName))); + explicitId = NutsIdParser.of(getSession()).setLenient(true).parse(NutsUtilStrings.trimToNull(attrs.getValue(attrName))); } if ("Nuts-Dependencies".equals(attrName.toString())) { String nutsDependencies = NutsUtilStrings.trimToNull(attrs.getValue(attrName)); @@ -203,45 +213,52 @@ private NutsDescriptor parseNonLenient(InputStream in, boolean closeStream) { Arrays.stream(nutsDependencies.split(";")) .map(String::trim) .filter(x -> x.length() > 0) - .map(getSession().dependency().parser().setLenient(true) - ::parseDependency) + .map(NutsDependencyParser.of(session).setLenient(true) + ::parse) .filter(Objects::nonNull) .collect(Collectors.toCollection(LinkedHashSet::new)); } all.put(attrName.toString(), NutsUtilStrings.trimToNull(attrs.getValue(attrName))); } if (explicitId == null) { - if (groupAndArtifact == null) { + if (automaticModuleName == null && implVendorId == null) { if (!NutsBlankable.isBlank(mainClass)) { - groupAndArtifact = CorePlatformUtils.getPackageName(mainClass); + automaticModuleName = CorePlatformUtils.getPackageName(mainClass); } + } else if (automaticModuleName == null && implVendorId != null) { + automaticModuleName = implVendorId; } - if (groupAndArtifact != null + if (automaticModuleName != null || mainVersion != null || !deps.isEmpty() ) { - String groupId = groupAndArtifact == null ? "" : CorePlatformUtils.getPackageName(groupAndArtifact); - String artifactId = groupAndArtifact == null ? "" : CorePlatformUtils.getSimpleClassName(groupAndArtifact); - explicitId = ws.id().builder().setGroupId(groupId).setArtifactId(artifactId) + String groupId = automaticModuleName == null ? "" : CorePlatformUtils.getPackageName(automaticModuleName); + String artifactId = automaticModuleName == null ? "" : CorePlatformUtils.getSimpleClassName(automaticModuleName); + explicitId = NutsIdBuilder.of(session).setGroupId(groupId).setArtifactId(artifactId) .setVersion( NutsBlankable.isBlank(mainVersion) ? "1.0" : mainVersion.trim() ).build(); } } if (explicitId != null || !deps.isEmpty()) { - return getSession().descriptor().descriptorBuilder() + String nutsName = NutsUtilStrings.trimToNull(all.get("Nuts-Name")); + if(nutsName==null){ + nutsName=implVendorTitle; + } + return NutsDescriptorBuilder.of(getSession()) .setId(explicitId) + .setName(nutsName) .addFlag(NutsBlankable.isBlank(mainClass) ? NutsDescriptorFlag.EXEC : null) .addFlags( Arrays.stream(NutsUtilStrings.trim( - all.get("Nuts-Flags") - ).split("; ,")) + all.get("Nuts-Flags") + ).split("; ,")) .map(NutsDescriptorFlag::parseLenient) .filter(Objects::nonNull) .toArray(NutsDescriptorFlag[]::new) ) .setPackaging(CoreStringUtils.coalesce( - NutsUtilStrings.trimToNull(all.get("Nuts-Flags")), + NutsUtilStrings.trimToNull(all.get("Nuts-Packaging")), "jar" )) .setCategories( @@ -260,20 +277,20 @@ private NutsDescriptor parseNonLenient(InputStream in, boolean closeStream) { .filter(Objects::nonNull) .collect(Collectors.toList()) ) - .setName(NutsUtilStrings.trimToNull(all.get("Nuts-Name"))) + .setName(nutsName) .setDescription(NutsUtilStrings.trimToNull(all.get("Nuts-Description"))) .setGenericName(NutsUtilStrings.trimToNull(all.get("Nuts-Generic-Name"))) .setProperties(all.entrySet().stream() - .filter(x->x.getKey().startsWith("Nuts-Property-")) - .map(x-> new DefaultNutsDescriptorPropertyBuilder(getSession()) - .setName(x.getKey().substring("Nuts-Property-".length())) - .setValue(x.getValue()) - //.setCondition() - .build()) - .toArray(NutsDescriptorProperty[]::new)) + .filter(x -> x.getKey().startsWith("Nuts-Property-")) + .map(x -> new DefaultNutsDescriptorPropertyBuilder(getSession()) + .setName(x.getKey().substring("Nuts-Property-".length())) + .setValue(x.getValue()) + //.setCondition() + .build()) + .toArray(NutsDescriptorProperty[]::new)) //.setCondition() .setExecutor(new DefaultNutsArtifactCall( - getSession().id().parser().parse("java"), + NutsId.of("java", getSession()), //new String[]{"-jar"} NutsBlankable.isBlank(mainClass) ? new String[0] : new String[]{ @@ -283,7 +300,7 @@ private NutsDescriptor parseNonLenient(InputStream in, boolean closeStream) { .setDependencies(deps.toArray(new NutsDependency[0])) .build(); } - throw new NutsParseException(getSession(), NutsMessage.cstyle("unable to parse Descriptor for Manifest from %s",in)); + throw new NutsParseException(getSession(), NutsMessage.cstyle("unable to parse Descriptor for Manifest from %s", in)); } catch (IOException ex) { throw new NutsIOException(getSession(), ex); } @@ -306,4 +323,9 @@ private NutsDescriptor parseNonLenient(InputStream in, boolean closeStream) { public NutsWorkspace getWorkspace() { return ws; } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsIdParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsIdParser.java index 68fb2fbce..3f1ed4ea9 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsIdParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsIdParser.java @@ -1,6 +1,7 @@ package net.thevpc.nuts.runtime.core.parser; import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -53,7 +54,7 @@ public NutsId parse(String nutsId) { } Matcher m = NUTS_ID_PATTERN.matcher(nutsId); if (m.find()) { - NutsIdBuilder builder = session.id().builder(); + NutsIdBuilder builder = NutsIdBuilder.of(session); String group = m.group("group"); String artifact = m.group("artifact"); builder.setArtifactId(artifact); @@ -73,4 +74,8 @@ public NutsId parse(String nutsId) { return null; } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsVersionParser.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsVersionParser.java index 5f403df2a..c2620f41c 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsVersionParser.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/parser/DefaultNutsVersionParser.java @@ -2,6 +2,7 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.model.DefaultNutsVersion; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.util.regex.Pattern; @@ -74,4 +75,9 @@ public NutsVersion parse(String version) { } throw new NutsParseException(session, NutsMessage.cstyle("invalid version format : %s", version)); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/DefaultNutsRepositoryManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/DefaultNutsRepositoryManager.java index 2a2ee7749..c09e7eb05 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/DefaultNutsRepositoryManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/DefaultNutsRepositoryManager.java @@ -26,8 +26,8 @@ public NutsRepositoryManager setSession(NutsSession session) { } @Override - public NutsRepositoryFilterManager filter() { - return model.getWorkspace().filters().repository().setSession(getSession()); + public NutsRepositoryFilters filter() { + return NutsRepositoryFilters.of(getSession()); } private NutsRepository toSessionAwareRepo(NutsRepository x){ diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/DefaultNutsRepositoryModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/DefaultNutsRepositoryModel.java index 104c376b0..e0e2ce361 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/DefaultNutsRepositoryModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/DefaultNutsRepositoryModel.java @@ -30,7 +30,7 @@ public class DefaultNutsRepositoryModel { private final NutsRepositoryRegistryHelper repositoryRegistryHelper; public NutsLogger LOG; - private NutsWorkspace workspace; + private final NutsWorkspace workspace; public DefaultNutsRepositoryModel(NutsWorkspace workspace) { this.workspace = workspace; @@ -43,15 +43,11 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsRepositoryModel.class); + LOG = NutsLogger.of(DefaultNutsRepositoryModel.class,session); } return LOG; } - public NutsRepositoryFilterManager filter() { - return getWorkspace().filters().repository(); - } - public NutsRepository[] getRepositories(NutsSession session) { return repositoryRegistryHelper.getRepositories(); } @@ -203,8 +199,9 @@ public NutsRepository createRepository(NutsAddRepositoryOptions options, Path ro if (rootFolder == null) { if (parentRepository == null) { NutsWorkspaceConfigManagerExt cc = NutsWorkspaceConfigManagerExt.of(session.config()); - rootFolder = options.isTemporary() ? Paths.get(cc.getModel().getTempRepositoriesRoot(session)) - : Paths.get(cc.getModel().getRepositoriesRoot(session)); + rootFolder = options.isTemporary() ? + cc.getModel().getTempRepositoriesRoot(session).toFile() + : cc.getModel().getRepositoriesRoot(session).toFile(); } else { NutsRepositoryConfigManagerExt cc = NutsRepositoryConfigManagerExt.of(parentRepository.config()); rootFolder = options.isTemporary() ? cc.getModel().getTempMirrorsRoot(session) @@ -245,7 +242,7 @@ public NutsRepository createRepository(NutsAddRepositoryOptions options, Path ro options.setEnabled(true); } else if (conf == null) { options.setLocation(CoreIOUtils.resolveRepositoryPath(options, rootFolder, session)); - conf = loadRepository(Paths.get(options.getLocation(), NutsConstants.Files.REPOSITORY_CONFIG_FILE_NAME), options.getName(),session); + conf = loadRepository(Paths.get(options.getLocation(), NutsConstants.Files.REPOSITORY_CONFIG_FILE_NAME), options.getName(), session); if (conf == null) { if (options.isFailSafe()) { return null; @@ -281,14 +278,14 @@ public NutsRepository createRepository(NutsAddRepositoryOptions options, Path ro if (NutsBlankable.isBlank(conf.getType()) && NutsBlankable.isBlank(conf.getLocation()) && !NutsBlankable.isBlank(options.getLocation()) - && session.io().path(options.getLocation()).isFile() + && NutsPath.of(options.getLocation(), session).isFile() ) { conf.setType("nuts"); conf.setLocation(options.getLocation()); } NutsRepositoryFactoryComponent factory_ = session.extensions() .setSession(session) - .createSupported(NutsRepositoryFactoryComponent.class, conf); + .createSupported(NutsRepositoryFactoryComponent.class, false, conf); if (factory_ != null) { NutsRepository r = factory_.create(options, session, parentRepository); if (r != null) { @@ -338,7 +335,8 @@ public NutsRepositoryConfig loadRepository(Path file, String name, NutsSession s throw new UncheckedIOException(ex); } try { - Map a_config0 = session.elem().setContentType(NutsContentType.JSON).parse(bytes, Map.class); + NutsElements elem = NutsElements.of(session); + Map a_config0 = elem.json().parse(bytes, Map.class); String version = (String) a_config0.get("configVersion"); if (version == null) { version = session.getWorkspace().getApiVersion().toString(); @@ -347,7 +345,7 @@ public NutsRepositoryConfig loadRepository(Path file, String name, NutsSession s if (buildNumber < 506) { } - conf = session.elem().setSession(session).setContentType(NutsContentType.JSON).parse(file, NutsRepositoryConfig.class); + conf = elem.json().parse(file, NutsRepositoryConfig.class); } catch (RuntimeException ex) { if (session.boot().getBootOptions().isRecover()) { onLoadRepositoryError(file, name, null, ex, session); @@ -376,9 +374,9 @@ private void onLoadRepositoryError(Path file, String name, String uuid, Throwabl Path logError = Paths.get(session.locations().getStoreLocation(getWorkspace().getApiId(), NutsStoreLocation.LOG)) .resolve("invalid-config"); try { - CoreIOUtils.mkdirs(logError,session); + CoreIOUtils.mkdirs(logError, session); } catch (Exception ex1) { - throw new UncheckedIOException("unable to log repository error while loading config file " + file.toString() + " : " + ex1.toString(), new IOException(ex)); + throw new UncheckedIOException("unable to log repository error while loading config file " + file.toString() + " : " + ex1, new IOException(ex)); } Path newfile = logError.resolve(fileName + ".json"); LOG.with().session(session).level(Level.SEVERE).verb(NutsLogVerb.FAIL) @@ -386,17 +384,17 @@ private void onLoadRepositoryError(Path file, String name, String uuid, Throwabl try { Files.move(file, newfile); } catch (IOException e) { - throw new UncheckedIOException("Unable to load and re-create repository config file " + file.toString() + " : " + e.toString(), new IOException(ex)); + throw new UncheckedIOException("Unable to load and re-create repository config file " + file + " : " + e, new IOException(ex)); } try (PrintStream o = new PrintStream(logError.resolve(fileName + ".error").toFile())) { - o.println("workspace.path:" + session.locations().getWorkspaceLocation()); - o.println("repository.path:" + file); - o.println("workspace.options:" + wboot.getBootOptions().formatter().setCompact(false).setRuntime(true).setInit(true).setExported(true).getBootCommandLine()); + o.printf("workspace.path:%s%n", session.locations().getWorkspaceLocation()); + o.printf("repository.path:%s%n", file); + o.printf("workspace.options:%s%n", wboot.getBootOptions().formatter().setCompact(false).setRuntime(true).setInit(true).setExported(true).getBootCommandLine()); for (NutsStoreLocation location : NutsStoreLocation.values()) { - o.println("location." + location.id() + ":" + session.locations().getStoreLocation(location)); + o.printf("location." + location.id() + ":%s%n", session.locations().getStoreLocation(location)); } - o.println("java.class.path:" + System.getProperty("java.class.path")); + o.printf("java.class.path:%s%n", System.getProperty("java.class.path")); o.println(); ex.printStackTrace(o); } catch (Exception ex2) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/NutsRepositoryUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/NutsRepositoryUtils.java index ad5736be7..b0e527554 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/NutsRepositoryUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/repos/NutsRepositoryUtils.java @@ -91,7 +91,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(NutsRepositoryUtils.class); + LOG = NutsLogger.of(NutsRepositoryUtils.class,session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/sessionaware/NutsWorkspaceSessionAwareImpl.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/sessionaware/NutsWorkspaceSessionAwareImpl.java index 141bcc3c5..6768a181f 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/sessionaware/NutsWorkspaceSessionAwareImpl.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/sessionaware/NutsWorkspaceSessionAwareImpl.java @@ -25,6 +25,7 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; +import net.thevpc.nuts.runtime.core.NutsWorkspaceModel; import net.thevpc.nuts.runtime.core.commands.ws.NutsExecutionContextBuilder; import net.thevpc.nuts.runtime.core.repos.NutsInstalledRepository; import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceEnvManager; @@ -37,7 +38,7 @@ public class NutsWorkspaceSessionAwareImpl implements NutsWorkspace, NutsWorkspaceExt { private final NutsSession session; - private NutsWorkspace ws; + private final NutsWorkspace ws; public NutsWorkspaceSessionAwareImpl(NutsSession session, NutsWorkspace ws) { if (ws instanceof NutsWorkspaceSessionAwareImpl) { @@ -87,6 +88,11 @@ public String getLocation() { // return ws().getCompanionIds(session); // } + @Override + public NutsSession createSession() { + return ws().createSession(); + } + @Override public NutsSearchCommand search() { return ws().search().setSession(getSession()); @@ -137,11 +143,6 @@ public NutsUpdateStatisticsCommand updateStatistics() { return ws().updateStatistics().setSession(getSession()); } - @Override - public NutsWorkspaceAppsManager apps() { - return ws().apps().setSession(getSession()); - } - @Override public NutsWorkspaceExtensionManager extensions() { return ws().extensions().setSession(getSession()); @@ -162,71 +163,21 @@ public NutsWorkspaceSecurityManager security() { return ws().security().setSession(getSession()); } - @Override - public NutsFilterManager filters() { - return ws().filters().setSession(getSession()); - } - - @Override - public NutsIOManager io() { - return ws().io().setSession(getSession()); - } - - @Override - public NutsLogManager log() { - return ws().log().setSession(getSession()); - } - @Override public NutsWorkspaceEventManager events() { return ws().events().setSession(getSession()); } - @Override - public NutsCommandLineManager commandLine() { - return ws().commandLine().setSession(getSession()); - } - - @Override - public NutsIdManager id() { - return ws().id().setSession(getSession()); - } - - @Override - public NutsVersionManager version() { - return ws().version().setSession(getSession()); - } - @Override public NutsInfoFormat info() { return ws().info().setSession(getSession()); } - @Override - public NutsDescriptorManager descriptor() { - return ws().descriptor().setSession(getSession()); - } - - @Override - public NutsDependencyManager dependency() { - return ws().dependency().setSession(getSession()); - } - @Override public NutsFormatManager formats() { return ws().formats().setSession(getSession()); } - @Override - public NutsConcurrentManager concurrent() { - return ws().concurrent().setSession(getSession()); - } - - @Override - public NutsUtilManager util() { - return ws.util().setSession(getSession()); - } - @Override public NutsImportManager imports() { return ws().imports().setSession(getSession()); @@ -248,30 +199,11 @@ public NutsWorkspaceEnvManager env() { return new DefaultNutsWorkspaceEnvManager(e.getModel()).setSession(getSession()); } - @Override - public NutsSession createSession() { - return ws().createSession(); - } - @Override public NutsBootManager boot() { return ws.boot().setSession(session); } - @Override - public NutsTerminalManager term() { - return ws.term().setSession(session); - } - - @Override - public NutsTextManager text() { - return ws.text().setSession(getSession()); - } - - @Override - public NutsElementFormat elem() { - return ws.elem().setSession(getSession()); - } @Override public int getSupportLevel(NutsSupportLevelContext context) { @@ -371,6 +303,11 @@ public NutsSession defaultSession() { return ((NutsWorkspaceExt) ws).defaultSession(); } + @Override + public NutsWorkspaceModel getModel() { + return ((NutsWorkspaceExt) ws).getModel(); + } + @Override public String toString() { return ws.toString(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/shell/AbstractWinNutsShellHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/shell/AbstractWinNutsShellHelper.java index b93392313..13d885626 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/shell/AbstractWinNutsShellHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/shell/AbstractWinNutsShellHelper.java @@ -8,6 +8,9 @@ import java.util.regex.Pattern; public abstract class AbstractWinNutsShellHelper implements NutsShellHelper{ + public AbstractWinNutsShellHelper() { + } + public String newlineString() { return "\r\n"; } @@ -156,7 +159,7 @@ public String escapeArgument(String arg, NutsCommandLineShellOptions options) { options=new NutsCommandLineShellOptions(); } if(options.getSession()==null){ - throw new IllegalArgumentException("missing session"); + throw new NutsMissingSessionException(); } NutsCommandLineFormatStrategy s = options.getFormatStrategy(); if(s==null|| s==NutsCommandLineFormatStrategy.DEFAULT){ diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/shell/ShNutsShellHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/shell/ShNutsShellHelper.java index 4ac5337ff..250578702 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/shell/ShNutsShellHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/shell/ShNutsShellHelper.java @@ -274,7 +274,7 @@ public String escapeArgument(String arg, NutsCommandLineShellOptions options) { options=new NutsCommandLineShellOptions(); } if(options.getSession()==null){ - throw new IllegalArgumentException("missing session"); + throw new NutsMissingSessionException(); } NutsCommandLineFormatStrategy s = options.getFormatStrategy(); if(s==null|| s==NutsCommandLineFormatStrategy.DEFAULT){ diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/AbstractSystemTerminalAdapter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/AbstractSystemTerminalAdapter.java index 5f21e58b7..d72088fae 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/AbstractSystemTerminalAdapter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/AbstractSystemTerminalAdapter.java @@ -146,7 +146,7 @@ public NutsSystemTerminal printProgress(float progress, NutsMessage message,Nuts getProgressBar(session).printProgress( Float.isNaN(progress) ? -1 : (int) (progress * 100), - session.text().toText(message).toString(), + NutsTexts.of(session).toText(message).toString(), err() ); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSessionTerminalFromSession.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSessionTerminalFromSession.java index 5c513f28b..88733843c 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSessionTerminalFromSession.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSessionTerminalFromSession.java @@ -4,12 +4,13 @@ import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; import net.thevpc.nuts.runtime.standalone.io.DefaultNutsQuestion; import net.thevpc.nuts.runtime.standalone.io.progress.CProgressBar; -import net.thevpc.nuts.spi.NutsPrototype; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import java.io.*; import java.util.Scanner; -@NutsPrototype +@NutsComponentScope(NutsComponentScopeType.PROTOTYPE) public class DefaultNutsSessionTerminalFromSession extends AbstractNutsSessionTerminal { protected NutsWorkspace ws; @@ -69,7 +70,7 @@ public String readLine(NutsPrintStream out, NutsMessage message, NutsSession ses out = out(); } if (out == null) { - out = session.io().stdout(); + out = NutsPrintStreams.of(session).stdout(); } if (this.in == null && parent != null) { if (this.out == null) { @@ -96,7 +97,7 @@ public char[] readPassword(NutsPrintStream out, NutsMessage message, NutsSession out = out(); } if (out == null) { - out = session.io().stdout(); + out = NutsPrintStreams.of(session).stdout(); } if (this.in == null && parent != null) { @@ -111,12 +112,12 @@ public char[] readPassword(NutsPrintStream out, NutsMessage message, NutsSession Console cons = null; char[] passwd = null; if (in == null) { - in = session.io().stdin(); + in = NutsInputStreams.of(session).stdin(); } if (( - in == session.io().stdin() + in == NutsInputStreams.of(session).stdin() ) && ((cons = System.console()) != null)) { - String txt = session.text().toText(message).toString(); + String txt = NutsTexts.of(session).toText(message).toString(); if ((passwd = cons.readPassword("%s", txt)) != null) { return passwd; } else { @@ -240,7 +241,7 @@ public NutsSessionTerminal printProgress(float progress, NutsMessage message) { getProgressBar().printProgress( Float.isNaN(progress) ? -1 : (int) (progress * 100), - session.text().toText(message).toString(), + NutsTexts.of(session).toText(message).toString(), err() ); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSessionTerminalFromSystem.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSessionTerminalFromSystem.java index 57d436351..f4ab78617 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSessionTerminalFromSystem.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSessionTerminalFromSystem.java @@ -69,7 +69,7 @@ public String readLine(NutsPrintStream out, NutsMessage message, NutsSession ses out = out(); } if (out == null) { - out = session.io().stdout(); + out = NutsPrintStreams.of(session).stdout(); } if (this.in == null && parent != null) { if (this.out == null) { @@ -96,7 +96,7 @@ public char[] readPassword(NutsPrintStream out, NutsMessage message, NutsSession out = out(); } if (out == null) { - out = session.io().stdout(); + out = NutsPrintStreams.of(session).stdout(); } if (this.in == null && parent != null) { @@ -111,12 +111,12 @@ public char[] readPassword(NutsPrintStream out, NutsMessage message, NutsSession Console cons = null; char[] passwd = null; if (in == null) { - in = session.io().stdin(); + in = NutsInputStreams.of(session).stdin(); } if (( - in == session.io().stdin() + in == NutsInputStreams.of(session).stdin() ) && ((cons = System.console()) != null)) { - String txt = session.text().toText(message).toString(); + String txt = NutsTexts.of(session).toText(message).toString(); if ((passwd = cons.readPassword("%s", txt)) != null) { return passwd; } else { @@ -240,7 +240,7 @@ public NutsSessionTerminal printProgress(float progress, NutsMessage message) { getProgressBar().printProgress( Float.isNaN(progress) ? -1 : (int) (progress * 100), - session.text().toText(message).toString(), + NutsTexts.of(session).toText(message).toString(), err() ); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSystemTerminalBase.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSystemTerminalBase.java index c4358f1a4..39f567b9f 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSystemTerminalBase.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSystemTerminalBase.java @@ -1,15 +1,12 @@ package net.thevpc.nuts.runtime.core.terminals; import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsPrototype; -import net.thevpc.nuts.spi.NutsSupportLevelContext; -import net.thevpc.nuts.spi.NutsSystemTerminalBase; -import net.thevpc.nuts.spi.NutsTerminalSpec; +import net.thevpc.nuts.spi.*; import java.io.InputStream; import java.util.Scanner; -@NutsPrototype +@NutsComponentScope(NutsComponentScopeType.PROTOTYPE) public class DefaultNutsSystemTerminalBase implements NutsSystemTerminalBase { private NutsLogger LOG; @@ -28,7 +25,7 @@ public DefaultNutsSystemTerminalBase() { private NutsLogger _LOG() { if (LOG == null && session != null) { - LOG = session.log().of(NutsSystemTerminalBase.class); + LOG = NutsLogger.of(NutsSystemTerminalBase.class,session); } return LOG; } @@ -67,7 +64,7 @@ private NutsLogger _LOG() { // getProgressBar().printProgress( // Float.isNaN(progress)?-1: // (int)(progress*100), -// session.text().toText(NutsMessage.cstyle(prompt,params)).toString(), +// NutsTexts.of(session).toText(NutsMessage.cstyle(prompt,params)).toString(), // getErr() // ); // } @@ -80,7 +77,7 @@ private NutsLogger _LOG() { // getParent().printProgress(prompt, params); // }else{ // getProgressBar().printProgress(-1, -// session.text().toText(NutsMessage.cstyle(prompt,params)).toString(), +// NutsTexts.of(session).toText(NutsMessage.cstyle(prompt,params)).toString(), // getErr() // ); // } @@ -120,9 +117,9 @@ public int getSupportLevel(NutsSupportLevelContext criteria) { terminalMode = NutsTerminalMode.FORMATTED; } } - this.out = session.io().stdout().setMode(terminalMode); - this.err = session.io().stderr().setMode(terminalMode); - this.in = session.io().stdin(); + this.out = NutsPrintStreams.of(session).stdout().setMode(terminalMode); + this.err = NutsPrintStreams.of(session).stderr().setMode(terminalMode); + this.in = NutsInputStreams.of(session).stdin(); this.scanner = new Scanner(this.in); } else { //on uninstall do nothing @@ -137,7 +134,7 @@ public String readLine(NutsPrintStream out, NutsMessage message,NutsSession sess out = getOut(); } if (out == null) { - out = session.io().stdout(); + out = NutsPrintStreams.of(session).stdout(); } if(message!=null) { out.printf("%s", message); @@ -152,7 +149,7 @@ public char[] readPassword(NutsPrintStream out, NutsMessage message,NutsSession out = getOut(); } if (out == null) { - out = session.io().stdout(); + out = NutsPrintStreams.of(session).stdout(); } if(message!=null) { out.printf("%s", message); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSystemTerminalBaseBoot.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSystemTerminalBaseBoot.java index a2eb194b7..2a543cfe3 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSystemTerminalBaseBoot.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/DefaultNutsSystemTerminalBaseBoot.java @@ -2,15 +2,12 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.standalone.boot.DefaultNutsBootModel; -import net.thevpc.nuts.spi.NutsPrototype; -import net.thevpc.nuts.spi.NutsSupportLevelContext; -import net.thevpc.nuts.spi.NutsSystemTerminalBase; -import net.thevpc.nuts.spi.NutsTerminalSpec; +import net.thevpc.nuts.spi.*; import java.io.InputStream; import java.util.Scanner; -@NutsPrototype +@NutsComponentScope(NutsComponentScopeType.PROTOTYPE) public class DefaultNutsSystemTerminalBaseBoot implements NutsSystemTerminalBase { private NutsLogger LOG; @@ -26,7 +23,6 @@ public class DefaultNutsSystemTerminalBaseBoot implements NutsSystemTerminalBase public DefaultNutsSystemTerminalBaseBoot(DefaultNutsBootModel bootModel) { this.bootModel = bootModel; - NutsWorkspaceOptions options = bootModel.getWorkspaceInitInformation().getOptions(); this.session = bootModel.bootSession(); this.workspace = session.getWorkspace(); // NutsTerminalMode terminalMode = options.getTerminalMode(); @@ -50,7 +46,7 @@ public DefaultNutsSystemTerminalBaseBoot(DefaultNutsBootModel bootModel) { private NutsLogger _LOG() { if (LOG == null && session != null) { - LOG = session.log().of(NutsSystemTerminalBase.class); + LOG = NutsLogger.of(NutsSystemTerminalBase.class,session); } return LOG; } @@ -89,7 +85,7 @@ private NutsLogger _LOG() { // getProgressBar().printProgress( // Float.isNaN(progress)?-1: // (int)(progress*100), -// session.text().toText(NutsMessage.cstyle(prompt,params)).toString(), +// NutsTexts.of(session).toText(NutsMessage.cstyle(prompt,params)).toString(), // getErr() // ); // } @@ -102,7 +98,7 @@ private NutsLogger _LOG() { // getParent().printProgress(prompt, params); // }else{ // getProgressBar().printProgress(-1, -// session.text().toText(NutsMessage.cstyle(prompt,params)).toString(), +// NutsTexts.of(session).toText(NutsMessage.cstyle(prompt,params)).toString(), // getErr() // ); // } @@ -173,7 +169,7 @@ public String readLine(NutsPrintStream out, NutsMessage message, NutsSession ses out = getOut(); } if (out == null) { - out = session.io().stdout(); + out = NutsPrintStreams.of(session).stdout(); } if (message != null) { out.printf("%s", message); @@ -188,7 +184,7 @@ public char[] readPassword(NutsPrintStream out, NutsMessage message, NutsSession out = getOut(); } if (out == null) { - out = session.io().stdout(); + out = NutsPrintStreams.of(session).stdout(); } if (message != null) { out.printf("%s", message); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/UnmodifiableSessionTerminal.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/UnmodifiableSessionTerminal.java index d7cff7455..ea3595920 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/UnmodifiableSessionTerminal.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/terminals/UnmodifiableSessionTerminal.java @@ -135,7 +135,7 @@ public NutsSessionTerminal printProgress(float progress, NutsMessage message) { getProgressBar().printProgress( Float.isNaN(progress) ? -1 : (int) (progress * 100), - session.text().toText(message).toString(), + NutsTexts.of(session).toText(message).toString(), err() ); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreCommonUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreCommonUtils.java index 8d2df64a7..c62178cb6 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreCommonUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreCommonUtils.java @@ -40,7 +40,7 @@ public class CoreCommonUtils { public static NutsString stringValueFormatted(Object o, boolean escapeString, NutsSession session) { - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); if (o == null) { return txt.ofBlank(); } @@ -70,7 +70,7 @@ public static NutsString stringValueFormatted(Object o, boolean escapeString, Nu } else if (o instanceof NutsElementEntry) { NutsElementEntry ne = (NutsElementEntry) o; - NutsTextBuilder sb = session.text().builder(); + NutsTextBuilder sb = NutsTexts.of(session).builder(); sb.append(stringValueFormatted(ne.getKey(), escapeString, session)); sb.append("="); if (ne.getValue().type() == NutsElementType.STRING) { @@ -86,7 +86,7 @@ public static NutsString stringValueFormatted(Object o, boolean escapeString, Nu o = sb.toString(); } else if (o instanceof Map.Entry) { Map.Entry ne = (Map.Entry) o; - NutsTextBuilder sb = session.text().builder(); + NutsTextBuilder sb = NutsTexts.of(session).builder(); sb.append(stringValueFormatted(ne.getKey(), escapeString, session)); sb.append("="); if (ne.getValue() instanceof String diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreIOUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreIOUtils.java index 230eb4ab1..2ccd57d6b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreIOUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreIOUtils.java @@ -507,8 +507,7 @@ public static String resolveRepositoryPath(NutsAddRepositoryOptions options, Pat if (goodName.length() < 3) { goodName = goodName + "-repo"; } - loc = session.io().tmp() - .setSession(session) + loc = NutsTmp.of(session) .createTempFolder(goodName + "-").toString(); } else { if (NutsBlankable.isBlank(loc)) { @@ -519,7 +518,9 @@ public static String resolveRepositoryPath(NutsAddRepositoryOptions options, Pat } } } - return session.io().path(loc).builder().setBaseDir(rootFolder.toString()).build().toString(); + return NutsPath.of(loc,session).builder().setBaseDir( + NutsPath.of(rootFolder,session)) + .build().toString(); } public static String trimSlashes(String repositoryIdPath) { @@ -568,8 +569,7 @@ public static NutsDescriptor resolveNutsDescriptorFromFileContent(Path localPath try { desc = parser.parse(ctx); } catch (Exception e) { - session.log().of(CoreIOUtils.class) - .with() + NutsLoggerOp.of(CoreIOUtils.class,session) .level(Level.FINE) .verb(NutsLogVerb.WARNING) .error(e) @@ -577,7 +577,10 @@ public static NutsDescriptor resolveNutsDescriptorFromFileContent(Path localPath //e.printStackTrace(); } if (desc != null) { - return desc; + if(!desc.isBlank()) { + return desc; + } + return checkDescriptor(desc, session); } } } @@ -585,6 +588,59 @@ public static NutsDescriptor resolveNutsDescriptorFromFileContent(Path localPath return null; } + private static NutsDescriptor checkDescriptor(NutsDescriptor nutsDescriptor, NutsSession session) { + NutsId id = nutsDescriptor.getId(); + String groupId = id == null ? null : id.getGroupId(); + String artifactId = id == null ? null : id.getArtifactId(); + NutsVersion version = id == null ? null : id.getVersion(); + if (groupId == null || artifactId == null || NutsBlankable.isBlank(version)) { + switch (session.getConfirm()) { + case ASK: + case ERROR: { + if (groupId == null) { + groupId = session.getTerminal().ask() + .forString(NutsMessage.cstyle("group id")) + .setDefaultValue(groupId) + .setHintMessage(NutsBlankable.isBlank(groupId) ? null : NutsMessage.plain(groupId)) + .getValue(); + } + if (artifactId == null) { + artifactId = session.getTerminal().ask() + .forString(NutsMessage.cstyle("artifact id")) + .setDefaultValue(artifactId) + .setHintMessage(NutsBlankable.isBlank(artifactId) ? null : NutsMessage.plain(artifactId)) + .getValue(); + } + if (NutsBlankable.isBlank(version)) { + String ov = version == null ? null : version.getValue(); + String v = session.getTerminal().ask() + .forString(NutsMessage.cstyle("version")) + .setDefaultValue(ov) + .setHintMessage(NutsBlankable.isBlank(ov) ? null : NutsMessage.plain(ov)) + .getValue(); + version = NutsVersionParser.of(session) + .setAcceptBlank(true) + .setAcceptIntervals(true) + .setLenient(true).parse(v); + } + break; + } + case NO: + case YES: { + //silently return null + } + } + } + if (groupId == null || artifactId == null || NutsBlankable.isBlank(version)) { + throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("invalid descriptor id %s:%s#%s", groupId, artifactId, version)); + } + return nutsDescriptor.builder() + .setId(NutsIdBuilder.of(session).setGroupId(groupId).setArtifactId(artifactId).setVersion(version).build()) + .build() + ; + } + + public static String getPath(NutsId id, String ext, char sep) { StringBuilder sb = new StringBuilder(); sb.append(id.getGroupId().replace('.', sep)); @@ -814,8 +870,8 @@ public static long copy(java.io.InputStream from, OutputStream to, boolean close public static java.io.InputStream monitor(URL from, NutsProgressMonitor monitor, NutsSession session) { return monitor( NutsWorkspaceUtils.of(session).openURL(from), - from, session.text().ofStyled(getURLName(from), NutsTextStyle.path()) - , session.io().path(from).getContentLength(), monitor, session); + from, NutsTexts.of(session).ofStyled(getURLName(from), NutsTextStyle.path()) + , NutsPath.of(from,session).getContentLength(), monitor, session); } public static java.io.InputStream monitor(java.io.InputStream from, Object source, NutsString sourceName, long length, NutsProgressMonitor monitor, NutsSession session) { @@ -827,7 +883,7 @@ public static java.io.InputStream monitor(java.io.InputStream from, Object sourc long length = -1; NutsInputStreamMetadata m = NutsInputStreamMetadata.resolve(from); if (m != null) { - sourceName = session.text().toText(m.getName()); + sourceName = NutsTexts.of(session).toText(m.getName()); length = m.getContentLength(); } return new MonitoredInputStream(from, source, sourceName, length, monitor, session); @@ -856,7 +912,7 @@ public static void delete(NutsSession session, Path file) { } } final int[] deleted = new int[]{0, 0, 0}; - NutsLogger LOG = session == null ? null : session.log().of(CoreIOUtils.class); + NutsLogger LOG = session == null ? null : NutsLogger.of(CoreIOUtils.class,session); try { Files.walkFileTree(file, new FileVisitor() { @Override @@ -1010,7 +1066,7 @@ public static String getURLName(String path) { // name = String.valueOf(source); // } // if (formattedString == null) { -// formattedString = session.text().forPlain(name); +// formattedString = NutsTexts.of(session).forPlain(name); // } // return new ByteArrayInput(name, formattedString, source, typeName, session); // } @@ -1050,7 +1106,7 @@ public static boolean isValidInputStreamSource(Class type) { // } public static NutsTransportConnection getHttpClientFacade(NutsSession session, String url) { NutsTransportComponent best = session.extensions() - .createSupported(NutsTransportComponent.class, url); + .createSupported(NutsTransportComponent.class, false, url); if (best == null) { best = DefaultHttpTransportComponent.INSTANCE; } @@ -1314,7 +1370,7 @@ public static InputStream getCachedUrlWithSHA1(String path, String sourceTypeNam String sha1 = null; try { ByteArrayOutputStream t = new ByteArrayOutputStream(); - session.io().copy() + NutsCp.of(session) .from(path + ".sha1").to(t).run(); sha1 = t.toString().trim(); } catch (NutsIOException ex) { @@ -1340,7 +1396,7 @@ public static InputStream getCachedUrlWithSHA1(String path, String sourceTypeNam if (cachedID != null) { Path p = urlContent.resolve(cachedID); if (Files.exists(p)) { - return session.io().path(p).getInputStream(); + return NutsPath.of(p,session).getInputStream(); } } } @@ -1370,7 +1426,7 @@ public static InputStream getCachedUrlWithSHA1(String path, String sourceTypeNam if (cachedID != null) { Path p = urlContent.resolve(cachedID); if (Files.exists(p)) { - return session.io().path(p).getInputStream(); + return NutsPath.of(p,session).getInputStream(); } } } @@ -1409,12 +1465,12 @@ public static InputStream getCachedUrlWithSHA1(String path, String sourceTypeNam }); return InputStreamMetadataAwareImpl.of(ist, new NutsDefaultInputStreamMetadata( path, - session.text().ofStyled(path, NutsTextStyle.path()), - size,session.io().path(path).getContentType(),sourceTypeName + NutsTexts.of(session).ofStyled(path, NutsTextStyle.path()), + size,NutsPath.of(path,session).getContentType(),sourceTypeName ) ); // session.io().input() -// .setName(session.text().forStyled(path, NutsTextStyle.path())) +// .setName(NutsTexts.of(session).forStyled(path, NutsTextStyle.path())) // .setTypeName(sourceTypeName) // .of(); } catch (IOException ex) { @@ -1534,10 +1590,9 @@ public static Path toPathInputSource(NutsStreamOrPath is, List tempPaths, if (is.isPath() && is.getPath().isFile()) { return is.getPath().toFile(); } - Path temp = session.io().tmp() - .setSession(session) + Path temp = NutsTmp.of(session) .createTempFile(getURLName(is.getName())).toFile(); - NutsIOCopyAction a = session.io().copy().setSafe(false); + NutsCp a = NutsCp.of(session).setSafe(false); if (is.isPath()) { a.from(is.getPath()); } else { @@ -2672,7 +2727,7 @@ public static PathInfo.Status tryWrite(byte[] content, Path out, /*boolean doNot } Files.write(out, content); if (session.isPlainTrace()) { - session.out().resetLine().printf("create file %s%n", session.io().path(out)); + session.out().resetLine().printf("create file %s%n", NutsPath.of(out,session)); } } catch (IOException e) { throw new UncheckedIOException(e); @@ -2684,7 +2739,7 @@ public static PathInfo.Status tryWrite(byte[] content, Path out, /*boolean doNot .resetLine() .setDefaultValue(true).setSession(session) .forBoolean("create %s ?", - session.text().ofStyled( + NutsTexts.of(session).ofStyled( betterPath(out.toString()), NutsTextStyle.path() ) ).getBooleanValue()) { @@ -2694,7 +2749,7 @@ public static PathInfo.Status tryWrite(byte[] content, Path out, /*boolean doNot } Files.write(out, content); if (session.isPlainTrace()) { - session.out().resetLine().printf("create file %s%n", session.io().path(out)); + session.out().resetLine().printf("create file %s%n", NutsPath.of(out,session)); } } catch (IOException e) { throw new UncheckedIOException(e); @@ -2723,7 +2778,7 @@ public static PathInfo.Status tryWrite(byte[] content, Path out, /*boolean doNot throw new UncheckedIOException(e); } if (session.isPlainTrace()) { - session.out().resetLine().printf("update file %s%n", session.io().path(out)); + session.out().resetLine().printf("update file %s%n", NutsPath.of(out,session)); } return PathInfo.Status.OVERRIDDEN; } @@ -2732,7 +2787,7 @@ public static PathInfo.Status tryWrite(byte[] content, Path out, /*boolean doNot .resetLine() .setDefaultValue(true).setSession(session) .forBoolean("override %s ?", - session.text().ofStyled( + NutsTexts.of(session).ofStyled( betterPath(out.toString()), NutsTextStyle.path() ) ).getBooleanValue()) { @@ -2747,7 +2802,7 @@ public static PathInfo.Status tryWrite(byte[] content, Path out, /*boolean doNot throw new UncheckedIOException(e); } if (session.isPlainTrace()) { - session.out().resetLine().printf("update file %s%n", session.io().path(out)); + session.out().resetLine().printf("update file %s%n", NutsPath.of(out,session)); } return PathInfo.Status.OVERRIDDEN; } else { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreNutsDependencyUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreNutsDependencyUtils.java index d8abdb5ca..701be7e92 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreNutsDependencyUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreNutsDependencyUtils.java @@ -36,7 +36,7 @@ public static String normalizeDependencyType(String s1) { } public static NutsDependencyFilter createJavaRunDependencyFilter(NutsSession session) { - NutsDependencyFilterManager d = session.dependency().filter(); + NutsDependencyFilters d = NutsDependencyFilters.of(session); return d .byScope(NutsDependencyScopePattern.RUN) .and(d.byOptional(false)) diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreNutsUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreNutsUtils.java index c4c4117f8..0505235ed 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreNutsUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreNutsUtils.java @@ -188,11 +188,11 @@ public static NutsVersion applyStringProperties(NutsVersion child, Function T simplify(T any) { public static T simplifyFilterOr(NutsSession ws, Class cls, T base, NutsFilter... all) { if (all.length == 0) { - return (T) ws.filters().always(cls); + return NutsFilters.of(ws).always(cls); } if (all.length == 1) { return (T) all[0].simplify(); @@ -245,7 +245,7 @@ public static T simplifyFilterOr(NutsSession ws, Class if (t2 != null) { switch (t2.getFilterOp()) { case TRUE: { - return (T) ws.filters().always(cls); + return NutsFilters.of(ws).always(cls); } case FALSE: { someFalse = true; @@ -264,9 +264,9 @@ public static T simplifyFilterOr(NutsSession ws, Class } if (all2.isEmpty()) { if (someFalse) { - return (T) ws.filters().never(cls); + return NutsFilters.of(ws).never(cls); } - return (T) ws.filters().always(cls); + return NutsFilters.of(ws).always(cls); } if (all2.size() == 1) { return all2.get(0); @@ -274,12 +274,12 @@ public static T simplifyFilterOr(NutsSession ws, Class if (!updates) { return base; } - return (T) ws.filters().any(cls, all2.toArray((T[]) Array.newInstance(cls, 0))); + return NutsFilters.of(ws).any(cls, all2.toArray((T[]) Array.newInstance(cls, 0))); } public static T simplifyFilterAnd(NutsSession ws, Class cls, T base, NutsFilter... all) { if (all.length == 0) { - return (T) ws.filters().always(cls); + return NutsFilters.of(ws).always(cls); } if (all.length == 1) { return (T) all[0].simplify(); @@ -291,7 +291,7 @@ public static T simplifyFilterAnd(NutsSession ws, Class T simplifyFilterAnd(NutsSession ws, Class T simplifyFilterAnd(NutsSession ws, Class T simplifyFilterNone(NutsSession ws, Class cls, T base, NutsFilter... all) { if (all.length == 0) { - return (T) ws.filters().always(cls); + return NutsFilters.of(ws).always(cls); } List all2 = new ArrayList<>(); boolean updates = false; @@ -331,7 +331,7 @@ public static T simplifyFilterNone(NutsSession ws, Class< if (t2 != null) { switch (t2.getFilterOp()) { case TRUE: { - return (T) ws.filters().never(cls); + return NutsFilters.of(ws).never(cls); } case FALSE: { updates = true; @@ -349,12 +349,12 @@ public static T simplifyFilterNone(NutsSession ws, Class< } } if (all2.size() == 0) { - return (T) ws.filters().always(cls); + return NutsFilters.of(ws).always(cls); } if (!updates) { return base; } - return (T) ws.filters().none(cls, all2.toArray((T[]) Array.newInstance(cls, 0))); + return NutsFilters.of(ws).none(cls, all2.toArray((T[]) Array.newInstance(cls, 0))); } public static T[] simplifyAndShrink(Class cls, T... any) { @@ -431,7 +431,7 @@ public static NutsId applyNutsIdInheritance(NutsId child, NutsId parent, NutsSes props.putAll(parentFaceMap); } if (modified) { - return ws.id().builder().setRepository(repository) + return NutsIdBuilder.of(ws).setRepository(repository) .setGroupId(group) .setArtifactId(name) .setVersion(version) @@ -494,7 +494,7 @@ public static Map traceJsonNutsDefinition(NutsSession session, N } if (def.getInstallInformation() != null) { if (def.getInstallInformation().getInstallFolder() != null) { - x.put("install-folder", def.getInstallInformation().getInstallFolder().toString()); + x.put("install-folder", def.getInstallInformation().getInstallFolder()); } x.put("install-status", def.getInstallInformation().getInstallStatus().toString()); x.put("was-installed", def.getInstallInformation().isWasInstalled()); @@ -507,10 +507,9 @@ public static Map traceJsonNutsDefinition(NutsSession session, N x.put("repository-uuid", def.getRepositoryUuid()); } if (def.getDescriptor() != null) { - x.put("descriptor", session.descriptor().formatter().setValue(def.getDescriptor()).format()); - x.put("effective-descriptor", session.descriptor().formatter( - NutsWorkspaceUtils.of(session).getEffectiveDescriptor(def) - ).format()); + x.put("descriptor", def.getDescriptor().formatter().setSession(session).format()); + x.put("effective-descriptor", NutsWorkspaceUtils.of(session).getEffectiveDescriptor(def) + .formatter().setSession(session).format()); } return x; } @@ -673,13 +672,9 @@ public static boolean isValidWorkspaceName(String workspace) { return true; } String workspaceName = workspace.trim(); - if (workspaceName.matches("[^/\\\\]+") + return workspaceName.matches("[^/\\\\]+") && !workspaceName.equals(".") - && !workspaceName.equals("..")) { - return true; - } else { - return false; - } + && !workspaceName.equals(".."); } public static String resolveValidWorkspaceName(String workspace) { @@ -737,7 +732,7 @@ public static boolean acceptClassifier(NutsIdLocation location, String classifie return c0.equals(c1); } - public static NutsString formatLogValue(NutsTextManager text, Object unresolved, Object resolved) { + public static NutsString formatLogValue(NutsTexts text, Object unresolved, Object resolved) { NutsString a = desc(unresolved, text); NutsString b = desc(resolved, text); if (a.equals(b)) { @@ -752,7 +747,7 @@ public static NutsString formatLogValue(NutsTextManager text, Object unresolved, } } - public static NutsString desc(Object s, NutsTextManager text) { + public static NutsString desc(Object s, NutsTexts text) { if (s == null || (s instanceof String && ((String) s).isEmpty())) { return text.ofStyled("", NutsTextStyle.option()); } @@ -767,9 +762,7 @@ public static boolean isUnsupportedFetchModeException(Throwable ex) { if (ex instanceof NutsNotFoundException) { if (ex.getCause() != null) { Throwable ex2 = ex.getCause(); - if (ex2 instanceof NutsFetchModeNotSupportedException) { - return true; - } + return ex2 instanceof NutsFetchModeNotSupportedException; } } return false; @@ -804,10 +797,7 @@ public static boolean acceptProgress(NutsSession session) { if (!session.isPlainOut()) { return false; } - if (session.isBot() || !parseProgressOptions(session).isEnabled()) { - return false; - } - return true; + return !session.isBot() && parseProgressOptions(session).isEnabled(); } public static boolean acceptMonitoring(NutsSession session) { @@ -822,7 +812,7 @@ public static boolean acceptMonitoring(NutsSession session) { Object o = session.getProperty("monitor-allowed"); NutsWorkspace ws = session.getWorkspace(); if (o != null) { - o = session.commandLine().create(String.valueOf(o)).next().getAll().getBoolean(); + o = NutsCommandLine.of(new String[]{String.valueOf(o)}, session).next().getAll().getBoolean(); } boolean monitorable = true; if (o instanceof Boolean) { @@ -941,9 +931,33 @@ public static Map getPropertiesMap(NutsDescriptorProperty[] list return m; } + public static NutsIdType detectIdType(NutsId depId, NutsSession session) { + switch (depId.getShortName()) { + case NutsConstants.Ids.NUTS_API: { + return NutsIdType.API; + } + case NutsConstants.Ids.NUTS_RUNTIME: { + return NutsIdType.RUNTIME; + } + default: { + String rt = session.getWorkspace().getRuntimeId().getShortName(); + if (rt.equals(depId.getShortName())) { + return NutsIdType.RUNTIME; + } else { + for (NutsClassLoaderNode n : session.boot().getBootExtensionClassLoaderNode()) { + if (NutsId.of(n.getId(),session).equalsShortId(depId)) { + return NutsIdType.EXTENSION; + } + } + return NutsIdType.REGULAR; + } + } + } + } + public static class ProgressOptions { - private boolean enabled=true; - private Map vals = new LinkedHashMap<>(); + private boolean enabled = true; + private final Map vals = new LinkedHashMap<>(); public boolean isEnabled() { return enabled; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreStringUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreStringUtils.java index 63ee7fe56..727bd1d3f 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreStringUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/CoreStringUtils.java @@ -80,13 +80,16 @@ public static String escapeReplacementStrings(String s) { return sb.toString(); } + public static String simpleQuote(String text) { + return simpleQuote(text,false,null); + } /** * @param text text * @param compact if true, quotes will not be used unless necessary - * @param entrySeparators entrySeparators + * @param escapedChars escapedChars, can be null * @return quotes */ - public static String simpleQuote(String text, boolean compact, String entrySeparators) { + public static String simpleQuote(String text, boolean compact, String escapedChars) { StringBuilder sb = new StringBuilder(); boolean q = !compact; for (char c : text.toCharArray()) { @@ -113,7 +116,7 @@ public static String simpleQuote(String text, boolean compact, String entrySepar break; } default: { - if (entrySeparators != null && entrySeparators.indexOf(c) >= 0) { + if (escapedChars != null && escapedChars.indexOf(c) >= 0) { q = true; sb.append("\\").append(c); } else { @@ -242,7 +245,7 @@ public static String enforceDoubleQuote(String s) { } public static String enforceDoubleQuote(String s, NutsSession session) { - s = session.text().builder().append(s).toString(); + s = NutsTexts.of(session).builder().append(s).toString(); if (s.isEmpty() || s.contains(" ") || s.contains("\"") || s.contains("'")) { s = "\"" + s + "\""; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/ProcessExecHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/ProcessExecHelper.java index 8ebaf5f13..dae22f236 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/ProcessExecHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/core/util/ProcessExecHelper.java @@ -13,7 +13,6 @@ import java.io.UncheckedIOException; import java.nio.file.Files; import java.nio.file.Path; -import java.nio.file.Paths; import java.util.*; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; @@ -50,18 +49,18 @@ public static ProcessExecHelper ofArgs(String[] args, Map env, P if (!inheritSystemIO) { if (inputFile == null) { in = execTerminal.in(); - if (session.io().setSession(session).isStandardInputStream(in)) { + if (NutsInputStreams.of(session).isStdin(in)) { in = null; } } if (outputFile == null) { out = execTerminal.out(); - if (session.io().setSession(session).isStandardOutputStream(out)) { + if (NutsPrintStreams.of(session).isStdout(out)) { out = null; } } err = execTerminal.err(); - if (session.io().setSession(session).isStandardErrorStream(err)) { + if (NutsPrintStreams.of(session).isStderr(err)) { err = null; } if (out != null) { @@ -91,18 +90,18 @@ public static ProcessExecHelper ofArgs(String[] args, Map env, P } } - NutsLogger _LL = session.log().setSession(session).of(NutsWorkspaceUtils.class); + NutsLogger _LL = NutsLogger.of(NutsWorkspaceUtils.class,session); if (_LL.isLoggable(Level.FINEST)) { _LL.with().level(Level.FINE).verb(NutsLogVerb.START).log( NutsMessage.jstyle("[exec] {0}", - session.text().ofCode("system", + NutsTexts.of(session).ofCode("system", pb.getCommandString() ))); } if (showCommand || CoreBooleanUtils.getSysBoolNutsProperty("show-command", false)) { if (prepareTerminal.out().mode() == NutsTerminalMode.FORMATTED) { - prepareTerminal.out().printf("%s ", session.text().ofStyled("[exec]", NutsTextStyle.primary4())); - prepareTerminal.out().println(session.text().ofCode("system", pb.getCommandString())); + prepareTerminal.out().printf("%s ", NutsTexts.of(session).ofStyled("[exec]", NutsTextStyle.primary4())); + prepareTerminal.out().println(NutsTexts.of(session).ofCode("system", pb.getCommandString())); } else { prepareTerminal.out().print("exec "); prepareTerminal.out().printf("%s%n", pb.getCommandString()); @@ -141,7 +140,7 @@ public static ProcessExecHelper ofDefinition(NutsDefinition nutMainFile, if (map.containsKey("nuts.jar")) { map.put("nuts.cmd", map.get("nuts.java") + " -jar " + map.get("nuts.jar")); } - map.put("nuts.workspace", session.locations().getWorkspaceLocation()); + map.put("nuts.workspace", session.locations().getWorkspaceLocation().toString()); if (installerFile != null) { map.put("nuts.installer", installerFile.toString()); } @@ -193,22 +192,23 @@ public String apply(String skey) { for (String arg : args) { String s = NutsUtilStrings.trim(StringPlaceHolderParser.replaceDollarPlaceHolders(arg, mapper)); if (s.startsWith("<::expand::>")) { - Collections.addAll(args2, session.commandLine().parse(s).toStringArray()); + Collections.addAll(args2, NutsCommandLine.parse(s,session).toStringArray()); } else { args2.add(s); } } args = args2.toArray(new String[0]); - Path path = Paths.get(session.locations().getWorkspaceLocation()).resolve(args[0]).normalize(); + Path wsLocation = session.locations().getWorkspaceLocation().toFile(); + Path path = wsLocation.resolve(args[0]).normalize(); if (Files.exists(path)) { CoreIOUtils.setExecutable(path); } Path pdirectory = null; if (NutsBlankable.isBlank(directory)) { - pdirectory = Paths.get(session.locations().getWorkspaceLocation()); + pdirectory = wsLocation; } else { - pdirectory = Paths.get(session.locations().getWorkspaceLocation()).resolve(directory); + pdirectory = wsLocation.resolve(directory); } return ofArgs(args, envmap, pdirectory, session.getTerminal(), execSession.getTerminal(), showCommand, failFast, sleep, diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/optional/gson/GsonItemSerializeManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/optional/gson/GsonItemSerializeManager.java index 30567fe01..83f4b9d7a 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/optional/gson/GsonItemSerializeManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/optional/gson/GsonItemSerializeManager.java @@ -48,7 +48,7 @@ //import net.thevpc.nuts.runtime.core.format.elem.NutsElementFactoryContext; //import net.thevpc.nuts.runtime.core.format.elem.NutsElementStreamFormat; //import net.thevpc.nuts.NutsElementEntry; -//import net.thevpc.nuts.NutsElementFormat; +//import net.thevpc.nuts.NutsElements; //import net.thevpc.nuts.NutsElementType; //import net.thevpc.nuts.NutsObjectElement; // @@ -70,7 +70,7 @@ // public NutsElement gsonToElement(JsonElement o,NutsElementFactoryContext context) { // JsonElement je = (JsonElement) o; // NutsWorkspace ws = context.getWorkspace(); -// NutsElementFormat element = ws.elem().setSession(context.getSession()); +// NutsElements element = ws.elem().setSession(context.getSession()); // if (je.isJsonNull()) { // return element.forNull(); // } else if (je.isJsonPrimitive()) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/optional/mslink/OptionalMsLinkHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/optional/mslink/OptionalMsLinkHelper.java index 2e5ac524d..866928af1 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/optional/mslink/OptionalMsLinkHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/optional/mslink/OptionalMsLinkHelper.java @@ -1,6 +1,7 @@ package net.thevpc.nuts.runtime.optional.mslink; import net.thevpc.nuts.NutsBlankable; +import net.thevpc.nuts.NutsCommandLine; import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.NutsUtilStrings; import net.thevpc.nuts.runtime.core.util.CoreIOUtils; @@ -49,11 +50,11 @@ public static boolean isSupported() { } public void write() { - String[] cmd = session.commandLine().parse(command).toStringArray(); + String[] cmd = NutsCommandLine.parse(command,session).toStringArray(); mslinks.ShellLink se = mslinks.ShellLink.createLink(cmd[0]) .setWorkingDir(wd) - .setCMDArgs(session.commandLine().create( - Arrays.copyOfRange(cmd, 1, cmd.length) + .setCMDArgs(NutsCommandLine.of( + Arrays.copyOfRange(cmd, 1, cmd.length),session ).toString()); if (NutsBlankable.isBlank(icon)) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsExecCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsExecCommand.java index 61bda3815..469f050bc 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsExecCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsExecCommand.java @@ -16,7 +16,7 @@ protected RemoteNutsWorkspace getWorkspace() { @Override public NutsExecutableInformation which() { - NutsElementFormat e = getSession().elem().setSession(getSession()); + NutsElements e = NutsElements.of(getSession()); return getWorkspace().remoteCall( getWorkspace().createCall("workspace.which", e.forObject() @@ -28,7 +28,7 @@ public NutsExecutableInformation which() { @Override public NutsExecCommand run() { - NutsElementFormat e = getSession().elem(); + NutsElements e = NutsElements.of(getSession()); try { int r = getWorkspace().remoteCall( getWorkspace().createCall("workspace.exec", diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsSearchCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsSearchCommand.java index 8369771c3..10d6d6457 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsSearchCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsSearchCommand.java @@ -32,8 +32,8 @@ public NutsFetchCommand toFetch() { @Override protected Iterator getResultIdIteratorBase(Boolean forceInlineDependencies) { - NutsSession ws = getSession(); - NutsElementFormat e = ws.elem().setSession(getSession()); + NutsSession session = getSession(); + NutsElements e = NutsElements.of(getSession()).setSession(getSession()); NutsObjectElementBuilder eb = e.forObject() .set("execType", getExecType()) .set("defaultVersions", getDefaultVersions()) @@ -47,7 +47,7 @@ protected Iterator getResultIdIteratorBase(Boolean forceInlineDependenci eb.set("idFilter", e.toElement(getIdFilter())); } if (getDescriptorFilter() != null) { - eb.set("descriptorFilter", ws.elem().toElement(getDescriptorFilter())); + eb.set("descriptorFilter", NutsElements.of(getSession()).toElement(getDescriptorFilter())); } if (getInstallStatus() != null) { eb.set("installStatus", e.forString(getInstallStatus().toString())); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsWorkspace.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsWorkspace.java index cf7f15ab7..452895974 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsWorkspace.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/remote/RemoteNutsWorkspace.java @@ -12,7 +12,7 @@ public RemoteNutsWorkspace() { public NutsElement createCall(String commandName, NutsElement body,NutsSession session) { try (NTalkClient cli = new NTalkClient()) { - NutsElementFormat e = session.elem().setContentType(NutsContentType.JSON); + NutsElements e = NutsElements.of(session).json(); NutsObjectElement q = e.forObject() .set("cmd", commandName) .set("body", body).build(); @@ -20,7 +20,7 @@ public NutsElement createCall(String commandName, NutsElement body,NutsSession s String wsURL = session.boot().getBootOptions().getWorkspace(); byte[] result = cli.request("nuts/ws:"+wsURL, json.toString().getBytes()); NutsObjectElement resultObject = e.parse(result, NutsObjectElement.class); - NutsElementFormat prv = session.elem(); + NutsElements prv = NutsElements.of(session); boolean success = resultObject.get(prv.forString("success") ).asPrimitive().getBoolean(); if (success) { @@ -28,13 +28,13 @@ public NutsElement createCall(String commandName, NutsElement body,NutsSession s } else { //TODO mush deserialize exception throw new NutsException(session, NutsMessage.cstyle("unable to call %s", - session.text().ofStyled(commandName,NutsTextStyle.primary1()))); + NutsTexts.of(session).ofStyled(commandName,NutsTextStyle.primary1()))); } } } public NutsElement createCall(String commandName, String callId, NutsElement body,NutsSession session) { - NutsElementFormat e = session.elem(); + NutsElements e = NutsElements.of(session); return e.forObject() .set( "cmd", @@ -94,7 +94,7 @@ public NutsElement createCall(String commandName, String callId, NutsElement bod // } // // @Override -// public NutsFilterManager filters() { +// public NutsFilters filters() { // throw new NutsUnsupportedOperationException(configManager.getWorkspace(), "not yet supported filters"); // } // diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsConcurrentManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsConcurrentManager.java deleted file mode 100644 index 212859791..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsConcurrentManager.java +++ /dev/null @@ -1,42 +0,0 @@ -package net.thevpc.nuts.runtime.standalone; - -import net.thevpc.nuts.NutsConcurrentManager; - -import java.util.concurrent.ExecutorService; -import net.thevpc.nuts.NutsIOLockAction; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; - -public class DefaultNutsConcurrentManager implements NutsConcurrentManager { - - private DefaultNutsConcurrentModel model; - private NutsSession session; - - public DefaultNutsConcurrentManager(DefaultNutsConcurrentModel model) { - this.model = model; - } - - public NutsSession getSession() { - return session; - } - - public NutsConcurrentManager setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(model.getWorkspace(), session); - return this; - } - - protected void checkSession() { - NutsWorkspaceUtils.checkSession(model.getWorkspace(), getSession()); - } - - @Override - public ExecutorService executorService() { - checkSession(); - return model.executorService(getSession()); - } - - public NutsIOLockAction lock() { - return model.lock().setSession(getSession()); - } - -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsConcurrentModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsConcurrentModel.java deleted file mode 100644 index 3f4056286..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsConcurrentModel.java +++ /dev/null @@ -1,46 +0,0 @@ -package net.thevpc.nuts.runtime.standalone; - -import net.thevpc.nuts.NutsWorkspace; -import net.thevpc.nuts.runtime.standalone.io.DefaultNutsIOLockAction; -import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import net.thevpc.nuts.NutsSession; - -public class DefaultNutsConcurrentModel { - private NutsWorkspace workspace; - private ExecutorService executorService; - public DefaultNutsConcurrentModel(NutsWorkspace workspace) { - this.workspace=workspace; - } - - public NutsWorkspace getWorkspace() { - return workspace; - } - - public ExecutorService executorService(NutsSession session) { - if (executorService == null) { - synchronized (this) { - if (executorService == null) { - executorService = session.boot().getBootOptions().getExecutorService(); - if (executorService == null) { - ThreadPoolExecutor executorService2 = (ThreadPoolExecutor) Executors.newCachedThreadPool(CoreNutsUtils.nutsDefaultThreadFactory); - executorService2.setKeepAliveTime(60, TimeUnit.SECONDS); - executorService2.setMaximumPoolSize(60); - executorService = executorService2; - } - } - } - } - return executorService; - } - - - public DefaultNutsIOLockAction lock() { - return new DefaultNutsIOLockAction(workspace); - } - -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsFormatManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsFormatManager.java index 9a9b0c682..943893012 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsFormatManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsFormatManager.java @@ -2,11 +2,9 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.format.DefaultNutsObjectFormat; -import net.thevpc.nuts.runtime.core.format.elem.DefaultNutsElementFormat; -import net.thevpc.nuts.runtime.core.format.tree.DefaultTreeFormat; -import net.thevpc.nuts.runtime.core.format.props.DefaultPropertiesFormat; +import net.thevpc.nuts.runtime.core.format.props.DefaultNutsPropertiesFormat; +import net.thevpc.nuts.runtime.core.format.tree.DefaultNutsTreeFormat; import net.thevpc.nuts.runtime.core.format.table.DefaultTableFormat; -import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTextManager; import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTextManagerModel; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; @@ -30,38 +28,14 @@ public NutsFormatManager setSession(NutsSession session) { return this; } -// @Override -// public NutsJsonFormat json() { -// return new DefaultNutsJsonFormat(ws); -// } -// -// @Override -// public NutsXmlFormat xml() { -// return new DefaultNutsXmlFormat(ws); -// } - @Override - public NutsElementFormat element() { - return new DefaultNutsElementFormat(model).setSession(getSession()); - } -// -// @Override -// public NutsStringFormat str() { -// return new DefaultNutsStringFormat(ws); -// } - @Override public NutsTreeFormat tree() { - return new DefaultTreeFormat(ws).setSession(getSession()); + return new DefaultNutsTreeFormat(getSession()); } @Override public NutsTableFormat table() { - return new DefaultTableFormat(ws).setSession(getSession()); - } - - @Override - public NutsElementFormat element(Object value) { - return element().setValue(value); + return new DefaultTableFormat(getSession()); } @Override @@ -81,7 +55,7 @@ public NutsPropertiesFormat props(Object value) { @Override public NutsPropertiesFormat props() { - return new DefaultPropertiesFormat(ws).setSession(getSession()); + return new DefaultNutsPropertiesFormat(getSession()); } @Override @@ -91,7 +65,7 @@ public NutsObjectFormat object(Object value) { @Override public NutsObjectFormat object() { - return new DefaultNutsObjectFormat(ws).setSession(getSession()); + return new DefaultNutsObjectFormat(getSession()); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsStreams.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsStreams.java new file mode 100644 index 000000000..fd5cb81af --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsStreams.java @@ -0,0 +1,72 @@ +package net.thevpc.nuts.runtime.standalone; + +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.NutsStream; +import net.thevpc.nuts.NutsStreams; +import net.thevpc.nuts.runtime.standalone.util.*; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.spi.NutsSupportLevelContext; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Stream; + +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) +public class DefaultNutsStreams implements NutsStreams { + private final NutsSession session; + + public DefaultNutsStreams(NutsSession session) { + this.session = session; + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } + + @Override + public NutsStream create(T[] str, String name) { + checkSession(); + if (str == null) { + return new NutsEmptyStream(getSession(), name); + } + return new NutsListStream(getSession(), name, Arrays.asList(str)); + } + + @Override + public NutsStream create(Iterable str, String name) { + checkSession(); + if (str == null) { + return new NutsEmptyStream(getSession(), name); + } + if (str instanceof List) { + return new NutsListStream(getSession(), name, (List) str); + } + if (str instanceof Collection) { + return new NutsCollectionStream(getSession(), name, (Collection) str); + } + return new NutsIterableStream<>(getSession(), name, str); + } + + @Override + public NutsStream create(Iterator str, String name) { + return new NutsIteratorStream(session, name, str); + } + + @Override + public NutsStream create(Stream str, String name) { + checkSession(); + return new NutsJavaStream<>(getSession(), name, str); + } + + public void checkSession() { + //should we ? + } + + public NutsSession getSession() { + return session; + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsTextStyleGenerator.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsTextStyleGenerator.java index 5ef53816f..9b92db87c 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsTextStyleGenerator.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsTextStyleGenerator.java @@ -109,7 +109,7 @@ private List> supps() { boolean includeAny = isIncludeAny(); supps = new ArrayList<>(); if (includePlain || includeAny) { - supps.add((i) -> NutsTextStyles.NONE); + supps.add((i) -> NutsTextStyles.PLAIN); } if (includeForeground || includeAny) { supps.add((i) -> { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsUtilManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsUtilManager.java deleted file mode 100644 index 3d943e698..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsUtilManager.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.thevpc.nuts.runtime.standalone; - -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsStream; -import net.thevpc.nuts.NutsUtilManager; -import net.thevpc.nuts.NutsVal; -import net.thevpc.nuts.runtime.standalone.util.*; - -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.stream.Stream; - -public class DefaultNutsUtilManager implements NutsUtilManager { - - private DefaultNutsUtilModel model; - private NutsSession session; - - public DefaultNutsUtilManager(DefaultNutsUtilModel model) { - this.model = model; - } - - public NutsSession getSession() { - return session; - } - - public NutsUtilManager setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(model.getWorkspace(), session); - return this; - } - - @Override - public NutsVal valOf(Object str) { - return new DefaultNutsVal(str); - } - - protected void checkSession() { - NutsWorkspaceUtils.checkSession(model.getWorkspace(), getSession()); - } - - @Override - public NutsStream streamOf(T[] str, String name) { - if(str==null){ - return new NutsEmptyStream(getSession(),name); - } - return new NutsListStream(getSession(),name, Arrays.asList(str)); - } - - @Override - public NutsStream streamOf(Iterable str, String name) { - if(str==null){ - return new NutsEmptyStream(getSession(),name); - } - if(str instanceof List){ - return new NutsListStream(getSession(),name, (List) str); - } - if(str instanceof Collection){ - return new NutsCollectionStream(getSession(),name, (Collection) str); - } - return new NutsIterableStream<>(getSession(),name, (Iterable) str); - } - - @Override - public NutsStream streamOf(Stream str, String name) { - return new NutsJavaStream<>(getSession(),name, str); - } -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsUtilModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsUtilModel.java deleted file mode 100644 index 95ace5389..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsUtilModel.java +++ /dev/null @@ -1,23 +0,0 @@ -package net.thevpc.nuts.runtime.standalone; - -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsWorkspace; -import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; -import net.thevpc.nuts.runtime.standalone.io.DefaultNutsIOLockAction; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -public class DefaultNutsUtilModel { - private NutsWorkspace workspace; - public DefaultNutsUtilModel(NutsWorkspace workspace) { - this.workspace=workspace; - } - - public NutsWorkspace getWorkspace() { - return workspace; - } - -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsVals.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsVals.java new file mode 100644 index 000000000..9ae078a6a --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsVals.java @@ -0,0 +1,24 @@ +package net.thevpc.nuts.runtime.standalone; + +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.NutsVal; +import net.thevpc.nuts.NutsVals; +import net.thevpc.nuts.spi.NutsSupportLevelContext; + +public class DefaultNutsVals implements NutsVals { + private NutsSession session; + + public DefaultNutsVals(NutsSession session) { + this.session = session; + } + + @Override + public NutsVal of(Object str) { + return new DefaultNutsVal(str); + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspace.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspace.java index 834acd655..4f9b02aac 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspace.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspace.java @@ -30,8 +30,9 @@ import net.thevpc.nuts.boot.NutsBootVersion; import net.thevpc.nuts.runtime.bundles.common.MapToFunction; import net.thevpc.nuts.runtime.core.AbstractNutsWorkspace; +import net.thevpc.nuts.runtime.core.DefaultNutsSession; import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; -import net.thevpc.nuts.runtime.core.app.DefaultNutsCommandLineManager; +import net.thevpc.nuts.runtime.core.NutsWorkspaceModel; import net.thevpc.nuts.runtime.core.app.DefaultNutsWorkspaceLocationManager; import net.thevpc.nuts.runtime.core.app.DefaultNutsWorkspaceLocationModel; import net.thevpc.nuts.runtime.core.commands.ws.DefaultNutsExecutionContextBuilder; @@ -41,17 +42,14 @@ import net.thevpc.nuts.runtime.core.events.DefaultNutsUpdateEvent; import net.thevpc.nuts.runtime.core.events.DefaultNutsWorkspaceEvent; import net.thevpc.nuts.runtime.core.filters.CoreFilterUtils; -import net.thevpc.nuts.runtime.core.filters.DefaultNutsFilterManager; import net.thevpc.nuts.runtime.core.filters.DefaultNutsFilterModel; import net.thevpc.nuts.runtime.core.format.DefaultNutsInfoFormat; -import net.thevpc.nuts.runtime.core.format.elem.DefaultNutsElementFormat; -import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTextManager; import net.thevpc.nuts.runtime.core.format.text.DefaultNutsTextManagerModel; -import net.thevpc.nuts.runtime.core.log.DefaultNutsLogManager; import net.thevpc.nuts.runtime.core.log.DefaultNutsLogModel; import net.thevpc.nuts.runtime.core.log.DefaultNutsLogger; import net.thevpc.nuts.runtime.core.model.DefaultNutsId; import net.thevpc.nuts.runtime.core.model.DefaultNutsProperties; +import net.thevpc.nuts.runtime.core.model.DefaultNutsVersion; import net.thevpc.nuts.runtime.core.parser.DefaultNutsVersionParser; import net.thevpc.nuts.runtime.core.repos.DefaultNutsRepositoryManager; import net.thevpc.nuts.runtime.core.repos.DefaultNutsRepositoryModel; @@ -64,14 +62,6 @@ import net.thevpc.nuts.runtime.standalone.ext.DefaultNutsWorkspaceExtensionManager; import net.thevpc.nuts.runtime.standalone.ext.DefaultNutsWorkspaceExtensionModel; import net.thevpc.nuts.runtime.standalone.installers.CommandForIdNutsInstallerComponent; -import net.thevpc.nuts.runtime.standalone.io.DefaultNutsIOManager; -import net.thevpc.nuts.runtime.standalone.io.DefaultNutsIOModel; -import net.thevpc.nuts.runtime.standalone.io.DefaultNutsTerminalManager; -import net.thevpc.nuts.runtime.standalone.io.DefaultNutsTerminalModel; -import net.thevpc.nuts.runtime.standalone.manager.DefaultNutsDependencyManager; -import net.thevpc.nuts.runtime.standalone.manager.DefaultNutsDescriptorManager; -import net.thevpc.nuts.runtime.standalone.manager.DefaultNutsIdManager; -import net.thevpc.nuts.runtime.standalone.manager.DefaultNutsVersionManager; import net.thevpc.nuts.runtime.standalone.repos.DefaultNutsInstalledRepository; import net.thevpc.nuts.runtime.standalone.security.DefaultNutsWorkspaceSecurityManager; import net.thevpc.nuts.runtime.standalone.security.DefaultNutsWorkspaceSecurityModel; @@ -106,7 +96,7 @@ /** * Created by vpc on 1/6/17. */ -@NutsPrototype +@NutsComponentScope(NutsComponentScopeType.PROTOTYPE) public class DefaultNutsWorkspace extends AbstractNutsWorkspace implements NutsWorkspaceExt { public static final String VERSION_INSTALL_INFO_CONFIG = "0.8.0"; @@ -122,29 +112,7 @@ public class DefaultNutsWorkspace extends AbstractNutsWorkspace implements NutsW public static final String VERSION_COMMAND_ALIAS_CONFIG_FACTORY = "0.8.0"; public static final String VERSION_USER_CONFIG = "0.8.0"; public NutsLogger LOG; - protected DefaultNutsWorkspaceSecurityModel securityModel; - protected DefaultNutsFilterModel filtersModel; - protected DefaultNutsWorkspaceConfigModel configModel; - protected DefaultNutsWorkspaceLocationModel locationsModel; - protected DefaultNutsRepositoryModel repositoryModel; - protected DefaultNutsWorkspaceEventModel eventsModel; - protected DefaultNutsTextManagerModel textModel; - protected DefaultNutsIOModel ioModel; - protected DefaultNutsTerminalModel termModel; - protected String uuid; - protected String location; - protected String name; - protected NutsVersion apiVersion; - protected NutsId apiId; - protected NutsId runtimeId; - private DefaultNutsInstalledRepository installedRepository; - private DefaultNutsLogModel logModel; - private DefaultNutsWorkspaceEnvManagerModel envModel; - private DefaultNutsWorkspaceExtensionModel extensionModel; - private DefaultCustomCommandsModel aliasesModel; - private DefaultImportModel importModel; - private DefaultNutsConcurrentModel concurrentModel; - private DefaultNutsUtilModel utilModel; + private NutsWorkspaceModel wsModel; public DefaultNutsWorkspace(NutsWorkspaceInitInformation info) { initWorkspace(info); @@ -216,33 +184,60 @@ private static Set toIds(NutsBootDescriptor[] all) { private void initWorkspace(NutsWorkspaceInitInformation info) { try { info = new CoreNutsWorkspaceInitInformation(info, this, null); - this.uuid = info.getUuid(); - this.bootModel = new DefaultNutsBootModel(this, info); - ((CoreNutsWorkspaceInitInformation) info).setSession(defaultSession()); - this.utilModel = new DefaultNutsUtilModel(this); - this.ioModel = new DefaultNutsIOModel(this, bootModel); - this.logModel = new DefaultNutsLogModel(this, info); - this.logModel.setDefaultSession(defaultSession()); - this.LOG = defaultSession().log().of(DefaultNutsWorkspace.class); + this.wsModel=new NutsWorkspaceModel(this); + this.wsModel.uuid = info.getUuid(); + + this.wsModel.bootModel = new DefaultNutsBootModel(this, info); + + //load suspendable LOG + this.LOG = new DefaultNutsLogger(this, defaultSession(),DefaultNutsWorkspace.class); ((DefaultNutsLogger) LOG).suspendTerminal(); - this.name = Paths.get(info.getWorkspaceLocation()).getFileName().toString(); - this.termModel = new DefaultNutsTerminalModel(this); - this.concurrentModel = new DefaultNutsConcurrentModel(this); - this.filtersModel = new DefaultNutsFilterModel(this); - this.installedRepository = new DefaultNutsInstalledRepository(this, info); - this.repositoryModel = new DefaultNutsRepositoryModel(this); - this.configModel = new DefaultNutsWorkspaceConfigModel(this, info); - this.envModel = new DefaultNutsWorkspaceEnvManagerModel(this, info, defaultSession()); - this.aliasesModel = new DefaultCustomCommandsModel(this); - this.importModel = new DefaultImportModel(this); - this.locationsModel = new DefaultNutsWorkspaceLocationModel(this, info, Paths.get(info.getWorkspaceLocation()).toString()); - this.eventsModel = new DefaultNutsWorkspaceEventModel(this); - this.textModel = new DefaultNutsTextManagerModel(this, info); - this.location = info.getWorkspaceLocation(); + + this.wsModel.configModel = new DefaultNutsWorkspaceConfigModel(this, info); + + String workspaceLocation = info.getWorkspaceLocation(); + String apiVersion = info.getApiVersion(); + NutsBootId runtimeId = info.getRuntimeId(); + String repositories = info.getBootRepositories(); + NutsWorkspaceOptions uoptions = info.getOptions(); + NutsBootWorkspaceFactory bootFactory = info.getBootWorkspaceFactory(); + ClassLoader bootClassLoader = info.getClassWorldLoader(); + NutsWorkspaceConfigManager _config = defaultSession().config(); + NutsBootManager _boot = defaultSession().boot(); + if (uoptions == null) { + uoptions = new ReadOnlyNutsWorkspaceOptions(_config.optionsBuilder().build(), defaultSession()); + } else { + //builder().build() (just to make a copy) + uoptions = new ReadOnlyNutsWorkspaceOptions(uoptions.builder().build(), defaultSession()); + } + NutsBootConfig cfg = new NutsBootConfig(); + cfg.setWorkspace(workspaceLocation); + cfg.setApiVersion(apiVersion); + cfg.setRuntimeId(runtimeId == null ? null : runtimeId.toString()); + cfg.setRuntimeBootDescriptor(info.getRuntimeBootDescriptor()); + cfg.setExtensionBootDescriptors(info.getExtensionBootDescriptors()); + + this.wsModel.extensionModel = new DefaultNutsWorkspaceExtensionModel(this,bootFactory,uoptions.getExcludedExtensions(), defaultSession()); + this.wsModel.extensionModel.onInitializeWorkspace(info, bootClassLoader, defaultSession()); + + ((CoreNutsWorkspaceInitInformation) info).setSession(defaultSession()); + this.wsModel.logModel = new DefaultNutsLogModel(this, info); + this.wsModel.logModel.setDefaultSession(defaultSession()); + this.wsModel.name = Paths.get(info.getWorkspaceLocation()).getFileName().toString(); + this.wsModel.filtersModel = new DefaultNutsFilterModel(this); + this.wsModel.installedRepository = new DefaultNutsInstalledRepository(this, info); + this.wsModel.repositoryModel = new DefaultNutsRepositoryModel(this); + this.wsModel.envModel = new DefaultNutsWorkspaceEnvManagerModel(this, info, defaultSession()); + this.wsModel.aliasesModel = new DefaultCustomCommandsModel(this); + this.wsModel.importModel = new DefaultImportModel(this); + this.wsModel.locationsModel = new DefaultNutsWorkspaceLocationModel(this, info, Paths.get(info.getWorkspaceLocation()).toString()); + this.wsModel.eventsModel = new DefaultNutsWorkspaceEventModel(this); + this.wsModel.textModel = new DefaultNutsTextManagerModel(this, info); + this.wsModel.location = info.getWorkspaceLocation(); DefaultNutsVersionParser vparser = new DefaultNutsVersionParser(defaultSession()); - this.apiVersion = vparser.parse(Nuts.getVersion()); - this.apiId = new DefaultNutsId("net.thevpc.nuts", "nuts", apiVersion, null, (Map) null, defaultSession()); - this.runtimeId = new DefaultNutsId( + this.wsModel.apiVersion = vparser.parse(Nuts.getVersion()); + this.wsModel.apiId = new DefaultNutsId("net.thevpc.nuts", "nuts", new DefaultNutsVersion(apiVersion,defaultSession()), null, (Map) null, defaultSession()); + this.wsModel.runtimeId = new DefaultNutsId( info.getRuntimeId().getGroupId(), info.getRuntimeId().getArtifactId(), vparser.parse(info.getRuntimeId().getVersion().toString()), @@ -251,7 +246,7 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { defaultSession()); boolean errorTheme = false; - NutsTextManager text = defaultSession().text().setSession(defaultSession()); + NutsTexts text = NutsTexts.of(defaultSession()); try { NutsTextFormatTheme theme = text.getTheme(); } catch (Exception ex) { @@ -268,6 +263,16 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { .log(NutsMessage.jstyle("unable to load theme {0}. Reset to default!", info.getOptions().getTheme())); } if (LOG.isLoggable(Level.CONFIG)) { + //just log known implementations + NutsCommandLines.of(defaultSession()); + NutsTerminals.of(defaultSession()); + NutsPrintStreams.of(defaultSession()); + NutsVersionFormat.of(defaultSession()); + NutsIdFormat.of(defaultSession()); + NutsInputStreams.of(defaultSession()); + NutsIdParser.of(defaultSession()); + NutsElements.of(defaultSession()); + LOGCSF.log(NutsMessage.jstyle(" ===============================================================================")); String s = CoreIOUtils.loadString(getClass().getResourceAsStream("/net/thevpc/nuts/runtime/includes/standard-header.ntf"), true); s = s.replace("${nuts.workspace-runtime.version}", Nuts.getVersion()); @@ -278,7 +283,6 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { LOGCSF.log(NutsMessage.jstyle(" = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =")); LOGCSF.log(NutsMessage.jstyle(" ")); LOGCSF.log(NutsMessage.jstyle("start ```sh nuts``` ```primary3 {0}``` at {1}", Nuts.getVersion(), CoreNutsUtils.DEFAULT_DATE_TIME_FORMATTER.format(Instant.ofEpochMilli(info.getOptions().getCreationTime())))); - NutsCommandLineManager commandLine = defaultSession().commandLine().setSession(defaultSession()); LOGCRF.log(NutsMessage.jstyle("open Nuts Workspace : {0}", info.getOptions().formatter().getBootCommandLine() )); @@ -287,8 +291,8 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { LOGCRF.log(NutsMessage.jstyle("open Workspace with config : ")); LOGCRF.log(NutsMessage.jstyle(" nuts-workspace-uuid : {0}", CoreNutsUtils.desc(info.getUuid(), text))); LOGCRF.log(NutsMessage.jstyle(" nuts-workspace-name : {0}", CoreNutsUtils.desc(info.getName(), text))); - LOGCRF.log(NutsMessage.jstyle(" nuts-api-version : {0}", defaultSession().version().parser().parse(Nuts.getVersion()))); - LOGCRF.log(NutsMessage.jstyle(" nuts-api-url : {0}", defaultSession().io().path(getApiURL()))); + LOGCRF.log(NutsMessage.jstyle(" nuts-api-version : {0}", NutsVersion.of(Nuts.getVersion(),defaultSession()))); + LOGCRF.log(NutsMessage.jstyle(" nuts-api-url : {0}", NutsPath.of(getApiURL(),defaultSession()))); LOGCRF.log(NutsMessage.jstyle(" nuts-api-digest : {0}", text.ofStyled(getApiDigest(), NutsTextStyle.version()))); LOGCRF.log(NutsMessage.jstyle(" nuts-boot-repositories : {0}", CoreNutsUtils.desc(info.getBootRepositories(), text))); LOGCRF.log(NutsMessage.jstyle(" nuts-runtime : {0}", getRuntimeId())); @@ -298,15 +302,14 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { LOGCRF.log(NutsMessage.jstyle(" nuts-runtime-dependencies : {0}", text.builder().appendJoined(text.ofStyled(";", NutsTextStyle.separator()), Arrays.stream(info.getRuntimeBootDescriptor().getDependencies()) - .map(x -> defaultSession().id().parser().parse(x.toString())) + .map(x -> NutsId.of(x.toString(),defaultSession())) .collect(Collectors.toList()) ) )); - NutsIOManager io = defaultSession().io(); LOGCRF.log(NutsMessage.jstyle(" nuts-runtime-urls : {0}", text.builder().appendJoined(text.ofStyled(";", NutsTextStyle.separator()), Arrays.stream(info.getClassWorldURLs()) - .map(x -> io.path(x.toString())) + .map(x -> NutsPath.of(x.toString(),defaultSession())) .collect(Collectors.toList()) ) )); @@ -314,7 +317,7 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { text.builder().appendJoined(text.ofStyled(";", NutsTextStyle.separator()), toIds(info.getExtensionBootDescriptors()).stream() .map(x -> - defaultSession().id().parser().parse(x.toString()) + NutsId.of(x.toString(),defaultSession()) ) .collect(Collectors.toList()) ) @@ -342,10 +345,10 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { LOGCRF.log(NutsMessage.jstyle(" option-progress : {0}", CoreNutsUtils.desc(info.getOptions().getProgressOptions(), text))); LOGCRF.log(NutsMessage.jstyle(" inherited : {0}", info.getOptions().isInherited())); LOGCRF.log(NutsMessage.jstyle(" inherited-nuts-boot-args : {0}", System.getProperty("nuts.boot.args") == null ? CoreNutsUtils.desc(null, text) - : CoreNutsUtils.desc(commandLine.setCommandlineFamily(NutsShellFamily.SH).parse(System.getProperty("nuts.boot.args")), text) + : CoreNutsUtils.desc(NutsCommandLine.parse(System.getProperty("nuts.boot.args"),NutsShellFamily.SH,defaultSession()), text) )); LOGCRF.log(NutsMessage.jstyle(" inherited-nuts-args : {0}", System.getProperty("nuts.args") == null ? CoreNutsUtils.desc(null, text) - : CoreNutsUtils.desc(text.toText(commandLine.setCommandlineFamily(NutsShellFamily.SH).parse(System.getProperty("nuts.args"))), text) + : CoreNutsUtils.desc(text.toText(NutsCommandLine.parse(System.getProperty("nuts.args"),NutsShellFamily.SH, defaultSession())), text) )); LOGCRF.log(NutsMessage.jstyle(" option-open-mode : {0}", CoreNutsUtils.formatLogValue(text, info.getOptions().getOpenMode(), info.getOptions().getOpenMode() == null ? NutsOpenMode.OPEN_OR_CREATE : info.getOptions().getOpenMode()))); LOGCRF.log(NutsMessage.jstyle(" java-home : {0}", System.getProperty("java.home"))); @@ -357,40 +360,18 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { LOGCRF.log(NutsMessage.jstyle(" os-arch : {0}", System.getProperty("os.arch"))); LOGCRF.log(NutsMessage.jstyle(" os-version : {0}", senv.getOsDist().getVersion())); LOGCRF.log(NutsMessage.jstyle(" user-name : {0}", System.getProperty("user.name"))); - LOGCRF.log(NutsMessage.jstyle(" user-dir : {0}", io.path(System.getProperty("user.dir")))); - LOGCRF.log(NutsMessage.jstyle(" user-home : {0}", io.path(System.getProperty("user.home")))); - } - securityModel = new DefaultNutsWorkspaceSecurityModel(this); - String workspaceLocation = info.getWorkspaceLocation(); - String apiVersion = info.getApiVersion(); - NutsBootId runtimeId = info.getRuntimeId(); - String repositories = info.getBootRepositories(); - NutsWorkspaceOptions uoptions = info.getOptions(); - NutsBootWorkspaceFactory bootFactory = info.getBootWorkspaceFactory(); - ClassLoader bootClassLoader = info.getClassWorldLoader(); - NutsWorkspaceConfigManager _config = defaultSession().config().setSession(defaultSession()); - NutsBootManager _boot = defaultSession().boot(); - NutsWorkspaceEnvManager _env = defaultSession().env(); - if (uoptions == null) { - uoptions = new ReadOnlyNutsWorkspaceOptions(_config.optionsBuilder().build(), defaultSession()); - } else { - //builder().build() (just to make a copy) - uoptions = new ReadOnlyNutsWorkspaceOptions(uoptions.builder().build(), defaultSession()); + LOGCRF.log(NutsMessage.jstyle(" user-dir : {0}", NutsPath.of(System.getProperty("user.dir"),defaultSession()))); + LOGCRF.log(NutsMessage.jstyle(" user-home : {0}", NutsPath.of(System.getProperty("user.home"),defaultSession()))); } + wsModel.securityModel = new DefaultNutsWorkspaceSecurityModel(this); + long now = System.currentTimeMillis(); if (uoptions.getCreationTime() == 0 || uoptions.getCreationTime() > now) { - configModel.setStartCreateTimeMillis(now); + wsModel.configModel.setStartCreateTimeMillis(now); } else { - configModel.setStartCreateTimeMillis(uoptions.getCreationTime()); + wsModel.configModel.setStartCreateTimeMillis(uoptions.getCreationTime()); } - NutsBootConfig cfg = new NutsBootConfig(); - cfg.setWorkspace(workspaceLocation); - cfg.setApiVersion(apiVersion); - cfg.setRuntimeId(runtimeId == null ? null : runtimeId.toString()); - cfg.setRuntimeBootDescriptor(info.getRuntimeBootDescriptor()); - cfg.setExtensionBootDescriptors(info.getExtensionBootDescriptors()); - extensionModel = new DefaultNutsWorkspaceExtensionModel(this, bootFactory, uoptions.getExcludedExtensions(), defaultSession()); boolean exists = NutsWorkspaceConfigManagerExt.of(_config).getModel().isValidWorkspaceFolder(defaultSession()); NutsOpenMode openMode = uoptions.getOpenMode(); if (openMode != null) { @@ -409,7 +390,6 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { } } } - extensionModel.onInitializeWorkspace(info, bootClassLoader, defaultSession()); // List regInfos = extensionManager.buildRegInfos(bootSession); // for (Iterator iterator = regInfos.iterator(); iterator.hasNext(); ) { // DefaultNutsWorkspaceExtensionManager.RegInfo regInfo = iterator.next(); @@ -432,16 +412,13 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { // } // } - NutsSystemTerminalBase termb = defaultSession().extensions().setSession(defaultSession()).createSupported(NutsSystemTerminalBase.class, null); - if (termb == null) { - throw new NutsExtensionNotFoundException(defaultSession(), NutsSystemTerminalBase.class, "SystemTerminalBase"); - } - NutsTerminalManager _term = defaultSession().term(); - _term + NutsSystemTerminalBase termb = defaultSession().extensions() + .createSupported(NutsSystemTerminalBase.class, true, null); + defaultSession().config() .setSystemTerminal(termb) - .setTerminal(_term.createTerminal() + .setDefaultTerminal(NutsSessionTerminal.of(defaultSession()) ); - bootModel.bootSession().setTerminal(bootModel.bootSession().term().createTerminal()); + wsModel.bootModel.bootSession().setTerminal(NutsSessionTerminal.of(wsModel.bootModel.bootSession())); // if (defaultSession().isPlainOut()) { // defaultSession().getTerminal().out().run(NutsTerminalCommand.LATER_RESET_LINE); // } @@ -452,13 +429,13 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { // extensionManager.registerType(regInfo.getExtensionPointType(),re, session); // iterator.remove(); // } - configModel.onExtensionsPrepared(defaultSession()); + wsModel.configModel.onExtensionsPrepared(defaultSession()); boolean justInstalled = false; NutsWorkspaceArchetypeComponent justInstalledArchetype=null; if (!loadWorkspace(defaultSession(), uoptions.getExcludedExtensions(), null)) { - bootModel.setFirstBoot(true); - if (uuid == null) { - uuid = UUID.randomUUID().toString(); + wsModel.bootModel.setFirstBoot(true); + if (wsModel.uuid == null) { + wsModel.uuid = UUID.randomUUID().toString(); } else { //this is the uuid of a freshly 'reset' workspace. We retain the uuid. } @@ -467,12 +444,12 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { NutsWorkspaceUtils.of(defaultSession()).checkReadOnly(); LOG.with().session(defaultSession()).level(Level.CONFIG).verb(NutsLogVerb.SUCCESS) .log(NutsMessage.jstyle("creating {0} workspace at {1}", - defaultSession().text().ofStyled("NEW", NutsTextStyle.info()), - defaultSession().io().path(defaultSession().locations().getWorkspaceLocation()) + text.ofStyled("NEW", NutsTextStyle.info()), + defaultSession().locations().getWorkspaceLocation() )); NutsWorkspaceConfigBoot bconfig = new NutsWorkspaceConfigBoot(); //load from config with resolution applied - bconfig.setUuid(uuid); + bconfig.setUuid(wsModel.uuid); NutsWorkspaceConfigApi aconfig = new NutsWorkspaceConfigApi(); aconfig.setApiVersion(apiVersion); aconfig.setRuntimeId(runtimeId == null ? null : runtimeId.toString()); @@ -504,14 +481,14 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { } bconfig.setName(CoreNutsUtils.resolveValidWorkspaceName(uoptions.getWorkspace())); - configModel.setCurrentConfig(new DefaultNutsWorkspaceCurrentConfig(this) + wsModel.configModel.setCurrentConfig(new DefaultNutsWorkspaceCurrentConfig(this) .merge(aconfig, defaultSession()) .merge(bconfig, defaultSession()) .build(defaultSession().locations().getWorkspaceLocation(), defaultSession())); // NutsUpdateOptions updateOptions = new NutsUpdateOptions().setSession(session); - configModel.setConfigBoot(bconfig, defaultSession()); - configModel.setConfigApi(aconfig, defaultSession()); - configModel.setConfigRuntime(rconfig, defaultSession()); + wsModel.configModel.setConfigBoot(bconfig, defaultSession()); + wsModel.configModel.setConfigApi(aconfig, defaultSession()); + wsModel.configModel.setConfigRuntime(rconfig, defaultSession()); justInstalledArchetype=initializeWorkspace(uoptions.getArchetype(), defaultSession()); if (!_config.isReadOnly()) { _config.save(); @@ -527,7 +504,7 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { out.resetLine(); StringBuilder version = new StringBuilder(nutsVersion.toString()); CoreStringUtils.fillString(' ', 25 - version.length(), version); - NutsTextManager txt = text.setSession(defaultSession()); + NutsTexts txt = text.setSession(defaultSession()); NutsText n = txt.parser().parseResource("/net/thevpc/nuts/runtime/includes/standard-header.ntf", txt.parser().createLoader(getClass().getClassLoader()) ); @@ -536,7 +513,7 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { txt.builder() .append("location", NutsTextStyle.underlined()) .append(":") - .append(defaultSession().locations().getWorkspaceLocation(), NutsTextStyle.path()) + .append(defaultSession().locations().getWorkspaceLocation()) .append(" ") .append(" (") .append(getHashName()) @@ -569,23 +546,23 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { repo.install(desc.getId(), defaultSession(), getRuntimeId()); } } - configModel.installBootIds(defaultSession().copy().setConfirm(NutsConfirmationMode.YES)); + wsModel.configModel.installBootIds(defaultSession().copy().setConfirm(NutsConfirmationMode.YES)); } else { - bootModel.setFirstBoot(false); - uuid = configModel.getStoreModelBoot().getUuid(); - if (NutsBlankable.isBlank(uuid)) { - uuid = UUID.randomUUID().toString(); - configModel.getStoreModelBoot().setUuid(uuid); + wsModel.bootModel.setFirstBoot(false); + wsModel.uuid = wsModel.configModel.getStoreModelBoot().getUuid(); + if (NutsBlankable.isBlank(wsModel.uuid)) { + wsModel.uuid = UUID.randomUUID().toString(); + wsModel.configModel.getStoreModelBoot().setUuid(wsModel.uuid); } if (uoptions.isRecover()) { - configModel.setBootApiVersion(cfg.getApiVersion(), defaultSession()); - configModel.setBootRuntimeId(cfg.getRuntimeId(), defaultSession()); - configModel.setBootRuntimeDependencies( + wsModel.configModel.setBootApiVersion(cfg.getApiVersion(), defaultSession()); + wsModel.configModel.setBootRuntimeId(cfg.getRuntimeId(), defaultSession()); + wsModel.configModel.setBootRuntimeDependencies( Arrays.stream(info.getRuntimeBootDescriptor().getDependencies()) .map(NutsBootId::toString) .collect(Collectors.joining(";")), defaultSession()); - configModel.setBootRepositories(cfg.getBootRepositories(), defaultSession()); + wsModel.configModel.setBootRepositories(cfg.getBootRepositories(), defaultSession()); try { defaultSession().install().setInstalled(true).setSession(defaultSession()).getResult(); } catch (Exception ex) { @@ -620,7 +597,7 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { if (!_config.isReadOnly()) { _config.save(false); } - configModel.setEndCreateTimeMillis(System.currentTimeMillis()); + wsModel.configModel.setEndCreateTimeMillis(System.currentTimeMillis()); if (justInstalled) { justInstalledArchetype.startWorkspace(defaultSession()); DefaultNutsWorkspaceEvent workspaceCreatedEvent = new DefaultNutsWorkspaceEvent(defaultSession(), null, null, null, null); @@ -630,13 +607,13 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { } // if (session.isPlainTrace()) { // PrintStream out = session.out(); -// io().term().sendTerminalCommand(out, NutsTerminalManager.MOVE_LINE_START); +// io().term().sendTerminalCommand(out, NutsTerminals.MOVE_LINE_START); // out.printf("workspace is %s!%n", formats().text().builder().append("ready")); // } if (uoptions.getUserName() != null && uoptions.getUserName().trim().length() > 0) { char[] password = uoptions.getCredentials(); if (password == null || NutsBlankable.isBlank(new String(password))) { - password = defaultSession().term().getTerminal().readPassword("Password : "); + password = defaultSession().config().getDefaultTerminal().readPassword("Password : "); } defaultSession().security().setSession(defaultSession()).login(uoptions.getUserName(), password); } @@ -649,14 +626,14 @@ private void initWorkspace(NutsWorkspaceInitInformation info) { if (CoreBooleanUtils.getSysBoolNutsProperty("perf", false)) { defaultSession().out().printf("```sh nuts``` workspace loaded in %s%n", - defaultSession().text().ofStyled(CoreTimeUtils.formatPeriodMilli(_boot.getCreationFinishTimeMillis() - _boot.getCreationStartTimeMillis()), + text.ofStyled(CoreTimeUtils.formatPeriodMilli(_boot.getCreationFinishTimeMillis() - _boot.getCreationStartTimeMillis()), NutsTextStyle.error() ) ); } } finally { - if (bootModel != null) { - bootModel.setInitializing(false); + if (wsModel.bootModel != null) { + wsModel.bootModel.setInitializing(false); } } // return !exists; @@ -782,7 +759,7 @@ public int getSupportLevel(NutsSupportLevelContext criteri @Override public String toString() { return "NutsWorkspace{" - + configModel + + wsModel.configModel + '}'; } @@ -855,7 +832,7 @@ public void installOrUpdateImpl(NutsDefinition def, String[] args, NutsInstaller NutsWorkspaceUtils wu = NutsWorkspaceUtils.of(session); if (session.isPlainTrace()) { - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); if (strategy0 == InstallStrategy0.UPDATE) { session.out().resetLine().printf("%s %s ...%n", text.ofStyled("update", NutsTextStyle.warn()), @@ -910,7 +887,7 @@ public void installOrUpdateImpl(NutsDefinition def, String[] args, NutsInstaller } default: { oldDef = session.search().setSession(session).addId(def.getId().getShortId()) - .setInstallStatus(session.filters().setSession(session).installStatus().byDeployed(true)) + .setInstallStatus(NutsInstallStatusFilters.of(session).byDeployed(true)) .setFailFast(false).getResultDefinitions().first(); break; } @@ -920,15 +897,15 @@ public void installOrUpdateImpl(NutsDefinition def, String[] args, NutsInstaller out.flush(); switch (def.getType()) { case API: { - configModel.prepareBootApi(def.getId(), null, true, session); + wsModel.configModel.prepareBootApi(def.getId(), null, true, session); break; } case RUNTIME: { - configModel.prepareBootRuntime(def.getId(), true, session); + wsModel.configModel.prepareBootRuntime(def.getId(), true, session); break; } case EXTENSION: { - configModel.prepareBootExtension(def.getId(), true, session); + wsModel.configModel.prepareBootExtension(def.getId(), true, session); break; } } @@ -1088,7 +1065,7 @@ public void installOrUpdateImpl(NutsDefinition def, String[] args, NutsInstaller if (session.isPlainTrace()) { String setAsDefaultString = ""; - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); if (updateDefaultVersion) { setAsDefaultString = " set as " + text.builder().append("default", NutsTextStyle.primary1()) + "."; } @@ -1218,14 +1195,14 @@ public String resolveCommandName(NutsId id, NutsSession session) { protected boolean loadWorkspace(NutsSession session, String[] excludedExtensions, String[] excludedRepositories) { checkSession(session); - if (configModel.loadWorkspace(session)) { + if (wsModel.configModel.loadWorkspace(session)) { //extensions already wired... this is needless! for (NutsId extensionId : session.extensions().setSession(session).getConfigExtensions()) { - if (extensionModel.isExcludedExtension(extensionId)) { + if (wsModel.extensionModel.isExcludedExtension(extensionId)) { continue; } NutsSession sessionCopy = session.copy(); - extensionModel.wireExtension(extensionId, + wsModel.extensionModel.wireExtension(extensionId, session.fetch().setSession(sessionCopy .copy() .setFetchStrategy(NutsFetchStrategy.ONLINE) @@ -1269,7 +1246,7 @@ protected boolean loadWorkspace(NutsSession session, String[] excludedExtensions @Override public String getWelcomeText(NutsSession session) { - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); NutsText n = txt.parser().parseResource("/net/thevpc/nuts/runtime/nuts-welcome.ntf", txt.parser().createLoader(getClass().getClassLoader()) ); @@ -1278,7 +1255,7 @@ public String getWelcomeText(NutsSession session) { @Override public String getHelpText(NutsSession session) { - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); NutsText n = txt.parser().parseResource("/net/thevpc/nuts/runtime/nuts-help.ntf", txt.parser().createLoader(getClass().getClassLoader()) ); @@ -1287,7 +1264,7 @@ public String getHelpText(NutsSession session) { @Override public String getLicenseText(NutsSession session) { - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); NutsText n = txt.parser().parseResource("/net/thevpc/nuts/runtime/nuts-license.ntf", txt.parser().createLoader(getClass().getClassLoader()) ); @@ -1296,11 +1273,11 @@ public String getLicenseText(NutsSession session) { @Override public String resolveDefaultHelp(Class clazz, NutsSession session) { - NutsId nutsId = session.id().resolveId(clazz); + NutsId nutsId = NutsIdResolver.of(session).resolveId(clazz); if (nutsId != null) { String urlPath = "/" + nutsId.getGroupId().replace('.', '/') + "/" + nutsId.getArtifactId() + ".ntf"; - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); NutsText n = txt.parser().parseResource(urlPath, txt.parser().createLoader(getClass().getClassLoader()) ); @@ -1344,7 +1321,7 @@ public NutsId resolveEffectiveId(NutsDescriptor descriptor, NutsSession session) } if (CoreStringUtils.containsVars(g) || CoreStringUtils.containsVars(v) || CoreStringUtils.containsVars(a)) { Map p = CoreNutsUtils.getPropertiesMap(descriptor.getProperties()); - NutsId bestId = session.id().builder().setGroupId(g).setArtifactId(thisId.getArtifactId()).setVersion(v).build(); + NutsId bestId = NutsIdBuilder.of(session).setGroupId(g).setArtifactId(thisId.getArtifactId()).setVersion(v).build(); bestId = bestId.builder().apply(new MapToFunction(p)).build(); if (CoreNutsUtils.isEffectiveId(bestId)) { return bestId; @@ -1364,7 +1341,7 @@ public NutsId resolveEffectiveId(NutsDescriptor descriptor, NutsSession session) throw new NutsNotFoundException(session, bestId, NutsMessage.cstyle("unable to fetchEffective for %s. best Result is %s", bestId, bestId), null); } - NutsId bestId = session.id().setSession(session).builder().setGroupId(g).setArtifactId(thisId.getArtifactId()).setVersion(v).build(); + NutsId bestId = NutsIdBuilder.of(session).setGroupId(g).setArtifactId(thisId.getArtifactId()).setVersion(v).build(); if (!CoreNutsUtils.isEffectiveId(bestId)) { throw new NutsNotFoundException(session, bestId, NutsMessage.cstyle("unable to fetchEffective for %s. best Result is %s", thisId, bestId), null); @@ -1413,7 +1390,8 @@ public NutsInstallerComponent getInstaller(NutsDefinition nutToInstall, NutsSess if (runnerFile == null) { runnerFile = nutToInstall; } - NutsInstallerComponent best = session.extensions().setSession(session).createSupported(NutsInstallerComponent.class, runnerFile); + NutsInstallerComponent best = session.extensions().setSession(session) + .createSupported(NutsInstallerComponent.class, false, runnerFile); if (best != null) { return best; } @@ -1469,7 +1447,7 @@ public NutsDescriptor resolveEffectiveDescriptor(NutsDescriptor descriptor, Nuts eff = l.resolve(nn); if (Files.isRegularFile(eff)) { try { - NutsDescriptor d = session.descriptor().parser().setSession(session).parse(eff); + NutsDescriptor d = NutsDescriptorParser.of(session).parse(eff); if (d != null) { return d; } @@ -1489,7 +1467,7 @@ public NutsDescriptor resolveEffectiveDescriptor(NutsDescriptor descriptor, Nuts eff = l.resolve(nn); } try { - session.descriptor().setSession(session).formatter(effectiveDescriptor).setNtf(false).print(eff); + effectiveDescriptor.formatter().setSession(session).setNtf(false).print(eff); } catch (Exception ex) { LOG.with().session(session).level(Level.FINE).error(ex) .log(NutsMessage.jstyle("failed to print {0}", eff)); @@ -1500,7 +1478,7 @@ public NutsDescriptor resolveEffectiveDescriptor(NutsDescriptor descriptor, Nuts @Override public NutsInstalledRepository getInstalledRepository() { - return installedRepository; + return wsModel.installedRepository; } @Override @@ -1510,7 +1488,7 @@ public NutsInstallStatus getInstallStatus(NutsId id, boolean checkDependencies, nutToInstall = session.search().addId(id) .setSession(session.copy().setTransitive(false)) .setInlineDependencies(checkDependencies) - .setInstallStatus(session.filters().installStatus().byDeployed(true)) + .setInstallStatus(NutsInstallStatusFilters.of(session).byDeployed(true)) .setOptional(false) .getResultDefinitions().first(); if (nutToInstall == null) { @@ -1551,11 +1529,11 @@ public void deployBoot(NutsSession session, NutsId id, boolean withDependencies) for (NutsDefinition def : defs.values()) { Path bootstrapFolder = Paths.get(session.locations().getStoreLocation(NutsStoreLocation.LIB)).resolve(NutsConstants.Folders.ID); NutsId id2 = def.getId(); - session.io().copy().from(def.getPath()) + NutsCp.of(session).from(def.getPath()) .to(bootstrapFolder.resolve(session.locations().getDefaultIdBasedir(id2)) .resolve(session.locations().getDefaultIdFilename(id2.builder().setFaceContent().setPackaging("jar").build())) ).run(); - session.descriptor().formatter(session.fetch().setId(id2).getResultDescriptor()).setNtf(false) + session.fetch().setId(id2).getResultDescriptor().formatter().setSession(session).setNtf(false) .print(bootstrapFolder.resolve(session.locations().getDefaultIdBasedir(id2)) .resolve(session.locations().getDefaultIdFilename(id2.builder().setFaceDescriptor().build()))); @@ -1594,12 +1572,12 @@ public void deployBoot(NutsSession session, NutsId id, boolean withDependencies) @Override public String getUuid() { - return uuid; + return wsModel.uuid; } @Override public String getName() { - return name; + return wsModel.name; } @Override @@ -1609,22 +1587,22 @@ public String getHashName() { @Override public NutsVersion getApiVersion() { - return apiVersion; + return wsModel.apiVersion; } @Override public NutsId getApiId() { - return apiId; + return wsModel.apiId; } @Override public NutsId getRuntimeId() { - return runtimeId; + return wsModel.runtimeId; } @Override public String getLocation() { - return location; + return wsModel.location; } // @Override @@ -1725,150 +1703,79 @@ public NutsUpdateStatisticsCommand updateStatistics() { return new DefaultNutsUpdateStatisticsCommand(this); } - @Override - public NutsWorkspaceAppsManager apps() { - return new DefaultNutsWorkspaceAppsManager(this); - } - @Override public NutsWorkspaceExtensionManager extensions() { - return new DefaultNutsWorkspaceExtensionManager(extensionModel); + return new DefaultNutsWorkspaceExtensionManager(wsModel.extensionModel); } @Override public NutsWorkspaceConfigManager config() { - return new DefaultNutsWorkspaceConfigManager(configModel); + return new DefaultNutsWorkspaceConfigManager(wsModel.configModel); } @Override public NutsRepositoryManager repos() { - return new DefaultNutsRepositoryManager(repositoryModel); + return new DefaultNutsRepositoryManager(wsModel.repositoryModel); } @Override public NutsWorkspaceSecurityManager security() { - return new DefaultNutsWorkspaceSecurityManager(securityModel); - } - - @Override - public NutsFilterManager filters() { - return new DefaultNutsFilterManager(filtersModel); - } - - @Override - public NutsIOManager io() { - return new DefaultNutsIOManager(ioModel); - } - - @Override - public NutsLogManager log() { - return new DefaultNutsLogManager(logModel); + return new DefaultNutsWorkspaceSecurityManager(wsModel.securityModel); } @Override public NutsWorkspaceEventManager events() { - return new DefaultNutsWorkspaceEventManager(eventsModel); - } - - @Override - public NutsCommandLineManager commandLine() { - return new DefaultNutsCommandLineManager(this); - } - - @Override - public NutsIdManager id() { - return new DefaultNutsIdManager(this); - } - - @Override - public NutsVersionManager version() { - return new DefaultNutsVersionManager(this); + return new DefaultNutsWorkspaceEventManager(wsModel.eventsModel); } @Override public NutsInfoFormat info() { - return new DefaultNutsInfoFormat(this); - } - - @Override - public NutsDescriptorManager descriptor() { - return new DefaultNutsDescriptorManager(this); - } - - @Override - public NutsDependencyManager dependency() { - return new DefaultNutsDependencyManager(this); + return new DefaultNutsInfoFormat(defaultSession()); } @Override public NutsFormatManager formats() { - return new DefaultNutsFormatManager(this, textModel); - } - - @Override - public NutsConcurrentManager concurrent() { - return new DefaultNutsConcurrentManager(concurrentModel); - } - - @Override - public NutsUtilManager util() { - return new DefaultNutsUtilManager(utilModel); + return new DefaultNutsFormatManager(this, wsModel.textModel); } @Override public NutsImportManager imports() { - return new DefaultImportManager(importModel); + return new DefaultImportManager(wsModel.importModel); } @Override public NutsCustomCommandManager commands() { - return new DefaultCustomCommandManager(aliasesModel); + return new DefaultCustomCommandManager(wsModel.aliasesModel); } @Override public NutsWorkspaceLocationManager locations() { - return new DefaultNutsWorkspaceLocationManager(locationsModel); + return new DefaultNutsWorkspaceLocationManager(wsModel.locationsModel); } @Override public NutsWorkspaceEnvManager env() { - return new DefaultNutsWorkspaceEnvManager(envModel); + return new DefaultNutsWorkspaceEnvManager(wsModel.envModel); } @Override public NutsBootManager boot() { - return new DefaultNutsBootManager(bootModel); + return new DefaultNutsBootManager(wsModel.bootModel); } - - @Override - public NutsTerminalManager term() { - return new DefaultNutsTerminalManager(termModel); - } - - @Override - public NutsTextManager text() { - return new DefaultNutsTextManager(this, textModel);//.setSession(getSession()); - } - - @Override - public NutsElementFormat elem() { - return new DefaultNutsElementFormat(textModel); - } - public DefaultNutsWorkspaceEnvManagerModel getEnvModel() { - return envModel; + return wsModel.envModel; } public DefaultCustomCommandsModel getAliasesModel() { - return aliasesModel; + return wsModel.aliasesModel; } public DefaultNutsWorkspaceConfigModel getConfigModel() { - return configModel; + return wsModel.configModel; } public DefaultImportModel getImportModel() { - return importModel; + return wsModel.importModel; } public enum InstallStrategy0 implements NutsEnum { @@ -1926,4 +1833,24 @@ public String id() { } + @Override + public NutsWorkspaceModel getModel() { + return wsModel; + } + + public NutsSession defaultSession() { + if (wsModel.initSession != null) { + return wsModel.initSession; + } + return wsModel.bootModel.bootSession(); + } + + @Override + public NutsSession createSession() { + NutsSession nutsSession = new DefaultNutsSession(this); + nutsSession.setTerminal(NutsSessionTerminal.of(nutsSession)); + nutsSession.setExpireTime(nutsSession.boot().getBootOptions().getExpireTime()); + return nutsSession; + } + } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceAppsManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceAppsManager.java deleted file mode 100644 index bd8434c05..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceAppsManager.java +++ /dev/null @@ -1,43 +0,0 @@ -package net.thevpc.nuts.runtime.standalone; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.standalone.io.DefaultNutsExecutionEntryAction; -import net.thevpc.nuts.runtime.core.app.DefaultNutsApplicationContext; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; - -public class DefaultNutsWorkspaceAppsManager implements NutsWorkspaceAppsManager { - - private NutsWorkspace ws; - private NutsSession session; - - public DefaultNutsWorkspaceAppsManager(NutsWorkspace ws) { - this.ws = ws; - } - - private void checkSession(NutsSession session) { - NutsWorkspaceUtils.checkSession(ws, session); - } - @Override - public NutsApplicationContext createApplicationContext(NutsSession session, String[] args, long startTimeMillis, Class appClass, String storeId) { - if (session == null) { - checkSession(this.session); - session = this.session; - } - return new DefaultNutsApplicationContext(ws, session, args, appClass, storeId, startTimeMillis); - } - - @Override - public NutsExecutionEntryAction execEntries() { - return new DefaultNutsExecutionEntryAction(ws).setSession(session); - } - - public NutsSession getSession() { - return session; - } - - public NutsWorkspaceAppsManager setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(ws, session); - return this; - } - -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceFactory.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceFactory.java index 00281d8ea..4fdf4ed47 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceFactory.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceFactory.java @@ -27,11 +27,17 @@ import net.thevpc.nuts.runtime.bundles.collections.ClassClassMap; import net.thevpc.nuts.runtime.bundles.collections.ListMap; import net.thevpc.nuts.runtime.core.NutsWorkspaceFactory; +import net.thevpc.nuts.runtime.core.model.DefaultNutsEnvConditionBuilder; +import net.thevpc.nuts.runtime.core.model.DefaultNutsIdBuilder; +import net.thevpc.nuts.runtime.core.parser.DefaultNutsIdParser; +import net.thevpc.nuts.runtime.core.parser.DefaultNutsVersionParser; import net.thevpc.nuts.runtime.core.util.CoreServiceUtils; import net.thevpc.nuts.runtime.core.util.CoreStringUtils; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; import net.thevpc.nuts.spi.*; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.net.URL; import java.util.*; import java.util.logging.Level; @@ -49,8 +55,11 @@ public class DefaultNutsWorkspaceFactory implements NutsWorkspaceFactory { // private final Map> discoveredCacheByLoader = new HashMap<>(); // private final Map> discoveredCacheByURL = new HashMap<>(); private final Map discoveredCacheById = new HashMap<>(); + private final Map cachedCtrls = new HashMap<>(); + private final HashMap _alreadyLogger = new HashMap<>(); // private final ClassClassMap discoveredCacheByClass = new ClassClassMap(); private final NutsWorkspace workspace; + public DefaultNutsWorkspaceFactory(NutsWorkspace ws) { this.workspace = ws; LOG = ((DefaultNutsWorkspace) ws).LOG; @@ -64,13 +73,19 @@ public Set discoverTypes(NutsId id, URL url, ClassLoader bootClassLoader, @Override public Set discoverTypes(NutsId id, URL url, ClassLoader bootClassLoader, Class[] extensionPoints, NutsSession session) { if (!discoveredCacheById.containsKey(id)) { - discoveredCacheById.put(id, new IdCache(id, url, bootClassLoader, LOG, extensionPoints, session)); + IdCache value = new IdCache(id, url, bootClassLoader, LOG, extensionPoints, session, workspace); + discoveredCacheById.put(id, value); + Set all = new HashSet<>(); + for (ClassClassMap m : value.classes.values()) { + all.addAll(m.values()); + } + return all; } - return null; + return Collections.emptySet(); } @Override - public , V> T createSupported(Class type, V supportCriteria, NutsSession session) { + public , V> T createSupported(Class type, V supportCriteria, boolean required, NutsSession session) { List list = createAll(type, session); int bestSupportLevel = Integer.MIN_VALUE; T bestObj = null; @@ -84,63 +99,72 @@ public , V> T createSupported(Class type, V suppor } } } -// if(bestObj==null){ -// throw new NutsElementNotFoundException("not found implementation for "+type.getName()); -// } -// if(bestObj==null){ -// throw new NutsElementNotFoundException(workspace,"missing implementation for Extension Point "+type); -// } + if (required && bestObj == null) { + //at boot time some types are nor yet available, so fall back to defaults! + + switch (type.getName()) { + case "net.thevpc.nuts.NutsIdParser": + return (T) new DefaultNutsIdParser(session); + case "net.thevpc.nuts.NutsIdBuilder": + return (T) new DefaultNutsIdBuilder(session); + case "net.thevpc.nuts.NutsEnvConditionBuilder": + return (T) new DefaultNutsEnvConditionBuilder(session); + case "net.thevpc.nuts.NutsVersionParser": + return (T) new DefaultNutsVersionParser(session); + } + throw new NutsExtensionNotFoundException(session, type, supportCriteria); + } return bestObj; } - @Override - public , V> T createSupported(Class type, V supportCriteria, Class[] constructorParameterTypes, Object[] constructorParameters, NutsSession session) { - List list = createAll(type, constructorParameterTypes, constructorParameters, session); - int bestSupportLevel = Integer.MIN_VALUE; - NutsSupportLevelContext lc = new NutsDefaultSupportLevelContext(session, supportCriteria); - T bestObj = null; - for (T t : list) { - int supportLevel = t.getSupportLevel(lc); - if (supportLevel > 0) { - if (bestObj == null || supportLevel > bestSupportLevel) { - bestSupportLevel = supportLevel; - bestObj = t; - } - } - } -// if(bestObj==null){ -// throw new NutsElementNotFoundException("not found implementation for "+type.getName()); +// @Override +// public , V> T createSupported(Class type, V supportCriteria, Class[] constructorParameterTypes, Object[] constructorParameters, boolean required, NutsSession session) { +// List list = createAll(type, constructorParameterTypes, constructorParameters, session); +// int bestSupportLevel = Integer.MIN_VALUE; +// NutsSupportLevelContext lc = new NutsDefaultSupportLevelContext(session, supportCriteria); +// T bestObj = null; +// for (T t : list) { +// int supportLevel = t.getSupportLevel(lc); +// if (supportLevel > 0) { +// if (bestObj == null || supportLevel > bestSupportLevel) { +// bestSupportLevel = supportLevel; +// bestObj = t; +// } +// } // } -// if(bestObj==null){ -// throw new NutsElementNotFoundException(workspace,"missing Implementation for Extension Point "+type); +//// if(bestObj==null){ +//// throw new NutsElementNotFoundException("not found implementation for "+type.getName()); +//// } +// if (required && bestObj == null) { +// throw new NutsElementNotFoundException(session, NutsMessage.cstyle("missing implementation for Extension Point %s with criteria %s", type, supportCriteria)); // } - return bestObj; - } +// return bestObj; +// } @Override public , V> List createAllSupported(Class type, V supportCriteria, NutsSession session) { List list = createAll(type, session); - class TypeAndLevel{ - T t; - int lvl; + class TypeAndLevel { + final T t; + final int lvl; public TypeAndLevel(T t, int lvl) { this.t = t; this.lvl = lvl; } } - List r=new ArrayList<>(); + List r = new ArrayList<>(); NutsDefaultSupportLevelContext context = new NutsDefaultSupportLevelContext<>(session, supportCriteria); for (Iterator iterator = list.iterator(); iterator.hasNext(); ) { T t = iterator.next(); int supportLevel = t.getSupportLevel(context); if (supportLevel <= 0) { iterator.remove(); - }else{ - r.add(new TypeAndLevel(t,supportLevel)); + } else { + r.add(new TypeAndLevel(t, supportLevel)); } } - return r.stream().sorted(Comparator.comparing(x->-x.lvl)).map(x->x.t).collect(Collectors.toList()); + return r.stream().sorted(Comparator.comparing(x -> -x.lvl)).map(x -> x.t).collect(Collectors.toList()); } // @Override // public List discoverInstances(Class type) { @@ -165,7 +189,7 @@ public List createAll(Class type, NutsSession session) { try { obj = (T) resolveInstance(c, type, session); } catch (Exception e) { - LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.FAIL).error(e) + LOG.with().session(validLogSession(session)).level(Level.FINEST).verb(NutsLogVerb.FAIL).error(e) .log(NutsMessage.jstyle("unable to instantiate {0} for {1} : {2}", c, type, e)); } if (obj != null) { @@ -175,6 +199,17 @@ public List createAll(Class type, NutsSession session) { return all; } + @Override + public T createFirst(Class type, NutsSession session) { + for (Object obj : instances.getAll(type)) { + return (T) obj; + } + for (Class c : getExtensionTypes(type, session)) { + return (T) resolveInstance(c, type, session); + } + return null; + } + // @Override // public Set discoverTypes(ClassLoader bootClassLoader) { // List types = discoveredCacheByLoader.get(bootClassLoader); @@ -236,7 +271,7 @@ public void registerInstance(Class extensionPoint, T implementation, Nuts throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("already registered Extension %s for %s", implementation, extensionPoint.getName())); } if (LOG.isLoggable(Level.CONFIG)) { - LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.UPDATE) + LOG.with().session(validLogSession(session)).level(Level.FINEST).verb(NutsLogVerb.UPDATE) .log(NutsMessage.jstyle("bind {0} for impl instance {1}", CoreStringUtils.alignLeft(extensionPoint.getSimpleName(), 40), implementation.getClass().getName())); } instances.add(extensionPoint, implementation); @@ -249,12 +284,12 @@ public void registerType(Class extensionPoint, Class implementation, NutsId sour throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("already registered Extension %s for %s", implementation.getName(), extensionPoint.getName())); } if (LOG.isLoggable(Level.CONFIG)) { - LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.UPDATE) + LOG.with().session(validLogSession(session)).level(Level.FINEST).verb(NutsLogVerb.UPDATE) .log(NutsMessage.jstyle("bind {0} for impl type {1}", CoreStringUtils.alignLeft(extensionPoint.getSimpleName(), 40), implementation.getName())); } IdCache t = discoveredCacheById.get(source); if (t == null) { - t = new IdCache(source); + t = new IdCache(source, workspace); discoveredCacheById.put(source, t); } ClassClassMap y = t.getClassClassMap(NutsComponent.class, true); @@ -285,40 +320,83 @@ private Object resolveClassSource(Class implementation) { return null; } - // public void unregisterType(Class extensionPoint, Class implementation) { -// Class registered = findRegisteredType(extensionPoint, implementation.getName()); -// if (registered != null) { -// if (LOG.isLoggable(Level.FINEST)) { -// LOG.with().session(session).level(Level.FINEST).verb( NutsLogVerb.UPDATE).formatted() -// .log("unbind {0} for __impl type__ {1}", extensionPoint, registered.getName()); -// } -// ClassExtension found = classes.getAll(extensionPoint).stream().filter(x->x.clazz.equals(registered)).findFirst().orElse(null); -// if(found!=null) { -// classes.remove(extensionPoint, found); -// } -// } -// } -// public void unregisterType(Class extensionPoint, String implementation) { -// Class registered = findRegisteredType(extensionPoint, implementation); -// if (registered != null) { -// if (LOG.isLoggable(Level.FINEST)) { -// LOG.with().session(session).level(Level.FINEST).verb( NutsLogVerb.UPDATE).formatted() -// .log("unbind Unregistering {0} for __impl type__ {1}", extensionPoint, registered.getName()); -// } -// ClassExtension found = classes.getAll(extensionPoint).stream().filter(x->x.clazz.equals(registered)).findFirst().orElse(null); -// if(found!=null) { -// classes.remove(extensionPoint, found); -// } -// } -// } + protected CachedConstructor getCtrl0(Class t, NutsSession session) { + CachedConstructor o = cachedCtrls.get(t); + if (o != null) { + return o; + } + try { + Constructor ctrl = t.getDeclaredConstructor(NutsSession.class); + ctrl.setAccessible(true); + CachedConstructor r = new CachedConstructor() { + @Override + public Constructor ctrl() { + return ctrl; + } + + @Override + public Object[] args(NutsSession session) { + return new Object[]{session}; + } + }; + cachedCtrls.put(t, r); + return r; + } catch (NoSuchMethodException e) { + // + } + try { + Constructor ctrl = t.getDeclaredConstructor(NutsWorkspace.class); + ctrl.setAccessible(true); + CachedConstructor r = new CachedConstructor() { + @Override + public Constructor ctrl() { + return ctrl; + } + + @Override + public Object[] args(NutsSession session) { + return new Object[]{session.getWorkspace()}; + } + }; + cachedCtrls.put(t, r); + return r; + } catch (NoSuchMethodException e) { + // + } + try { + Constructor ctrl = t.getDeclaredConstructor(); + ctrl.setAccessible(true); + CachedConstructor r = new CachedConstructor() { + @Override + public Constructor ctrl() { + return ctrl; + } + + @Override + public Object[] args(NutsSession session) { + return new Object[0]; + } + }; + cachedCtrls.put(t, r); + return r; + } catch (NoSuchMethodException e) { + // + } + return null; + } + protected T instantiate0(Class t, NutsSession session) { checkSession(session); T theInstance = null; + CachedConstructor ctrl = getCtrl0(t, session); + if (ctrl == null) { + throw new NutsFactoryException(session, NutsMessage.cstyle("instantiate '%s' failed. missing constructor", t)); + } try { - theInstance = t.newInstance(); - } catch (InstantiationException e) { + theInstance = ctrl.ctrl().newInstance(ctrl.args(session)); + } catch (InstantiationException | InvocationTargetException e) { if (LOG.isLoggable(Level.FINEST)) { - LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.FAIL).error(e) + LOG.with().session(validLogSession(session)).level(Level.FINEST).verb(NutsLogVerb.FAIL).error(e) .log(NutsMessage.jstyle("unable to instantiate {0}", t)); } Throwable cause = e.getCause(); @@ -343,7 +421,7 @@ protected T instantiate0(Class t, Class[] argTypes, Object[] args, NutsSe t1 = t.getConstructor(argTypes).newInstance(args); } catch (InstantiationException e) { if (LOG.isLoggable(Level.FINEST)) { - LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.FAIL).error(e) + LOG.with().session(validLogSession(session)).level(Level.FINEST).verb(NutsLogVerb.FAIL).error(e) .log(NutsMessage.jstyle("unable to instantiate {0}", t)); } Throwable cause = e.getCause(); @@ -356,7 +434,7 @@ protected T instantiate0(Class t, Class[] argTypes, Object[] args, NutsSe throw new NutsFactoryException(session, NutsMessage.cstyle("instantiate '%s' failed", t), cause); } catch (Exception e) { if (LOG.isLoggable(Level.FINEST)) { - LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.FAIL).error(e) + LOG.with().session(validLogSession(session)).level(Level.FINEST).verb(NutsLogVerb.FAIL).error(e) .log(NutsMessage.jstyle("unable to instantiate {0}", t)); } if (e instanceof RuntimeException) { @@ -368,43 +446,121 @@ protected T instantiate0(Class t, Class[] argTypes, Object[] args, NutsSe return t1; } - protected T resolveInstance(Class type, Class baseType, NutsSession session) { - if (type == null) { + protected T resolveInstance(Class implType, Class apiType, NutsSession session) { + if (implType == null) { return null; } - Boolean singleton = null; - if (baseType.getAnnotation(NutsSingleton.class) != null) { - singleton = true; - } else if (baseType.getAnnotation(NutsPrototype.class) != null) { - singleton = false; - } - if (type.getAnnotation(NutsSingleton.class) != null) { - singleton = true; - } else if (type.getAnnotation(NutsPrototype.class) != null) { - singleton = false; + NutsComponentScopeType scope = computeScope(implType, apiType, session); + switch (scope) { + case WORKSPACE: { + Object o = singletons.get(implType); + if (o == null) { + o = instantiate0(implType, session); + if (o != null) { + singletons.put(implType, o); + doLogInstantiation(apiType, o.getClass(), "singleton", session); + } + } + return (T) o; + } + case SESSION: { + //the same class wont be create twice for this session! + String key = "session-scoped:" + Integer.toHexString(System.identityHashCode(session)).toUpperCase() + ":" + implType.getName(); + Object o = session.getProperty(key); + if (o == null) { + o = instantiate0(implType, session); + if (o != null) { + session.setProperty(key, o); + doLogInstantiation(apiType, o.getClass(), "session", session); + } + } + return (T) o; + } + default: { + T o = instantiate0(implType, session); + if (o != null) { + doLogInstantiation(apiType, o.getClass(), "prototype", session); + } + return o; + } } - if (singleton == null) { - singleton = false; + } + + private NutsComponentScopeType computeScope(Class implType, Class apiType, NutsSession session) { + NutsComponentScope apiScope = apiType.getAnnotation(NutsComponentScope.class); + NutsComponentScope implScope = implType.getAnnotation(NutsComponentScope.class); + NutsComponentScopeType scope = NutsComponentScopeType.PROTOTYPE; + if (apiScope != null || implScope != null) { + if (apiScope != null && implScope == null) { + scope = apiScope.value(); + } else if (apiScope == null && implScope != null) { + scope = implScope.value(); + } else { + if (apiScope.value() == implScope.value()) { + scope = apiScope.value(); + } else { + //bo defined! stick with api! + scope = apiScope.value(); + if (LOG.isLoggable(Level.CONFIG)) { + switch (apiType.getName()) { + //skip logging for NutsTexts to avoid infinite recursion + case "net.thevpc.nuts.NutsTexts": { + break; + } + default: { + LOG.with().session(validLogSession(session)).level(Level.FINEST).verb(NutsLogVerb.FAIL) + .log(NutsMessage.jstyle("invalid scope {0} ; expected {1} for {2}", + implScope.value(), + apiScope.value(), + implType.getName() + )); + } + } + } + } + } } - if (singleton) { - Object o = singletons.get(type); - if (o == null) { - o = instantiate0(type, session); - singletons.put(type, o); + return scope; + } + + private void doLogInstantiation(Class baseType, Class implType, String scope, NutsSession session) { + switch (baseType.getName()) { + //skip logging this to avoid infinite recursion + case "net.thevpc.nuts.NutsTexts": + case "net.thevpc.nuts.spi.NutsLogManager": + case "net.thevpc.nuts.NutsLogger": + case "net.thevpc.nuts.NutsLoggerOp": + { + break; + } + default: { if (LOG.isLoggable(Level.CONFIG)) { - LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.READ) - .log(NutsMessage.jstyle("resolve {0} to ```underlined singleton``` {1}", CoreStringUtils.alignLeft(baseType.getSimpleName(), 40), o.getClass().getName())); + String old = _alreadyLogger.get(baseType.getName()); + if(old==null || !old.equals(implType.getName())) { + _alreadyLogger.put(baseType.getName(),implType.getName()); + LOG.with().session(validLogSession(session)).level(Level.FINEST).verb(NutsLogVerb.READ) + .log(NutsMessage.jstyle("resolve {0} to ```underlined {1}``` {2}", + CoreStringUtils.alignLeft(baseType.getSimpleName(), 40), + scope, + implType.getName() + )); + } } } - return (T) o; - } else { - T o = instantiate0(type, session); - if (LOG.isLoggable(Level.CONFIG)) { - LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.READ) - .log(NutsMessage.jstyle("resolve {0} to ```underlined prototype``` {1}", CoreStringUtils.alignLeft(baseType.getSimpleName(), 40), o.getClass().getName())); - } - return o; } + + } + + private NutsSession validLogSession(NutsSession session) { + if (session == null) { + //this is a bug + return NutsWorkspaceUtils.defaultSession(workspace); + } + if (session.getTerminal() == null) { + //chances are that we are creating the session or the session's Terminal + return NutsWorkspaceUtils.defaultSession(workspace); + } + return session; } protected T resolveInstance(Class type, Class baseType, Class[] argTypes, Object[] args, NutsSession session) { @@ -435,7 +591,7 @@ protected T resolveInstance(Class type, Class baseType, Class[] argTyp o = instantiate0(type, session); singletons.put(type, o); if (LOG.isLoggable(Level.CONFIG)) { - LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.READ) + LOG.with().session(validLogSession(session)).level(Level.FINEST).verb(NutsLogVerb.READ) .log(NutsMessage.jstyle("resolve {0} to ```underlined singleton``` {1}", CoreStringUtils.alignLeft(baseType.getSimpleName(), 40), o.getClass().getName())); } } @@ -443,7 +599,7 @@ protected T resolveInstance(Class type, Class baseType, Class[] argTyp } else { T o = instantiate0(type, argTypes, args, session); if (LOG.isLoggable(Level.CONFIG)) { - LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.READ) + LOG.with().session(validLogSession(session)).level(Level.FINEST).verb(NutsLogVerb.READ) .log(NutsMessage.jstyle("resolve {0} to ```underlined prototype``` {1}", CoreStringUtils.alignLeft(baseType.getSimpleName(), 40), o.getClass().getName())); } return o; @@ -457,7 +613,7 @@ public T create(Class type, NutsSession session) { if (one != null) { //if static instance found, always return it! if (LOG.isLoggable(Level.CONFIG)) { - LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.READ) + LOG.with().session(validLogSession(session)).level(Level.FINEST).verb(NutsLogVerb.READ) .log(NutsMessage.jstyle("resolve {0} to singleton {1}", CoreStringUtils.alignLeft(type.getSimpleName(), 40), one.getClass().getName())); } return (T) one; @@ -479,7 +635,7 @@ public List createAll(Class type, Class[] argTypes, Object[] args, Nut try { obj = (T) resolveInstance(c, type, argTypes, args, session); } catch (Exception e) { - LOG.with().session(session).level(Level.WARNING).verb(NutsLogVerb.FAIL).error(e) + LOG.with().session(validLogSession(session)).level(Level.WARNING).verb(NutsLogVerb.FAIL).error(e) .log(NutsMessage.jstyle("unable to instantiate {0} for {1} : {2}", c, type, e)); } if (obj != null) { @@ -493,6 +649,38 @@ public List createAll(Class type, Class[] argTypes, Object[] args, Nut return all; } + // public void unregisterType(Class extensionPoint, Class implementation) { +// Class registered = findRegisteredType(extensionPoint, implementation.getName()); +// if (registered != null) { +// if (LOG.isLoggable(Level.FINEST)) { +// LOG.with().session(session).level(Level.FINEST).verb( NutsLogVerb.UPDATE).formatted() +// .log("unbind {0} for __impl type__ {1}", extensionPoint, registered.getName()); +// } +// ClassExtension found = classes.getAll(extensionPoint).stream().filter(x->x.clazz.equals(registered)).findFirst().orElse(null); +// if(found!=null) { +// classes.remove(extensionPoint, found); +// } +// } +// } +// public void unregisterType(Class extensionPoint, String implementation) { +// Class registered = findRegisteredType(extensionPoint, implementation); +// if (registered != null) { +// if (LOG.isLoggable(Level.FINEST)) { +// LOG.with().session(session).level(Level.FINEST).verb( NutsLogVerb.UPDATE).formatted() +// .log("unbind Unregistering {0} for __impl type__ {1}", extensionPoint, registered.getName()); +// } +// ClassExtension found = classes.getAll(extensionPoint).stream().filter(x->x.clazz.equals(registered)).findFirst().orElse(null); +// if(found!=null) { +// classes.remove(extensionPoint, found); +// } +// } +// } + private interface CachedConstructor { + Constructor ctrl(); + + Object[] args(NutsSession session); + } + private final static class ClassExtension { Class clazz; @@ -509,16 +697,19 @@ public ClassExtension(Class clazz, Object source, boolean enabled) { private static class IdCache { private final NutsId id; - private URL url; private final Map classes = new HashMap<>(); + private final NutsWorkspace workspace; + private URL url; - public IdCache(NutsId id) { + public IdCache(NutsId id, NutsWorkspace workspace) { this.id = id; + this.workspace = workspace; } - public IdCache(NutsId id, URL url, ClassLoader bootClassLoader, NutsLogger LOG, Class[] extensionPoints, NutsSession session) { + public IdCache(NutsId id, URL url, ClassLoader bootClassLoader, NutsLogger LOG, Class[] extensionPoints, NutsSession session, NutsWorkspace workspace) { this.id = id; this.url = url; + this.workspace = workspace; for (Class extensionPoint : extensionPoints) { ClassClassMap cc = new ClassClassMap(); classes.put(extensionPoint, cc); @@ -528,21 +719,35 @@ public IdCache(NutsId id, URL url, ClassLoader bootClassLoader, NutsLogger LOG, try { c = Class.forName(n, false, bootClassLoader); } catch (ClassNotFoundException x) { - LOG.with().session(session).verb(NutsLogVerb.WARNING).level(Level.FINE).error(x) + LOG.with().session(validLogSession(session)).verb(NutsLogVerb.WARNING).level(Level.FINE).error(x) .log(NutsMessage.jstyle("not a valid type {0}", c)); } if (c != null) { if (!serviceClass.isAssignableFrom(c)) { - LOG.with().session(session).verb(NutsLogVerb.WARNING).level(Level.FINE) + LOG.with().session(validLogSession(session)).verb(NutsLogVerb.WARNING).level(Level.FINE) .log(NutsMessage.jstyle("not a valid type {0} <> {1}, ignore...", c, serviceClass)); } else { cc.add(c); } } } +// int size=cc.size(); } } + private NutsSession validLogSession(NutsSession session) { + if (session == null) { + //this is a bug + return NutsWorkspaceUtils.defaultSession(workspace); + } + if (session.getTerminal() == null) { + //chances are that we are creating the session or the session's Terminal + return NutsWorkspaceUtils.defaultSession(workspace); + } + return session; + } + + private ClassClassMap getClassClassMap(Class extensionPoint, boolean create) { ClassClassMap r = classes.get(extensionPoint); if (r == null && create) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceListManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceListManager.java index 9aa323cec..b19fc6b12 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceListManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/DefaultNutsWorkspaceListManager.java @@ -15,20 +15,20 @@ */ public class DefaultNutsWorkspaceListManager implements NutsWorkspaceListManager { - private final NutsSession defaultWorkspace; + private final NutsSession defaultSession; private final String name; private Map workspaces = new LinkedHashMap<>(); private NutsWorkspaceListConfig config; public DefaultNutsWorkspaceListManager(NutsSession session, String name) { - this.defaultWorkspace = session; + this.defaultSession = session; if (NutsBlankable.isBlank(name)) { name = "default"; } this.name = name.trim(); Path file = getConfigFile(session); if (Files.exists(file)) { - this.config = this.defaultWorkspace.elem().setContentType(NutsContentType.JSON).parse(file, NutsWorkspaceListConfig.class); + this.config = NutsElements.of(this.defaultSession).json().parse(file, NutsWorkspaceListConfig.class); for (NutsWorkspaceLocation var : this.config.getWorkspaces()) { this.workspaces.put(var.getUuid(), var); } @@ -40,17 +40,16 @@ public DefaultNutsWorkspaceListManager(NutsSession session, String name) { new NutsWorkspaceLocation() .setUuid(session.getWorkspace().getUuid()) .setName(NutsConstants.Names.DEFAULT_WORKSPACE_NAME) - .setLocation(this.defaultWorkspace.locations().getWorkspaceLocation()) + .setLocation(this.defaultSession.locations().getWorkspaceLocation().toString()) ); this.save(session); } } private Path getConfigFile(NutsSession session) { - return Paths.get(this.defaultWorkspace + return Paths.get(session .locations() - .getStoreLocation(this.defaultWorkspace - .id().setSession(session).resolveId(DefaultNutsWorkspaceListManager.class), + .getStoreLocation(NutsIdResolver.of(session).resolveId(DefaultNutsWorkspaceListManager.class), NutsStoreLocation.CONFIG)) .resolve(name + "-nuts-workspace-list.json"); } @@ -81,10 +80,8 @@ public NutsSession addWorkspace(String path, NutsSession session) { NutsSession ss = this.createWorkspace(path); NutsWorkspaceLocation workspaceLocation = new NutsWorkspaceLocation() .setUuid(ss.getWorkspace().getUuid()) - .setName( - Paths.get(ss.locations().getWorkspaceLocation()) - .getFileName().toString()) - .setLocation(ss.locations().getWorkspaceLocation()); + .setName(ss.locations().getWorkspaceLocation().getName()) + .setLocation(ss.locations().getWorkspaceLocation().toString()); workspaces.put(ss.getWorkspace().getUuid(), workspaceLocation); this.save(session); return ss; @@ -105,7 +102,7 @@ public void save(NutsSession session) { ? null : new ArrayList<>(this.workspaces.values())); Path file = getConfigFile(session); - this.defaultWorkspace.elem().setContentType(NutsContentType.JSON).setValue(this.config) + NutsElements.of(this.defaultSession).json().setValue(this.config) .setNtf(false) .print(file); } @@ -117,7 +114,7 @@ public DefaultNutsWorkspaceListManager setWorkspaces(Map def = new LinkedHashMap<>(); Map defaults = new HashMap<>(); for (NutsAddRepositoryOptions d : rm.getDefaultRepositories()) { if (d.getConfig() != null) { - def.put(session.io().path(d.getConfig().getLocation()).builder().build().toString(), d); + def.put(NutsPath.of(d.getConfig().getLocation(),session).builder().build().toString(), d); } else { - def.put(session.io().path(d.getLocation()).builder().build().toString(), d); + def.put(NutsPath.of(d.getLocation(),session).builder().build().toString(), d); } defaults.put(d.getName(), null); } @@ -64,8 +65,7 @@ public void initializeWorkspace(NutsSession session) { NutsRepositorySelector.Selection[] br = rm.getModel().resolveBootRepositoriesList().resolveSelectors(defaults); for (NutsRepositorySelector.Selection s : br) { NutsAddRepositoryOptions oo = NutsRepositorySelector.createRepositoryOptions(s, false, session); - String sloc = session.io() - .path(oo.getConfig().getLocation()).builder().build().toString(); + String sloc = NutsPath.of(oo.getConfig().getLocation(),session).builder().build().toString(); if (def.containsKey(sloc)) { session.repos().addRepository(def.get(sloc)); def.remove(sloc); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/archetypes/MinimalNutsWorkspaceArchetypeComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/archetypes/MinimalNutsWorkspaceArchetypeComponent.java index 0652f6160..2c696fd36 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/archetypes/MinimalNutsWorkspaceArchetypeComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/archetypes/MinimalNutsWorkspaceArchetypeComponent.java @@ -23,23 +23,22 @@ */ package net.thevpc.nuts.runtime.standalone.archetypes; -import java.util.HashMap; - import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.repos.NutsRepositorySelector; import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigManager; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.spi.NutsSupportLevelContext; import net.thevpc.nuts.spi.NutsWorkspaceArchetypeComponent; +import java.util.HashMap; import java.util.Map; -import net.thevpc.nuts.runtime.core.repos.NutsRepositorySelector; - /** * Created by vpc on 1/23/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class MinimalNutsWorkspaceArchetypeComponent implements NutsWorkspaceArchetypeComponent { private NutsLogger LOG; @@ -50,7 +49,7 @@ public String getName() { @Override public void initializeWorkspace(NutsSession session) { - this.LOG = session.log().of(MinimalNutsWorkspaceArchetypeComponent.class); + this.LOG = NutsLogger.of(MinimalNutsWorkspaceArchetypeComponent.class, session); // NutsWorkspace ws = session.getWorkspace(); DefaultNutsWorkspaceConfigManager rm = (DefaultNutsWorkspaceConfigManager) session.config(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/archetypes/ServerNutsWorkspaceArchetypeComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/archetypes/ServerNutsWorkspaceArchetypeComponent.java index 0de8d3c9e..38db7f79b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/archetypes/ServerNutsWorkspaceArchetypeComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/archetypes/ServerNutsWorkspaceArchetypeComponent.java @@ -25,23 +25,22 @@ */ package net.thevpc.nuts.runtime.standalone.archetypes; -import java.util.HashMap; - import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.repos.NutsRepositorySelector; import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigManager; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.spi.NutsSupportLevelContext; import net.thevpc.nuts.spi.NutsWorkspaceArchetypeComponent; +import java.util.HashMap; import java.util.Map; -import net.thevpc.nuts.runtime.core.repos.NutsRepositorySelector; - /** * Created by vpc on 1/23/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class ServerNutsWorkspaceArchetypeComponent implements NutsWorkspaceArchetypeComponent { private NutsLogger LOG; @@ -52,7 +51,7 @@ public String getName() { @Override public void initializeWorkspace(NutsSession session) { - this.LOG = session.log().of(ServerNutsWorkspaceArchetypeComponent.class); + this.LOG = NutsLogger.of(ServerNutsWorkspaceArchetypeComponent.class, session); DefaultNutsWorkspaceConfigManager rm = (DefaultNutsWorkspaceConfigManager) session.config(); Map defaults = new HashMap<>(); defaults.put("maven-local", null); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/DefaultNutsBootManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/DefaultNutsBootManager.java index acf1afd2a..329ecd617 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/DefaultNutsBootManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/DefaultNutsBootManager.java @@ -23,10 +23,9 @@ */ package net.thevpc.nuts.runtime.standalone.boot; -import net.thevpc.nuts.NutsBootManager; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsVal; -import net.thevpc.nuts.NutsWorkspaceOptions; +import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; +import net.thevpc.nuts.runtime.core.NutsWorkspaceModel; import net.thevpc.nuts.runtime.standalone.DefaultNutsVal; import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigManager; import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigModel; @@ -61,6 +60,12 @@ public NutsSession getSession() { return session; } + public NutsClassLoaderNode getBootRuntimeClassLoaderNode(){ + return model.workspaceInitInformation.getRuntimeBootDependencyNode(); + } + public NutsClassLoaderNode[] getBootExtensionClassLoaderNode(){ + return model.workspaceInitInformation.getExtensionBootDependencyNodes(); + } @Override public NutsBootManager setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(model.getWorkspace(), session); @@ -106,6 +111,12 @@ public URL[] getBootClassWorldURLs() { return _configModel().getBootClassWorldURLs(); } +// public ee(){ +// NutsWorkspaceModel wsModel = ((NutsWorkspaceExt) session.getWorkspace()).getModel(); +// wsModel.bootModel.getWorkspaceInitInformation().getOptions(); +// +// } + @Override public String getBootRepositories() { checkSession(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/DefaultNutsBootModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/DefaultNutsBootModel.java index 34fd0e2ee..13b64c48e 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/DefaultNutsBootModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/DefaultNutsBootModel.java @@ -112,14 +112,17 @@ public DefaultNutsBootModel setFirstBoot(boolean firstBoot) { return this; } + @Override public NutsPrintStream stdout() { return stdout; } + @Override public NutsPrintStream stderr() { return stderr; } + @Override public InputStream stdin() { return stdin; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/NutsBootModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/NutsBootModel.java index d65889350..fad4209d6 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/NutsBootModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/boot/NutsBootModel.java @@ -23,6 +23,10 @@ */ package net.thevpc.nuts.runtime.standalone.boot; +import net.thevpc.nuts.NutsPrintStream; + +import java.io.InputStream; + /** * * @author vpc @@ -32,4 +36,9 @@ public interface NutsBootModel { boolean isInitializing(); boolean isFirstBoot(); + NutsPrintStream stdout(); + + NutsPrintStream stderr(); + + InputStream stdin(); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/AbstractMavenRepositoryHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/AbstractMavenRepositoryHelper.java index c80e1a827..f774ea87c 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/AbstractMavenRepositoryHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/AbstractMavenRepositoryHelper.java @@ -52,7 +52,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(AbstractMavenRepositoryHelper.class); + LOG = NutsLogger.of(AbstractMavenRepositoryHelper.class,session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/LuceneIndexImporter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/LuceneIndexImporter.java index 138291a35..4234cadca 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/LuceneIndexImporter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/LuceneIndexImporter.java @@ -1,8 +1,6 @@ package net.thevpc.nuts.runtime.standalone.bridges.maven; -import net.thevpc.nuts.NutsId; -import net.thevpc.nuts.NutsIdParser; -import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.bundles.mvn.DirtyLuceneIndexParser; import net.thevpc.nuts.runtime.standalone.index.ArtifactsIndexDB; @@ -23,12 +21,12 @@ public LuceneIndexImporter(NutsSession session) { public long importGzURL(URL url, String repository,NutsSession session) { // NutsWorkspace ws = session.getWorkspace(); - String tempGzFile = session.io().tmp().createTempFile("lucene-repository.gz").toString(); - session.io().copy() + String tempGzFile = NutsTmp.of(session).createTempFile("lucene-repository.gz").toString(); + NutsCp.of(session) .setSession(session) .from(url).to(tempGzFile).run(); - String tempFolder = session.io().tmp().createTempFolder("lucene-repository").toString(); - session.io().uncompress().from(tempGzFile).to( + String tempFolder = NutsTmp.of(session).createTempFolder("lucene-repository").toString(); + NutsUncompress.of(session).from(tempGzFile).to( tempFolder ).setFormat("gz").run(); try { @@ -46,7 +44,7 @@ public long importGzURL(URL url, String repository,NutsSession session) { public long importFile(String filePath,String repository,NutsSession session) { ArtifactsIndexDB adb = ArtifactsIndexDB.of(session); - NutsIdParser idParser = session.id().parser(); + NutsIdParser idParser = NutsIdParser.of(session); int addedCount=0; int allCount=0; try (DirtyLuceneIndexParser p = new DirtyLuceneIndexParser(new FileInputStream(filePath))) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenFolderRepository.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenFolderRepository.java index 13a5caac4..2002a7c45 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenFolderRepository.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenFolderRepository.java @@ -81,7 +81,7 @@ protected void checkSHA1Hash(NutsId id, InputStream stream, String typeName, Nut public MavenFolderRepository(NutsAddRepositoryOptions options, NutsSession session, NutsRepository parentRepository) { super(options, session, parentRepository, NutsSpeedQualifier.FASTER, false, NutsConstants.RepoTypes.MAVEN); - LOG = session.log().of(MavenFolderRepository.class); + LOG = NutsLogger.of(MavenFolderRepository.class,session); if (options.getConfig().getStoreLocationStrategy() != NutsStoreLocationStrategy.STANDALONE) { cache.setWriteEnabled(false); cache.setReadEnabled(false); @@ -146,13 +146,13 @@ public NutsContent fetchContentCore(NutsId id, NutsDescriptor descriptor, String } if (localPath == null) { return new NutsDefaultContent( - session.io().path(f.toString()), true, false); + NutsPath.of(f,session), true, false); } else { - session.io().copy() + NutsCp.of(session) .setSession(session) .from(f).to(localPath).setSafe(true).run(); return new NutsDefaultContent( - session.io().path(localPath), true, false); + NutsPath.of(localPath,session), true, false); } } @@ -188,8 +188,8 @@ public Iterator searchVersionsCore(NutsId id, NutsIdFilter idFilter, Nut } try { namedNutIdIterator = findInFolder(getLocationAsPath(session),getLocalGroupAndArtifactFile(id, session), - session.id().filter().nonnull(idFilter).and( - session.id().filter().byName(id.getShortName()) + NutsIdFilters.of(session).nonnull(idFilter).and( + NutsIdFilters.of(session).byName(id.getShortName()) ), Integer.MAX_VALUE, session); } catch (NutsNotFoundException ex) { @@ -358,7 +358,7 @@ public NutsId parseId(Path pomFile, Path rootPath, NutsIdFilter filter, String r gn.append(ns); } return validate( - session.id().builder() + NutsIdBuilder.of(session) .setGroupId(gn.toString()) .setArtifactId(an) .setVersion(vn) diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRemoteRepository.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRemoteRepository.java index af9524f11..98b7bb271 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRemoteRepository.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRemoteRepository.java @@ -62,7 +62,7 @@ public boolean isDescFile(String pathname) { @Override public NutsDescriptor parseDescriptor(String pathname, InputStream in, NutsFetchMode fetchMode, NutsRepository repository, NutsSession session, String rootURL) throws IOException { - session.getTerminal().printProgress("%-8s %s", "parse", session.io().path(pathname).toCompressedForm()); + session.getTerminal().printProgress("%-8s %s", "parse", NutsPath.of(pathname,session).toCompressedForm()); return MavenUtils.of(session).parsePomXmlAndResolveParents(in, fetchMode, pathname, repository); } @@ -89,7 +89,7 @@ public NutsId parseId(String path, String rootPath, NutsIdFilter filter, NutsRep gn.append(ns); } return validate( - session.id().builder() + NutsIdBuilder.of(session) .setGroupId(gn.toString()) .setArtifactId(an) .setVersion(vn) @@ -115,9 +115,9 @@ protected String getIdPath(NutsId id, NutsSession session) { @Override protected boolean exists(NutsId id, String path, Object source, String typeName, NutsSession session) { - session.getTerminal().printProgress("%-8s %s", "search", session.io().path(path).toCompressedForm()); + session.getTerminal().printProgress("%-8s %s", "search", NutsPath.of(path,session).toCompressedForm()); try { - try (InputStream s = session.io().monitor().setSource(path).setOrigin(source).setSession(session) + try (InputStream s = NutsInputStreamMonitor.of(session).setSource(path).setOrigin(source) .setSourceTypeName(typeName).create()) { // } @@ -129,8 +129,8 @@ protected boolean exists(NutsId id, String path, Object source, String typeName, @Override protected InputStream openStream(NutsId id, String path, Object source, String typeName, String action, NutsSession session) { - session.getTerminal().printProgress("%-8s %s", action, session.io().path(path).toCompressedForm()); - return session.io().monitor().setSource(path).setOrigin(source).setSession(session).setSourceTypeName(typeName).create(); + session.getTerminal().printProgress("%-8s %s", action, NutsPath.of(path,session).toCompressedForm()); + return NutsInputStreamMonitor.of(session).setSource(path).setOrigin(source).setSourceTypeName(typeName).create(); } }; @@ -141,7 +141,7 @@ protected InputStream openStream(NutsId id, String path, Object source, String t // } protected MavenRemoteRepository(NutsAddRepositoryOptions options, NutsSession session, NutsRepository parentRepository, String repoType) { super(options, session, parentRepository, NutsSpeedQualifier.SLOW, false, repoType); - LOG = session.log().of(MavenRemoteRepository.class); + LOG = NutsLogger.of(MavenRemoteRepository.class,session); switch (repoType) { case "maven": { this.findApi = RemoteRepoApi.MAVEN; @@ -188,8 +188,8 @@ public Iterator searchVersionsCore(final NutsId id, NutsIdFilter idFilte } return ret.iterator(); } - NutsIdFilter filter2 = session.id().filter().nonnull(idFilter).and( - session.id().filter().byName(id.getShortName()) + NutsIdFilter filter2 = NutsIdFilters.of(session).nonnull(idFilter).and( + NutsIdFilters.of(session).byName(id.getShortName()) ); switch (versionApi) { case DEFAULT: @@ -249,27 +249,25 @@ public NutsContent fetchContentCore(NutsId id, NutsDescriptor descriptor, String if (content != null && Files.exists(content)) { if (localPath == null) { return new NutsDefaultContent( - session.io().path(content.toString()), true, false); + NutsPath.of(content,session), true, false); } else { - String tempFile = session.io().tmp() + String tempFile = NutsTmp.of(session) .setRepositoryId(getUuid()) .createTempFile(content.getFileName().toString()).toString(); - session.io().copy() - .setSession(session) + NutsCp.of(session) .from(content).to(tempFile).setSafe(true).run(); return new NutsDefaultContent( - session.io().path(tempFile), true, false); + NutsPath.of(tempFile,session), true, false); } } } if (localPath == null) { String p = helper.getIdPath(id, session); - String tempFile = session.io().tmp() - .setSession(session) + String tempFile = NutsTmp.of(session) .setRepositoryId(getUuid()) .createTempFile(new File(p).getName()).toString(); try { - session.io().copy() + NutsCp.of(session) .from(helper.getStream(id, "artifact binaries", "retrieve", session)).to(tempFile).setValidator(new NutsIOCopyValidator() { @Override public void validate(InputStream in) throws IOException { @@ -280,11 +278,10 @@ public void validate(InputStream in) throws IOException { throw new NutsNotFoundException(session, id, null, ex); } return new NutsDefaultContent( - session.io().path(tempFile), true, true); + NutsPath.of(tempFile,session), true, true); } else { try { - session.io().copy() - .setSession(session) + NutsCp.of(session) .from(helper.getStream(id, "artifact content", "retrieve", session)).to(localPath) .setValidator(in -> helper.checkSHA1Hash( id.builder().setFace(NutsConstants.QueryFaces.CONTENT_HASH).build(), @@ -296,7 +293,7 @@ public void validate(InputStream in) throws IOException { throw new NutsNotFoundException(session, id, null, ex); } return new NutsDefaultContent( - session.io().path(localPath), true, false); + NutsPath.of(localPath,session), true, false); } } @@ -312,7 +309,7 @@ public Iterator searchCore(final NutsIdFilter filter, String[] roots, Nu case GITHUB: { List> li = new ArrayList<>(); for (String root : roots) { - session.getTerminal().printProgress("%-8s %s", "browse", session.io().path(root).toCompressedForm()); + session.getTerminal().printProgress("%-8s %s", "browse", NutsPath.of(root,session).toCompressedForm()); if (root.endsWith("/*")) { String name = root.substring(0, root.length() - 2); li.add(FilesFoldersApi.createIterator(session, this, config.getLocation(true), name, filter, RemoteRepoApi.DIR_TEXT, session, Integer.MAX_VALUE, findModel)); @@ -325,7 +322,7 @@ public Iterator searchCore(final NutsIdFilter filter, String[] roots, Nu case DIR_LIST: { List> li = new ArrayList<>(); for (String root : roots) { - session.getTerminal().printProgress("%-8s %s", "browse", session.io().path(root).toCompressedForm()); + session.getTerminal().printProgress("%-8s %s", "browse", NutsPath.of(root,session).toCompressedForm()); if (root.endsWith("/*")) { String name = root.substring(0, root.length() - 2); li.add(FilesFoldersApi.createIterator(session, this, config.getLocation(true), name, filter, RemoteRepoApi.DIR_LIST, session, Integer.MAX_VALUE, findModel)); @@ -343,7 +340,7 @@ public Iterator searchCore(final NutsIdFilter filter, String[] roots, Nu true, session ); - final InputStream is = session.io().monitor().setSource(s).setSession(session).create(); + final InputStream is = NutsInputStreamMonitor.of(session).setSource(s).create(); return MavenUtils.of(session) .createArchetypeCatalogIterator(is, filter, true, session); } catch (UncheckedIOException ex) { @@ -393,9 +390,8 @@ public Iterator findVersionsImplGithub(NutsId id, NutsIdFilter idFilter, } catch (UncheckedIOException | NutsIOException ex) { throw new NutsNotFoundException(session, id, ex); } - List> info = session.elem().setContentType(NutsContentType.JSON).parse(new InputStreamReader(metadataStream), List.class); + List> info = NutsElements.of(session).json().parse(new InputStreamReader(metadataStream), List.class); if (info != null) { - NutsIdManager idMan = session.id(); for (Map version : info) { if ("dir".equals(version.get("type"))) { String versionName = (String) version.get("name"); @@ -405,7 +401,7 @@ public Iterator findVersionsImplGithub(NutsId id, NutsIdFilter idFilter, continue; } ret.add( - idMan.builder().setGroupId(groupId).setArtifactId(artifactId).setVersion(versionName).build() + NutsIdBuilder.of(session).setGroupId(groupId).setArtifactId(artifactId).setVersion(versionName).build() ); } @@ -444,7 +440,6 @@ public Iterator findVersionsImplMetadataXml(final NutsId id, NutsIdFilte } MavenMetadata info = MavenUtils.of(session).parseMavenMetaData(metadataStream, session); if (info != null) { - NutsIdManager idMan = session.id(); for (String version : info.getVersions()) { final NutsId nutsId = id.builder().setVersion(version).build(); @@ -452,7 +447,7 @@ public Iterator findVersionsImplMetadataXml(final NutsId id, NutsIdFilte continue; } ret.add( - idMan.builder().setGroupId(groupId).setArtifactId(artifactId).setVersion(version).build() + NutsIdBuilder.of(session).setGroupId(groupId).setArtifactId(artifactId).setVersion(version).build() ); } } @@ -506,7 +501,6 @@ public Iterator findVersionsImplFilesFolders(final NutsId id, NutsIdFilt FilesFoldersApi.Item[] all = FilesFoldersApi.getDirItems(true, false, versionApi, foldersFileUrl, session); if (all != null) { - NutsIdManager idMan = session.id(); for (FilesFoldersApi.Item version : all) { final NutsId nutsId = id.builder().setVersion(version.getName()).build(); @@ -514,7 +508,7 @@ public Iterator findVersionsImplFilesFolders(final NutsId id, NutsIdFilt continue; } ret.add( - idMan.builder().setGroupId(groupId).setArtifactId(artifactId).setVersion(version.getName()).build() + NutsIdBuilder.of(session).setGroupId(groupId).setArtifactId(artifactId).setVersion(version.getName()).build() ); } } @@ -526,7 +520,7 @@ private NutsRepository getLocalMavenRepo(NutsSession session) { if (nutsRepository.getRepositoryType().equals(NutsConstants.RepoTypes.MAVEN) && nutsRepository.config().getLocation(true) != null && nutsRepository.config().getLocation(true).equals( - Paths.get(session.io().path("~/.m2").builder().withWorkspaceBaseDir().build().toString()).toString() + Paths.get(NutsPath.of("~/.m2",session).builder().withWorkspaceBaseDir().build().toString()).toString() )) { return nutsRepository; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRepositoryFactoryComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRepositoryFactoryComponent.java index 9d9310256..555dfca18 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRepositoryFactoryComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRepositoryFactoryComponent.java @@ -23,36 +23,37 @@ */ package net.thevpc.nuts.runtime.standalone.bridges.maven; -import java.io.File; import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.repos.NutsRepositorySelector; +import net.thevpc.nuts.runtime.core.repos.NutsRepositoryType; +import net.thevpc.nuts.runtime.core.repos.NutsRepositoryURL; import net.thevpc.nuts.runtime.core.util.CoreIOUtils; -import net.thevpc.nuts.runtime.standalone.repos.RemoteRepoApi; import net.thevpc.nuts.runtime.standalone.repos.FilesFoldersApi; +import net.thevpc.nuts.runtime.standalone.repos.RemoteRepoApi; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.spi.NutsRepositoryFactoryComponent; +import net.thevpc.nuts.spi.NutsSupportLevelContext; +import java.io.File; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Map; -import net.thevpc.nuts.runtime.core.repos.NutsRepositorySelector; -import net.thevpc.nuts.runtime.core.repos.NutsRepositoryType; -import net.thevpc.nuts.runtime.core.repos.NutsRepositoryURL; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.spi.NutsSupportLevelContext; /** * Created by vpc on 1/15/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class MavenRepositoryFactoryComponent implements NutsRepositoryFactoryComponent { @Override public NutsAddRepositoryOptions[] getDefaultRepositories(NutsSession session) { return new NutsAddRepositoryOptions[]{ - NutsRepositorySelector.createRepositoryOptions(NutsRepositorySelector.parseSelection("maven-local"), - true, session), - NutsRepositorySelector.createRepositoryOptions(NutsRepositorySelector.parseSelection("maven-central"), - true, session) + NutsRepositorySelector.createRepositoryOptions(NutsRepositorySelector.parseSelection("maven-local"), + true, session), + NutsRepositorySelector.createRepositoryOptions(NutsRepositorySelector.parseSelection("maven-central"), + true, session) }; } @@ -88,9 +89,9 @@ public int getSupportLevel(NutsSupportLevelContext criteri return DEFAULT_SUPPORT; } if (nru.isHttp()) { - try (InputStream s = criteria.getSession().io().path(nru.getLocation() + "/nuts-repository.json") + try (InputStream s = NutsPath.of(nru.getLocation(), criteria.getSession()).resolve("nuts-repository.json") .setUserKind("nuts-repository.json").getInputStream()) { - Map m = criteria.getSession().elem().setContentType(NutsContentType.JSON) + Map m = NutsElements.of(criteria.getSession()).setContentType(NutsContentType.JSON) .parse(s, Map.class); if (m != null) { String type = (String) m.get("type"); @@ -113,9 +114,8 @@ public int getSupportLevel(NutsSupportLevelContext criteri criteria.getConstraints().setType("maven+dirtext"); return DEFAULT_SUPPORT; } - if (criteria.getSession().io().path( - location + "/archetype-catalog.xml" - ).setUserKind("archetype-catalog.xml").exists()) { + if (NutsPath.of(location, criteria.getSession()).resolve("archetype-catalog.xml") + .setUserKind("archetype-catalog.xml").exists()) { criteria.getConstraints().setType(NutsConstants.RepoTypes.MAVEN); return DEFAULT_SUPPORT; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRepositoryFolderHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRepositoryFolderHelper.java index af888a4cf..0ee7f7f58 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRepositoryFolderHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenRepositoryFolderHelper.java @@ -79,7 +79,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(MavenRepositoryFolderHelper.class); + LOG = NutsLogger.of(MavenRepositoryFolderHelper.class,session); } return LOG; } @@ -93,7 +93,7 @@ public NutsContent fetchContentImpl(NutsId id, Path localPath, NutsSession sessi Path cacheContent = getIdLocalFile(id, session); if (cacheContent != null && Files.exists(cacheContent)) { return new NutsDefaultContent( - session.io().path(cacheContent.toString()), true, false); + NutsPath.of(cacheContent,session), true, false); } return null; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenUtils.java index 60b1e8956..6156f18ef 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MavenUtils.java @@ -65,7 +65,7 @@ public class MavenUtils { private MavenUtils(NutsSession session) { this.session = session; - LOG = session.log().of(MavenUtils.class); + LOG = NutsLogger.of(MavenUtils.class,session); } public static MavenUtils of(NutsSession session) { @@ -103,7 +103,7 @@ public NutsDependency[] toNutsDependencies(PomDependency[] deps, NutsSession ses } public NutsId toNutsId(PomId d) { - return session.id().builder().setGroupId(d.getGroupId()).setArtifactId(d.getArtifactId()).setVersion(toNutsVersion(d.getVersion())).build(); + return NutsIdBuilder.of(session).setGroupId(d.getGroupId()).setArtifactId(d.getArtifactId()).setVersion(toNutsVersion(d.getVersion())).build(); } public NutsEnvCondition toCondition(NutsSession session, String os0, String arch0, PomProfileActivation a) { @@ -144,7 +144,7 @@ public NutsEnvCondition toCondition(NutsSession session, String os0, String arch if (arch != null) { ars = arch.id(); } - return session.descriptor().envConditionBuilder() + return NutsEnvConditionBuilder.of(session) .setOs(oss == null ? new String[0] : new String[]{oss}) .setArch(ars == null ? new String[0] : new String[]{ars}) .setPlatform(platform == null ? new String[0] : new String[]{platform}) @@ -193,7 +193,7 @@ public NutsDependency toNutsDependency(PomDependency d, NutsSession session, Pom } } } - return session.dependency().builder() + return NutsDependencyBuilder.of(session) .setGroupId(d.getGroupId()) .setArtifactId(d.getArtifactId()) .setClassifier(d.getClassifier()) @@ -278,7 +278,7 @@ public NutsDescriptor parsePomXml(InputStream stream, NutsFetchMode fetchMode, S LOG.with().session(session).level(Level.FINEST).verb(NutsLogVerb.SUCCESS).time(time) .log(NutsMessage.jstyle("{0}{1} parse pom {2}", fetchString, CoreStringUtils.alignLeft(repository == null ? "" : repository.getName(), 20), - session.text().ofStyled(urlDesc, NutsTextStyle.path()) + NutsTexts.of(session).ofStyled(urlDesc, NutsTextStyle.path()) )); String icons = pom.getProperties().get("nuts.icons"); @@ -302,12 +302,12 @@ public NutsDescriptor parsePomXml(InputStream stream, NutsFetchMode fetchMode, S } List props = new ArrayList<>(); for (Map.Entry e : pom.getProperties().entrySet()) { - props.add(session.descriptor().propertyBuilder().setName(e.getKey()) + props.add(NutsDescriptorPropertyBuilder.of(session).setName(e.getKey()) .setValue(e.getValue()).build()); } for (PomProfile profile : profiles) { for (Map.Entry e : profile.getProperties().entrySet()) { - props.add(session.descriptor().propertyBuilder() + props.add(NutsDescriptorPropertyBuilder.of(session) .setName(e.getKey()) .setValue(e.getValue()) .setCondition(toCondition(session, null, null, profile.getActivation())) @@ -320,7 +320,7 @@ public NutsDescriptor parsePomXml(InputStream stream, NutsFetchMode fetchMode, S } else { mavenCompilerTarget = ""; } - return session.descriptor().descriptorBuilder() + return NutsDescriptorBuilder.of(session) .setId(toNutsId(pom.getPomId())) .setParents(pom.getParent() == null ? new NutsId[0] : new NutsId[]{toNutsId(pom.getParent())}) .setPackaging(pom.getPackaging()) @@ -369,7 +369,7 @@ public String toNutsVersion(String version) { public NutsDescriptor parsePomXmlAndResolveParents(Path path, NutsFetchMode fetchMode, NutsRepository repository) throws IOException { try { - session.getTerminal().printProgress("%-8s %s", "parse", session.io().path(path.toString()).toCompressedForm()); + session.getTerminal().printProgress("%-8s %s", "parse", NutsPath.of(path,session).toCompressedForm()); try (InputStream is = Files.newInputStream(path)) { NutsDescriptor nutsDescriptor = parsePomXmlAndResolveParents(is, fetchMode, path.toString(), repository); if (nutsDescriptor.getId().getArtifactId() == null) { @@ -556,7 +556,7 @@ public DepsAndRepos loadDependenciesAndRepositoriesFromPomPath(String urlPath, N } public DepsAndRepos loadDependenciesAndRepositoriesFromPomUrl(String url, NutsSession session) { - session.getTerminal().printProgress("%-8s %s", "load", session.io().path(url).toCompressedForm()); + session.getTerminal().printProgress("%-8s %s", "load", NutsPath.of(url,session).toCompressedForm()); DepsAndRepos depsAndRepos = new DepsAndRepos(); // String repositories = null; // String dependencies = null; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MvnClient.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MvnClient.java index e30979848..13bb84488 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MvnClient.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/bridges/maven/MvnClient.java @@ -19,7 +19,7 @@ public enum Status { public MvnClient(NutsSession session) { this.session = session; - LOG=session.log().of(MvnClient.class); + LOG=NutsLogger.of(MvnClient.class,session); } public boolean get(NutsId id, String repoURL, NutsSession session) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultCustomCommandsModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultCustomCommandsModel.java index 382d40593..49f1b0dcf 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultCustomCommandsModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultCustomCommandsModel.java @@ -28,7 +28,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultCustomCommandsModel.class); + LOG = NutsLogger.of(DefaultCustomCommandsModel.class,session); } return LOG; } @@ -176,7 +176,7 @@ public boolean add(NutsCommandConfig command, NutsSession session) { .resetLine() .setDefaultValue(false) .forBoolean("override existing command %s ?", - session.text().ofStyled( + NutsTexts.of(session).ofStyled( command.getName(), NutsTextStyle.primary1() ) ).getBooleanValue()) { @@ -189,7 +189,7 @@ public boolean add(NutsCommandConfig command, NutsSession session) { defaultCommandFactory.installCommand(command, session); if (session.isPlainTrace()) { NutsPrintStream out = session.getTerminal().out(); - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); out.printf("%s command %s%n", text.ofStyled("install", NutsTextStyle.success()), text.ofStyled(command.getName(), NutsTextStyle.primary3())); @@ -218,7 +218,7 @@ public boolean update(NutsCommandConfig command, NutsSession session) { defaultCommandFactory.installCommand(command, session); if (session.isPlainTrace()) { NutsPrintStream out = session.getTerminal().out(); - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); out.printf("%s command %s%n", text.ofStyled("update ", NutsTextStyles.of(NutsTextStyle.success(), NutsTextStyle.underlined())), text.ofStyled(command.getName(), NutsTextStyle.primary3())); @@ -248,7 +248,7 @@ public void remove(String name, NutsSession session) { defaultCommandFactory.uninstallCommand(name, session); if (session.isPlainTrace()) { NutsPrintStream out = session.getTerminal().out(); - out.printf("%s command %s%n", "uninstall", session.text().ofStyled(name, NutsTextStyle.primary3())); + out.printf("%s command %s%n", "uninstall", NutsTexts.of(session).ofStyled(name, NutsTextStyle.primary3())); } } @@ -326,7 +326,7 @@ public NutsCommandFactoryConfig[] getFactories(NutsSession session) { public NutsWorkspaceCustomCommand find(String name, NutsId forId, NutsId forOwner, NutsSession session) { NutsWorkspaceCustomCommand a = find(name, session); if (a != null && a.getCommand() != null && a.getCommand().length > 0) { - NutsId i = session.id().parser().parse(a.getCommand()[0]); + NutsId i = NutsId.of(a.getCommand()[0],session); if (i != null && (forId == null || i.getShortName().equals(forId.getArtifactId()) diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIdLocation.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIdLocation.java deleted file mode 100755 index 3a2609428..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIdLocation.java +++ /dev/null @@ -1,89 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
- * - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== - */ -package net.thevpc.nuts.runtime.standalone.config; - -import net.thevpc.nuts.NutsBlankable; -import net.thevpc.nuts.NutsIdLocation; - -import java.util.Objects; - -public class DefaultNutsIdLocation implements NutsIdLocation { - private final String url; - private final String classifier; - private final String region; - - public DefaultNutsIdLocation(String url, String classifier, String region) { - this.url = url; - this.classifier = classifier; - this.region = region; - } - - @Override - public String getUrl() { - return url; - } - - @Override - public String getClassifier() { - return classifier; - } - - @Override - public String getRegion() { - return region; - } - - @Override - public boolean isBlank() { - if(!NutsBlankable.isBlank(url)){ - return false; - } - if(!NutsBlankable.isBlank(classifier)){ - return false; - } - if(!NutsBlankable.isBlank(region)){ - return false; - } - return true; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - DefaultNutsIdLocation that = (DefaultNutsIdLocation) o; - return Objects.equals(url, that.url) && - Objects.equals(classifier, that.classifier) && - Objects.equals(region, that.region) - ; - } - - @Override - public int hashCode() { - return Objects.hash(url, classifier, region); - } -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIdLocationBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIdLocationBuilder.java deleted file mode 100755 index d7d81ff58..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIdLocationBuilder.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
- * - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== - */ -package net.thevpc.nuts.runtime.standalone.config; - -import net.thevpc.nuts.NutsIdLocation; -import net.thevpc.nuts.NutsIdLocationBuilder; -import net.thevpc.nuts.NutsSession; - -import java.util.Objects; - -public class DefaultNutsIdLocationBuilder implements NutsIdLocationBuilder { - private String url; - private String classifier; - private String region; - private NutsSession session; - - public DefaultNutsIdLocationBuilder() { - } - public DefaultNutsIdLocationBuilder(NutsSession session) { - this.session=session; - } - - public DefaultNutsIdLocationBuilder(NutsIdLocation value,NutsSession session) { - this.session=session; - setUrl(value.getUrl()); - setClassifier(value.getClassifier()); - } - - @Override - public String getUrl() { - return url; - } - - @Override - public DefaultNutsIdLocationBuilder setUrl(String url) { - this.url = url; - return this; - } - - @Override - public String getClassifier() { - return classifier; - } - - @Override - public DefaultNutsIdLocationBuilder setClassifier(String classifier) { - this.classifier = classifier; - return this; - } - - @Override - public String getRegion() { - return region; - } - - @Override - public DefaultNutsIdLocationBuilder setRegion(String region) { - this.region = region; - return this; - } - - @Override - public NutsIdLocationBuilder clear() { - setUrl(null); - setClassifier(null); - return this; - } - - @Override - public NutsIdLocationBuilder set(NutsIdLocationBuilder value) { - if(value==null){ - clear(); - }else{ - setUrl(value.getUrl()); - setClassifier(value.getClassifier()); - } - return this; - } - - @Override - public NutsIdLocationBuilder set(NutsIdLocation value) { - if(value==null){ - clear(); - }else{ - setUrl(value.getUrl()); - setClassifier(value.getClassifier()); - } - return this; - } - - @Override - public NutsIdLocation build() { - return new DefaultNutsIdLocation(url, classifier,region); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - DefaultNutsIdLocationBuilder that = (DefaultNutsIdLocationBuilder) o; - return Objects.equals(url, that.url) && - Objects.equals(classifier, that.classifier)&& - Objects.equals(region, that.region) - ; - } - - @Override - public int hashCode() { - return Objects.hash(url, classifier,region); - } -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIndexStore.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIndexStore.java index b6e04f6dd..7536f7cd4 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIndexStore.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsIndexStore.java @@ -66,9 +66,9 @@ public Iterator searchVersions(NutsId id, NutsSession session) { try { NutsTransportConnection clientFacade = CoreIOUtils.getHttpClientFacade(session, URL); - Map[] array = session.elem().setContentType(NutsContentType.JSON).parse(new InputStreamReader(clientFacade.open()), Map[].class); + Map[] array = NutsElements.of(session).json().parse(new InputStreamReader(clientFacade.open()), Map[].class); return Arrays.stream(array) - .map(s -> session.id().parser().parse(s.get("stringId").toString())) + .map(s -> NutsId.of(s.get("stringId").toString(),session)) .collect(Collectors.toList()).iterator(); } catch (UncheckedIOException | NutsIOException e) { setInaccessible(); @@ -91,9 +91,9 @@ public Iterator search(NutsIdFilter filter, NutsSession session) { try { NutsTransportConnection clientFacade = CoreIOUtils.getHttpClientFacade(session, URL); - Map[] array = session.elem().setContentType(NutsContentType.JSON).parse(new InputStreamReader(clientFacade.open()), Map[].class); + Map[] array = NutsElements.of(session).json().parse(new InputStreamReader(clientFacade.open()), Map[].class); return Arrays.stream(array) - .map(s -> session.id().parser().parse(s.get("stringId").toString())) + .map(s -> NutsId.of(s.get("stringId").toString(),session)) .filter(filter != null ? new NutsIdFilterToNutsIdPredicate(filter, session) : NutsPredicates.always()) .iterator(); } catch (UncheckedIOException | NutsIOException e) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsPlatformModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsPlatformModel.java index eeddce26b..1cba32343 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsPlatformModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsPlatformModel.java @@ -66,12 +66,12 @@ public boolean add0(NutsPlatformLocation location, NutsSession session, boolean if (notify) { if (session.isPlainTrace()) { session.out().resetLine().printf("%s %s %s (%s) %s at %s%n", - session.text().ofStyled("install",NutsTextStyles.of(NutsTextStyle.success())), + NutsTexts.of(session).ofStyled("install",NutsTextStyles.of(NutsTextStyle.success())), location.getId().getShortName(), location.getPackaging(), location.getProduct(), - session.version().parser().parse(location.getVersion()), - session.io().path(location.getPath()) + NutsVersion.of(location.getVersion(),session), + NutsPath.of(location.getPath(),session) ); } NutsWorkspaceConfigManagerExt.of(session.config()) @@ -144,7 +144,7 @@ public NutsPlatformLocation findPlatform(NutsPlatformLocation location, NutsSess public NutsPlatformLocation findPlatformByVersion(NutsPlatformType type, NutsVersionFilter javaVersionFilter, final NutsSession session) { return findOnePlatform(type, - location -> javaVersionFilter == null || javaVersionFilter.acceptVersion(session.version().parser().parse(location.getVersion()), session), + location -> javaVersionFilter == null || javaVersionFilter.acceptVersion(NutsVersion.of(location.getVersion(),session), session), session); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceConfigManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceConfigManager.java index a2bbd2650..2a3f625ba 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceConfigManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceConfigManager.java @@ -27,17 +27,19 @@ import net.thevpc.nuts.runtime.core.config.NutsWorkspaceConfigManagerExt; import net.thevpc.nuts.runtime.core.model.CoreNutsWorkspaceOptions; import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; -import net.thevpc.nuts.runtime.standalone.solvers.NutsDependencySolvers; +import net.thevpc.nuts.runtime.standalone.solvers.NutsDependencySolverUtils; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; import net.thevpc.nuts.spi.NutsDependencySolver; import net.thevpc.nuts.spi.NutsDependencySolverFactory; import net.thevpc.nuts.spi.NutsIndexStoreFactory; +import net.thevpc.nuts.spi.NutsSystemTerminalBase; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Comparator; import java.util.Set; +import java.util.concurrent.ExecutorService; /** * @author thevpc @@ -130,7 +132,7 @@ public Set getAvailableArchetypes() { @Override public String resolveRepositoryPath(String repositoryLocation) { checkSession(); - return model.resolveRepositoryPath(repositoryLocation, session); + return model.resolveRepositoryPath(NutsPath.of(repositoryLocation,session), session); } @Override @@ -250,7 +252,7 @@ public String[] getDependencySolverNames() { @Override public int compare(String o1, String o2) { if(!o1.equals(o2)){ - String n = NutsDependencySolvers.resolveSolverName(session.getDependencySolver()); + String n = NutsDependencySolverUtils.resolveSolverName(session.getDependencySolver()); if(o1.equals(n)){ return -1; } @@ -270,4 +272,36 @@ public NutsDependencySolver createDependencySolver(String name) { return model.createDependencySolver(name, getSession()); } + @Override + public ExecutorService executorService() { + checkSession(); + return model.executorService(getSession()); + } + + @Override + public NutsSystemTerminal getSystemTerminal() { + checkSession(); + return model.getSystemTerminal(); + } + + @Override + public NutsWorkspaceConfigManager setSystemTerminal(NutsSystemTerminalBase terminal) { + checkSession(); + model.setSystemTerminal(terminal, session); + return this; + } + + @Override + public NutsSessionTerminal getDefaultTerminal() { + checkSession(); + return model.getTerminal(); + } + + @Override + public NutsWorkspaceConfigManager setDefaultTerminal(NutsSessionTerminal terminal) { + checkSession(); + model.setTerminal(terminal, session); + return this; + } + } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceConfigModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceConfigModel.java index 7292a058a..02caae9d3 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceConfigModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceConfigModel.java @@ -23,56 +23,71 @@ */ package net.thevpc.nuts.runtime.standalone.config; -import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; -import net.thevpc.nuts.runtime.core.model.DefaultNutsDefinition; -import net.thevpc.nuts.runtime.core.repos.NutsInstalledRepository; -import net.thevpc.nuts.runtime.core.repos.NutsRepositorySelector; import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.CoreNutsConstants; +import net.thevpc.nuts.runtime.core.NutsSupplierBase; +import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; +import net.thevpc.nuts.runtime.core.app.DefaultNutsWorkspaceLocationManager; import net.thevpc.nuts.runtime.core.config.NutsRepositoryConfigManagerExt; import net.thevpc.nuts.runtime.core.events.DefaultNutsWorkspaceEvent; +import net.thevpc.nuts.runtime.core.io.*; +import net.thevpc.nuts.runtime.core.model.CoreNutsWorkspaceOptions; +import net.thevpc.nuts.runtime.core.model.DefaultNutsDefinition; +import net.thevpc.nuts.runtime.core.repos.NutsInstalledRepository; +import net.thevpc.nuts.runtime.core.repos.NutsRepositorySelector; +import net.thevpc.nuts.runtime.core.terminals.*; +import net.thevpc.nuts.runtime.core.util.CoreBooleanUtils; +import net.thevpc.nuts.runtime.core.util.CoreIOUtils; +import net.thevpc.nuts.runtime.core.util.CoreNutsDependencyUtils; +import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; import net.thevpc.nuts.runtime.standalone.*; +import net.thevpc.nuts.runtime.standalone.boot.DefaultNutsBootManager; +import net.thevpc.nuts.runtime.standalone.boot.DefaultNutsBootModel; import net.thevpc.nuts.runtime.standalone.bridges.maven.MavenUtils; -import net.thevpc.nuts.runtime.core.model.CoreNutsWorkspaceOptions; -import net.thevpc.nuts.NutsLogVerb; -import net.thevpc.nuts.runtime.standalone.DefaultNutsWorkspace; import net.thevpc.nuts.runtime.standalone.config.compat.CompatUtils; import net.thevpc.nuts.runtime.standalone.config.compat.NutsVersionCompat; import net.thevpc.nuts.runtime.standalone.config.compat.v502.NutsVersionCompat502; import net.thevpc.nuts.runtime.standalone.config.compat.v506.NutsVersionCompat506; import net.thevpc.nuts.runtime.standalone.config.compat.v507.NutsVersionCompat507; -import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; +import net.thevpc.nuts.runtime.standalone.io.NutsPrintStreamNull; +import net.thevpc.nuts.runtime.standalone.io.NutsWorkspaceVarExpansionFunction; import net.thevpc.nuts.runtime.standalone.security.ReadOnlyNutsWorkspaceOptions; -import net.thevpc.nuts.runtime.standalone.solvers.NutsDependencySolvers; +import net.thevpc.nuts.runtime.standalone.solvers.NutsDependencySolverUtils; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; -import net.thevpc.nuts.runtime.core.util.CoreIOUtils; import net.thevpc.nuts.spi.*; -import java.io.File; -import java.io.IOException; -import java.io.PrintStream; -import java.io.UncheckedIOException; +import java.io.*; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.time.Instant; import java.util.*; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; import java.util.logging.Level; +import java.util.regex.Pattern; import java.util.stream.Collectors; -import net.thevpc.nuts.runtime.core.app.DefaultNutsWorkspaceLocationManager; -import net.thevpc.nuts.runtime.core.util.CoreBooleanUtils; -import net.thevpc.nuts.runtime.core.util.CoreNutsDependencyUtils; - /** * @author thevpc */ public class DefaultNutsWorkspaceConfigModel { + public static final Pattern MOSTLY_URL_PATTERN = Pattern.compile("([a-zA-Z][a-zA-Z0-9_-]+):.*"); public static final boolean NO_M2 = CoreBooleanUtils.getSysBoolNutsProperty("no-m2", false); + public final NutsPrintStream nullOut; private final DefaultNutsWorkspace ws; private final Map configUsers = new LinkedHashMap<>(); + private final NutsWorkspaceStoredConfig storedConfig = new NutsWorkspaceStoredConfigImpl(); + private final ClassLoader bootClassLoader; + private final URL[] bootClassWorldURLs; + private final NutsWorkspaceOptions options; + private final NutsWorkspaceInitInformation initOptions; + private final Function pathExpansionConverter; protected NutsWorkspaceConfigBoot storeModelBoot = new NutsWorkspaceConfigBoot(); protected NutsWorkspaceConfigApi storeModelApi = new NutsWorkspaceConfigApi(); protected NutsWorkspaceConfigRuntime storeModelRuntime = new NutsWorkspaceConfigRuntime(); @@ -81,23 +96,28 @@ public class DefaultNutsWorkspaceConfigModel { protected Map dependencySolvers; private NutsLogger LOG; private DefaultNutsWorkspaceCurrentConfig currentConfig; - private final NutsWorkspaceStoredConfig storedConfig = new NutsWorkspaceStoredConfigImpl(); - private final ClassLoader bootClassLoader; - private final URL[] bootClassWorldURLs; private boolean storeModelBootChanged = false; private boolean storeModelApiChanged = false; private boolean storeModelRuntimeChanged = false; private boolean storeModelSecurityChanged = false; private boolean storeModelMainChanged = false; - private final NutsWorkspaceOptions options; - private final NutsWorkspaceInitInformation initOptions; private long startCreateTime; private long endCreateTime; private NutsIndexStoreFactory indexStoreClientFactory; // private Set excludedRepositoriesSet = new HashSet<>(); private NutsStoreLocationsMap preUpdateConfigStoreLocations; private NutsRepositorySelector.SelectorList parsedBootRepositoriesList; -// private NutsRepositorySelector[] parsedBootRepositoriesArr; + // private NutsRepositorySelector[] parsedBootRepositoriesArr; + private ExecutorService executorService; + private NutsSessionTerminal terminal; + private NutsSystemTerminal systemTerminal; + private final WorkspaceSystemTerminalAdapter workspaceSystemTerminalAdapter; + // private final NutsLogger LOG; + private InputStream stdin = null; + private NutsPrintStream stdout; + private NutsPrintStream stderr; + private final List pathFactories = new ArrayList<>(); + private final DefaultNutsBootModel bootModel; public DefaultNutsWorkspaceConfigModel(final DefaultNutsWorkspace ws, NutsWorkspaceInitInformation initOptions) { this.ws = ws; @@ -105,7 +125,20 @@ public DefaultNutsWorkspaceConfigModel(final DefaultNutsWorkspace ws, NutsWorksp this.options = this.initOptions.getOptions(); this.bootClassLoader = initOptions.getClassWorldLoader() == null ? Thread.currentThread().getContextClassLoader() : initOptions.getClassWorldLoader(); this.bootClassWorldURLs = initOptions.getClassWorldURLs() == null ? null : Arrays.copyOf(initOptions.getClassWorldURLs(), initOptions.getClassWorldURLs().length); -// this.excludedRepositoriesSet = this.options.getExcludedRepositories() == null ? null : new HashSet<>(CoreStringUtils.split(Arrays.asList(this.options.getExcludedRepositories()), " ,;")); + workspaceSystemTerminalAdapter = new WorkspaceSystemTerminalAdapter(ws); + + this.pathExpansionConverter = new NutsWorkspaceVarExpansionFunction(NutsWorkspaceUtils.defaultSession(ws)); + this.bootModel = (DefaultNutsBootModel) ((DefaultNutsBootManager) ws.boot()).getModel(); + this.stdout = bootModel.stdout(); + this.stderr = bootModel.stderr(); + this.stdin = bootModel.stdin(); + this.nullOut = new NutsPrintStreamNull(bootModel.bootSession()); + addPathFactory(new FilePathFactory()); + addPathFactory(new ClasspathNutsPathFactory()); + addPathFactory(new URLPathFactory()); + addPathFactory(new NutsResourcePathFactory()); + + // this.excludedRepositoriesSet = this.options.getExcludedRepositories() == null ? null : new HashSet<>(CoreStringUtils.split(Arrays.asList(this.options.getExcludedRepositories()), " ,;")); } protected NutsLoggerOp _LOGOP(NutsSession session) { @@ -114,7 +147,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsWorkspaceConfigModel.class); + LOG = NutsLogger.of(DefaultNutsWorkspaceConfigModel.class, session); } return LOG; } @@ -152,9 +185,10 @@ public boolean save(boolean force, NutsSession session) { boolean ok = false; session.security().checkAllowed(NutsConstants.Permissions.SAVE, "save"); String apiVersionSpecificLocation = session.locations().getStoreLocation(session.getWorkspace().getApiId(), NutsStoreLocation.CONFIG); + NutsElements elem = NutsElements.of(session); if (force || storeModelBootChanged) { - Path file = Paths.get(session.locations().getWorkspaceLocation()).resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME); + Path file = session.locations().getWorkspaceLocation().toFile().resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME); storeModelBoot.setConfigVersion(DefaultNutsWorkspace.VERSION_WS_CONFIG_BOOT); if (storeModelBoot.getExtensions() != null) { for (NutsWorkspaceConfigBoot.ExtensionConfig extension : storeModelBoot.getExtensions()) { @@ -162,7 +196,7 @@ public boolean save(boolean force, NutsSession session) { extension.setConfigVersion(null); } } - session.elem().setContentType(NutsContentType.JSON).setValue(storeModelBoot) + elem.json().setValue(storeModelBoot) .setNtf(false).print(file); storeModelBootChanged = false; ok = true; @@ -180,7 +214,7 @@ public boolean save(boolean force, NutsSession session) { extension.setConfigVersion(null); } } - session.elem().setSession(session).setContentType(NutsContentType.JSON).setValue(storeModelSecurity) + elem.setSession(session).json().setValue(storeModelSecurity) .setNtf(false).print(file); storeModelSecurityChanged = false; ok = true; @@ -215,7 +249,7 @@ public boolean save(boolean force, NutsSession session) { item.setConfigVersion(null); } } - session.elem().setSession(session).setContentType(NutsContentType.JSON).setValue(storeModelMain) + elem.setSession(session).json().setValue(storeModelMain) .setNtf(false).print(file); storeModelMainChanged = false; ok = true; @@ -230,7 +264,7 @@ public boolean save(boolean force, NutsSession session) { item.setConfigVersion(null); } } - session.elem().setSession(session).setContentType(NutsContentType.JSON).setValue(storeModelApi) + elem.setSession(session).json().setValue(storeModelApi) .setNtf(false).print(afile); storeModelApiChanged = false; ok = true; @@ -240,7 +274,7 @@ public boolean save(boolean force, NutsSession session) { .resolve(NutsConstants.Folders.ID).resolve(session.locations().getDefaultIdBasedir(session.getWorkspace().getRuntimeId())); Path afile = runtimeVersionSpecificLocation.resolve(NutsConstants.Files.WORKSPACE_RUNTIME_CONFIG_FILE_NAME); storeModelRuntime.setConfigVersion(current().getApiVersion()); - session.elem().setSession(session).setContentType(NutsContentType.JSON).setValue(storeModelRuntime) + elem.setSession(session).json().setValue(storeModelRuntime) .setNtf(false).print(afile); storeModelRuntimeChanged = false; ok = true; @@ -279,7 +313,7 @@ public NutsWorkspaceBootConfig loadBootConfig(String _ws, boolean global, boolea lastConfigPath = NutsUtilPlatforms.getWorkspaceLocation(null, global, CoreNutsUtils.resolveValidWorkspaceName(effWorkspaceName)); - lastConfigLoaded = parseBootConfig(lastConfigPath, session); + lastConfigLoaded = parseBootConfig(NutsPath.of(lastConfigPath, session), session); defaultLocation = true; return new DefaultNutsWorkspaceBootConfig(session, _ws0, lastConfigPath, effWorkspaceName, defaultLocation, lastConfigLoaded); } else if (followLinks) { @@ -294,7 +328,7 @@ public NutsWorkspaceBootConfig loadBootConfig(String _ws, boolean global, boolea CoreNutsUtils.resolveValidWorkspaceName(_ws) ) : CoreIOUtils.getAbsolutePath(_ws); - NutsWorkspaceConfigBoot configLoaded = parseBootConfig(lastConfigPath, session); + NutsWorkspaceConfigBoot configLoaded = parseBootConfig(NutsPath.of(lastConfigPath, session), session); if (configLoaded == null) { //not loaded break; @@ -323,7 +357,7 @@ public NutsWorkspaceBootConfig loadBootConfig(String _ws, boolean global, boolea CoreNutsUtils.resolveValidWorkspaceName(_ws) ) : CoreIOUtils.getAbsolutePath(_ws); - lastConfigLoaded = parseBootConfig(lastConfigPath, session); + lastConfigLoaded = parseBootConfig(NutsPath.of(lastConfigPath, session), session); if (lastConfigLoaded == null) { return null; } @@ -338,7 +372,7 @@ public NutsWorkspaceOptionsBuilder optionsBuilder(NutsSession session) { public boolean isExcludedExtension(String extensionId, NutsWorkspaceOptions options, NutsSession session) { if (extensionId != null && options != null) { - NutsId pnid = session.id().parser().parse(extensionId); + NutsId pnid = NutsId.of(extensionId, session); String shortName = pnid.getShortName(); String artifactId = pnid.getArtifactId(); for (String excludedExtensionList : options.getExcludedExtensions()) { @@ -463,11 +497,13 @@ public Set getAvailableArchetypes(NutsSession session) { // String passphrase = getEnv(CoreSecurityUtils.ENV_KEY_PASSPHRASE, CoreSecurityUtils.DEFAULT_PASSPHRASE); // return CoreSecurityUtils.httpEncrypt(input, passphrase); // } - public String resolveRepositoryPath(String repositoryLocation, NutsSession session) { - String root = this.getRepositoriesRoot(session); - return Paths.get(session.io().path(repositoryLocation).builder() - .setBaseDir(root != null ? root : Paths.get(session.locations().getStoreLocation(NutsStoreLocation.CONFIG)) - .resolve(NutsConstants.Folders.REPOSITORIES).toString()) + public String resolveRepositoryPath(NutsPath repositoryLocation, NutsSession session) { + NutsPath root = this.getRepositoriesRoot(session); + return Paths.get(repositoryLocation.builder() + .setBaseDir(root != null ? root : + NutsPath.of( + Paths.get(session.locations().getStoreLocation(NutsStoreLocation.CONFIG)), session) + .resolve(NutsConstants.Folders.REPOSITORIES)) .build().toString()).toString(); } @@ -579,7 +615,7 @@ public void prepareBootApi(NutsId apiId, NutsId runtimeId, boolean force, NutsSe .setFailFast(false).setLatest(true).getResultIds().first(); } if (runtimeId == null) { - runtimeId = MavenUtils.of(session).resolveLatestMavenId(session.id().parser().parse(NutsConstants.Ids.NUTS_RUNTIME), + runtimeId = MavenUtils.of(session).resolveLatestMavenId(NutsId.of(NutsConstants.Ids.NUTS_RUNTIME, session), (rtVersion) -> rtVersion.startsWith(apiId.getVersion().getValue() + "."), session); } @@ -593,7 +629,7 @@ public void prepareBootApi(NutsId apiId, NutsId runtimeId, boolean force, NutsSe String javaOptions = getStoredConfigApi().getJavaOptions(); m.put("javaCommand", javaCommand); m.put("javaOptions", javaOptions); - session.elem().setContentType(NutsContentType.JSON).setValue(m) + NutsElements.of(session).json().setValue(m) .setNtf(false).print(apiConfigFile); } //downloadId(apiId, force, null, true, NutsIdType.API, session); @@ -637,7 +673,7 @@ public boolean loadWorkspace(NutsSession session) { } DefaultNutsWorkspaceCurrentConfig cconfig = new DefaultNutsWorkspaceCurrentConfig(ws).merge(_config, session); if (cconfig.getApiId() == null) { - cconfig.setApiId(session.id().parser().parse(NutsConstants.Ids.NUTS_API + "#" + initOptions.getApiVersion())); + cconfig.setApiId(NutsId.of(NutsConstants.Ids.NUTS_API + "#" + initOptions.getApiVersion(), session)); } if (cconfig.getRuntimeId() == null) { cconfig.setRuntimeId(initOptions.getRuntimeId() == null ? null : initOptions.getRuntimeId().toString(), session); @@ -668,7 +704,7 @@ public boolean loadWorkspace(NutsSession session) { NutsWorkspaceConfigMain mconfig = compat.parseMainConfig(session); if (options.isRecover() || options.isReset()) { //always reload boot resolved versions! - cconfig.setApiId(session.id().parser().parse(NutsConstants.Ids.NUTS_API + "#" + initOptions.getApiVersion())); + cconfig.setApiId(NutsId.of(NutsConstants.Ids.NUTS_API + "#" + initOptions.getApiVersion(), session)); cconfig.setRuntimeId(initOptions.getRuntimeId() == null ? null : initOptions.getRuntimeId().toString(), session); cconfig.setRuntimeBootDescriptor(initOptions.getRuntimeBootDescriptor()); cconfig.setExtensionBootDescriptors(initOptions.getExtensionBootDescriptors()); @@ -824,17 +860,17 @@ public NutsWorkspace getWorkspace() { return ws; } - public NutsDependencySolver createDependencySolver(String name,NutsSession session) { - NutsDependencySolverFactory c = getSolversMap(session).get(NutsDependencySolvers.resolveSolverName(name)); - if(c!=null){ + public NutsDependencySolver createDependencySolver(String name, NutsSession session) { + NutsDependencySolverFactory c = getSolversMap(session).get(NutsDependencySolverUtils.resolveSolverName(name)); + if (c != null) { return c.create(session); } - throw new NutsIllegalArgumentException(session,NutsMessage.cstyle("dependency solver not found %s",name)); + throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("dependency solver not found %s", name)); } private Map getSolversMap(NutsSession session) { - if(dependencySolvers==null) { - dependencySolvers=new LinkedHashMap<>(); + if (dependencySolvers == null) { + dependencySolvers = new LinkedHashMap<>(); for (NutsDependencySolverFactory nutsDependencySolver : session.extensions().createAllSupported(NutsDependencySolverFactory.class, null)) { dependencySolvers.put(nutsDependencySolver.getName(), nutsDependencySolver); } @@ -847,16 +883,22 @@ public NutsDependencySolverFactory[] getDependencySolvers(NutsSession session) { } - public String getRepositoriesRoot(NutsSession session) { - return Paths.get(session.locations().getStoreLocation(NutsStoreLocation.CONFIG)).resolve(NutsConstants.Folders.REPOSITORIES).toString(); + public NutsPath getRepositoriesRoot(NutsSession session) { + return NutsPath.of( + Paths.get(session.locations().getStoreLocation(NutsStoreLocation.CONFIG)).resolve(NutsConstants.Folders.REPOSITORIES), + session) + ; } - public String getTempRepositoriesRoot(NutsSession session) { - return Paths.get(session.locations().getStoreLocation(NutsStoreLocation.TEMP)).resolve(NutsConstants.Folders.REPOSITORIES).toString(); + public NutsPath getTempRepositoriesRoot(NutsSession session) { + return NutsPath.of( + Paths.get(session.locations().getStoreLocation(NutsStoreLocation.TEMP)).resolve(NutsConstants.Folders.REPOSITORIES) + , session + ); } public boolean isValidWorkspaceFolder(NutsSession session) { - Path file = Paths.get(session.locations().getWorkspaceLocation()).resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME); + Path file = session.locations().getWorkspaceLocation().toFile().resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME); return Files.isRegularFile(file); } @@ -864,7 +906,7 @@ public NutsAuthenticationAgent createAuthenticationAgent(String authenticationAg authenticationAgent = NutsUtilStrings.trim(authenticationAgent); NutsAuthenticationAgent supported = null; if (authenticationAgent.isEmpty()) { - supported = session.extensions().createSupported(NutsAuthenticationAgent.class, ""); + supported = session.extensions().createSupported(NutsAuthenticationAgent.class, true, ""); } else { List agents = session.extensions().createAllSupported(NutsAuthenticationAgent.class, authenticationAgent); for (NutsAuthenticationAgent agent : agents) { @@ -874,7 +916,7 @@ public NutsAuthenticationAgent createAuthenticationAgent(String authenticationAg } } if (supported == null) { - throw new NutsExtensionNotFoundException(session, NutsAuthenticationAgent.class, "AuthenticationAgent"); + throw new NutsExtensionNotFoundException(session, NutsAuthenticationAgent.class, authenticationAgent); } NutsWorkspaceUtils.setSession(supported, session); return supported; @@ -903,7 +945,7 @@ public NutsId createSdkId(String type, String version, NutsSession session) { public void onExtensionsPrepared(NutsSession session) { try { - indexStoreClientFactory = session.extensions().createSupported(NutsIndexStoreFactory.class, null); + indexStoreClientFactory = session.extensions().createSupported(NutsIndexStoreFactory.class, false, null); } catch (Exception ex) { // } @@ -1079,7 +1121,7 @@ public void prepareBootRuntimeOrExtension(NutsId id, boolean force, NutsIdType r m.put("bootRepositories", String.join(";", dd.repos)); } for (String dep : dd.deps) { - deps.add(session.id().parser().parse(dep)); + deps.add(NutsId.of(dep, session)); } } else { throw new NutsNotFoundException(session, id); @@ -1097,7 +1139,7 @@ public void prepareBootRuntimeOrExtension(NutsId id, boolean force, NutsIdType r } if (force || !Files.isRegularFile(configFile)) { - session.elem().setContentType(NutsContentType.JSON).setValue(m) + NutsElements.of(session).json().setValue(m) .setNtf(false).print(configFile); } // downloadId(id, force, (def != null && def.getContent().getPath() != null) ? def.getContent().getFilePath() : null, false, runtime,session); @@ -1112,12 +1154,12 @@ private boolean isFirstBoot() { private void downloadId(NutsId id, NutsIdType idType, NutsSession session) { NutsWorkspaceUtils.checkSession(ws, session); - List nutsIds = session.search().setInstallStatus(session.filters().installStatus().byDeployed(true)) + List nutsIds = session.search().setInstallStatus(NutsInstallStatusFilters.of(session).byDeployed(true)) .setId(id).setLatest(true).getResultIds().toList(); if (!nutsIds.isEmpty()) { return; } - nutsIds = session.search().setInstallStatus(session.filters().installStatus().byDeployed(false)) + nutsIds = session.search().setInstallStatus(NutsInstallStatusFilters.of(session).byDeployed(false)) .setId(id).setLatest(true).getResultIds().toList(); if (!nutsIds.isEmpty()) { session.install().setId(nutsIds.get(0)).run(); @@ -1127,53 +1169,100 @@ private void downloadId(NutsId id, NutsIdType idType, NutsSession session) { // and hence there is no repository to look from. // In that case we look in default repos on "first boot" if (isFirstBoot()) { - String idFileName = session.locations().getDefaultIdFilename(id.builder().setFaceContent().setPackaging("jar").build()); -// Path jarFile = Paths.get(session.locations().getStoreLocation(NutsStoreLocation.LIB)) -// .resolve(NutsConstants.Folders.ID).resolve(session.locations().getDefaultIdBasedir(id)) -// .resolve(idFileName); - - for (NutsRepositorySelector.Selection pp0 : resolveBootRepositoriesBootSelectionArray(session)) { - NutsAddRepositoryOptions opt = NutsRepositorySelector.createRepositoryOptions(pp0, false, session); - NutsPath pp = NutsPath.of(opt.getConfig() == null ? opt.getLocation() : opt.getConfig().getLocation(), session); - boolean copiedLocally = false; + boolean deployFromDefaultRepos=false; + if(deployFromDefaultRepos) { String tmp = null; try { - try { - tmp = session.io().tmp().createTempFile(idFileName).toString(); - session.io().copy().from(pp - .resolve(session.locations().getDefaultIdBasedir(id)) - .resolve(idFileName) - ).to(tmp).run(); - copiedLocally = true; - } catch (Exception ex) { - // - } - if (copiedLocally) { - NutsInstalledRepository ins = NutsWorkspaceExt.of(session.getWorkspace()).getInstalledRepository(); - NutsDescriptor descriptor = CoreIOUtils.resolveNutsDescriptorFromFileContent(Paths.get(tmp), null, session); - if (descriptor != null) { - DefaultNutsDefinition b = new DefaultNutsDefinition( - null, null, - descriptor.getId(), - descriptor, new NutsDefaultContent(NutsPath.of(tmp, session), true, true), - new DefaultNutsInstallInfo(descriptor.getId(), NutsInstallStatus.NONE, null, null, null, null, null, null, false, false), - idType, null, session - ); - ins.install(b, session); - return; + String idFileName = session.locations().getDefaultIdFilename(id.builder().setFaceContent().setPackaging("jar").build()); + for (NutsRepositorySelector.Selection pp0 : resolveBootRepositoriesBootSelectionArray(session)) { + NutsAddRepositoryOptions opt = NutsRepositorySelector.createRepositoryOptions(pp0, false, session); + NutsPath pp = NutsPath.of(opt.getConfig() == null ? opt.getLocation() : opt.getConfig().getLocation(), session); + boolean copiedLocally = false; + try { + if (tmp == null) { + tmp = NutsTmp.of(session).createTempFile(idFileName).toString(); + } + NutsPath srcPath = pp + .resolve(session.locations().getDefaultIdBasedir(id)) + .resolve(idFileName); + if(srcPath.exists()) { + NutsCp.of(session).from(srcPath).to(tmp).run(); + copiedLocally = true; + } + } catch (Exception ex) { + // + } + if (copiedLocally) { + if(deployToInstalledRepository(idType,Paths.get(tmp),session)) { + return; + } } } } finally { - if (copiedLocally) { + if (tmp != null) { NutsPath tp = NutsPath.of(tmp, session); - tp.delete(); + if (tp.exists()) { + tp.delete(); + } } } } + NutsClassLoaderNode n = searchBootNode(id, session); + if(n!=null){ + if(deployToInstalledRepository(idType, + NutsPath.of(n.getURL(),session).toFile() + ,session)) { + for (NutsClassLoaderNode d : n.getDependencies()) { + NutsId depId = NutsId.of(d.getId(), session); + downloadId(depId,CoreNutsUtils.detectIdType(depId,session), session); + } + return; + } + } } throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("unable to load %s", id)); } + private boolean deployToInstalledRepository(NutsIdType idType,Path tmp,NutsSession session){ + NutsInstalledRepository ins = NutsWorkspaceExt.of(session.getWorkspace()).getInstalledRepository(); + NutsDescriptor descriptor = CoreIOUtils.resolveNutsDescriptorFromFileContent(tmp, null, session); + if (descriptor != null) { + DefaultNutsDefinition b = new DefaultNutsDefinition( + null, null, + descriptor.getId(), + descriptor, new NutsDefaultContent(NutsPath.of(tmp, session), true, true), + new DefaultNutsInstallInfo(descriptor.getId(), NutsInstallStatus.NONE, null, null, null, null, null, null, false, false), + idType, null, session + ); + ins.install(b, session); + return true; + } + return false; + } + + private NutsClassLoaderNode searchBootNode(NutsId id,NutsSession session){ + NutsBootManager boot = session.boot(); + List all=new ArrayList(); + all.add(boot.getBootRuntimeClassLoaderNode()); + all.addAll(Arrays.asList(boot.getBootExtensionClassLoaderNode())); + return searchBootNode(id,all.toArray(new NutsClassLoaderNode[0])); + } + + private NutsClassLoaderNode searchBootNode(NutsId id,NutsClassLoaderNode[] into){ + for (NutsClassLoaderNode n : into) { + if(n!=null){ + if(id.getLongName().equals(n.getId())){ + return n; + } + } + NutsClassLoaderNode a = searchBootNode(id, n.getDependencies()); + if(a!=null){ + return a; + } + } + return null; + } + public void onPreUpdateConfig(String confName, NutsSession session) { // options = CoreNutsUtils.validate(options, ws); preUpdateConfigStoreLocations = new NutsStoreLocationsMap(currentConfig.getStoreLocations()); @@ -1202,7 +1291,7 @@ public void onPostUpdateConfig(String confName, NutsSession session) { private void onLoadWorkspaceError(Throwable ex, NutsSession session) { DefaultNutsWorkspaceConfigModel wconfig = this; - Path file = Paths.get(session.locations().getWorkspaceLocation()).resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME); + Path file = session.locations().getWorkspaceLocation().toFile().resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME); if (wconfig.isReadOnly()) { throw new UncheckedIOException("unable to load config file " + file, new IOException(ex)); } @@ -1253,14 +1342,14 @@ private NutsWorkspaceConfigBoot parseBootConfig(NutsSession session) { return parseBootConfig(session.locations().getWorkspaceLocation(), session); } - private NutsWorkspaceConfigBoot parseBootConfig(String path, NutsSession session) { - Path file = Paths.get(path).resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME); + private NutsWorkspaceConfigBoot parseBootConfig(NutsPath path, NutsSession session) { + Path file = path.toFile().resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME); byte[] bytes = CompatUtils.readAllBytes(file); if (bytes == null) { return null; } try { - Map a_config0 = session.elem().setContentType(NutsContentType.JSON).parse(bytes, Map.class); + Map a_config0 = NutsElements.of(session).json().parse(bytes, Map.class); String version = (String) a_config0.get("configVersion"); if (version == null) { version = (String) a_config0.get("createApiVersion"); @@ -1321,6 +1410,234 @@ public NutsWorkspaceConfigSecurity getStoreModelSecurity() { return storeModelSecurity; } + public ExecutorService executorService(NutsSession session) { + if (executorService == null) { + synchronized (this) { + if (executorService == null) { + executorService = session.boot().getBootOptions().getExecutorService(); + if (executorService == null) { + ThreadPoolExecutor executorService2 = (ThreadPoolExecutor) Executors.newCachedThreadPool(CoreNutsUtils.nutsDefaultThreadFactory); + executorService2.setKeepAliveTime(60, TimeUnit.SECONDS); + executorService2.setMaximumPoolSize(60); + executorService = executorService2; + } + } + } + } + return executorService; + } + + public NutsSystemTerminal createSystemTerminal(NutsTerminalSpec spec, NutsSession session) { + NutsSystemTerminalBase termb = session.extensions() + .setSession(session) + .createSupported(NutsSystemTerminalBase.class, true, spec); + return NutsSystemTerminal_of_NutsSystemTerminalBase(termb, session); + } + + public void enableRichTerm(NutsSession session) { + NutsSystemTerminal st = getSystemTerminal(); + if (st.isAutoCompleteSupported()) { + //that's ok + } else { + NutsId extId = NutsId.of("net.thevpc.nuts.ext:next-term#" + session.getWorkspace().getApiVersion(), session); + if (!session.config().isExcludedExtension(extId.toString(), session.boot().getBootOptions())) { + NutsWorkspaceExtensionManager extensions = session.extensions(); + extensions.setSession(session).loadExtension(extId); + NutsSystemTerminal systemTerminal = createSystemTerminal( + new NutsDefaultTerminalSpec() + .setAutoComplete(true), + session + ); + setSystemTerminal(systemTerminal, session); + if (getSystemTerminal().isAutoCompleteSupported()) { + _LOGOP(session).level(Level.FINE).verb(NutsLogVerb.SUCCESS) + .log(NutsMessage.jstyle("enable rich terminal")); + } else { + _LOGOP(session).level(Level.FINE).verb(NutsLogVerb.FAIL) + .log(NutsMessage.jstyle("unable to enable rich terminal")); + } + } else { + _LOGOP(session).level(Level.FINE).verb(NutsLogVerb.WARNING) + .log(NutsMessage.jstyle("enableRichTerm discarded; next-term is excluded.")); + } + } + } + + public NutsSystemTerminal getSystemTerminal() { + return systemTerminal; + } + + public NutsSessionTerminal getTerminal() { + return terminal; + } + + public void setTerminal(NutsSessionTerminal terminal, NutsSession session) { + NutsWorkspaceUtils.checkSession(ws, session); + if (terminal == null) { + terminal = createTerminal(session); + } + if (!(terminal instanceof UnmodifiableSessionTerminal)) { + terminal = new UnmodifiableSessionTerminal(terminal, session); + } + this.terminal = terminal; + } + + public NutsSessionTerminal createTerminal(InputStream in, NutsPrintStream out, NutsPrintStream err, NutsSession session) { + NutsSessionTerminal t = createTerminal(session); + if (in != null) { + t.setIn(in); + } + if (out != null) { + t.setOut(out); + } + if (err != null) { + t.setErr(err); + } + return t; + } + + public NutsSessionTerminal createTerminal(NutsSession session) { + return new DefaultNutsSessionTerminalFromSystem( + session, workspaceSystemTerminalAdapter + ); +// return createTerminal(null, session); + } + + private NutsSystemTerminal NutsSystemTerminal_of_NutsSystemTerminalBase(NutsSystemTerminalBase terminal, NutsSession session) { + if (terminal == null) { + throw new NutsExtensionNotFoundException(session, NutsSystemTerminalBase.class, "SystemTerminalBase"); + } + NutsSystemTerminal syst; + if ((terminal instanceof NutsSystemTerminal)) { + syst = (NutsSystemTerminal) terminal; + } else { + try { + syst = new DefaultSystemTerminal(terminal); + NutsWorkspaceUtils.setSession(syst, session); + } catch (Exception ex) { + _LOGOP(session).level(Level.FINEST).verb(NutsLogVerb.WARNING) + .log(NutsMessage.jstyle("unable to create system terminal : {0}", ex)); + DefaultNutsSystemTerminalBase b = new DefaultNutsSystemTerminalBase(); + NutsWorkspaceUtils.setSession(b, session); + syst = new DefaultSystemTerminal(b); + NutsWorkspaceUtils.setSession(syst, session); + } + } + return syst; + } + + public void setSystemTerminal(NutsSystemTerminalBase terminal, NutsSession session) { + if (terminal == null) { + throw new NutsExtensionNotFoundException(session, NutsSystemTerminalBase.class, null); + } + NutsSystemTerminal syst = NutsSystemTerminal_of_NutsSystemTerminalBase(terminal, session); + NutsSystemTerminal old = this.systemTerminal; + this.systemTerminal = syst; + + if (old != this.systemTerminal) { + NutsWorkspaceEvent event = null; + if (session != null) { + for (NutsWorkspaceListener workspaceListener : session.events().getWorkspaceListeners()) { + if (event == null) { + event = new DefaultNutsWorkspaceEvent(session, null, "systemTerminal", old, this.systemTerminal); + } + workspaceListener.onUpdateProperty(event); + } + } + } + } + + public InputStream stdin() { + return stdin == null ? bootModel.stdin() : stdin; + } + + public void setStdin(InputStream stdin) { + this.stdin = stdin; + } + + public NutsPrintStream stdout() { + return stdout; + } + + public void setStdout(NutsPrintStream stdout) { + this.stdout = stdout == null ? + + bootModel.stdout() : stdout; + } + + public NutsPrintStream stderr() { + return stderr; + } + + public void setStderr(NutsPrintStream stderr) { + this.stderr = stderr == null ? bootModel.stderr() : stderr; + } + + public void addPathFactory(NutsPathFactory f) { + if (f != null && !pathFactories.contains(f)) { + pathFactories.add(f); + } + } + + public void removePathFactory(NutsPathFactory f) { + pathFactories.remove(f); + } + + public NutsPath resolve(String path, NutsSession session, ClassLoader classLoader) { + if (classLoader == null) { + classLoader = Thread.currentThread().getContextClassLoader(); + } + // + ClassLoader finalClassLoader = classLoader; + NutsSupplier z = Arrays.stream(getPathFactories()) + .map(x -> { + try { + return x.createPath(path, session, finalClassLoader); + } catch (Exception ex) { + // + } + return null; + }) + .filter(x -> x != null && x.getLevel() > 0) + .max(Comparator.comparingInt(NutsSupplier::getLevel)) + .orElse(null); + NutsPathSPI s = z == null ? null : z.create(); + if (s != null) { + if (s instanceof NutsPath) { + return (NutsPath) s; + } + return new NutsPathFromSPI(s); + } + return null; + } + + public NutsPathFactory[] getPathFactories() { + return pathFactories.toArray(new NutsPathFactory[0]); + } + + public DefaultNutsBootModel getBootModel() { + return bootModel; + } + + public NutsPrintStream nullPrintStream() { + return nullOut; + //return createPrintStream(NullOutputStream.INSTANCE, NutsTerminalMode.FILTERED, session); + } + + private static class WorkspaceSystemTerminalAdapter extends AbstractSystemTerminalAdapter { + + private final NutsWorkspace workspace; + + public WorkspaceSystemTerminalAdapter(NutsWorkspace workspace) { + this.workspace = workspace; + } + + public NutsSystemTerminalBase getParent() { + return NutsWorkspaceUtils.defaultSession(workspace).config() + .getSystemTerminal(); + } + } + private class NutsWorkspaceStoredConfigImpl implements NutsWorkspaceStoredConfig { public NutsWorkspaceStoredConfigImpl() { @@ -1372,8 +1689,7 @@ public NutsId getApiId() { NutsSession ws = NutsWorkspaceUtils.defaultSession(DefaultNutsWorkspaceConfigModel.this.ws); return v == null ? null - : ws - .id().parser().parse(NutsConstants.Ids.NUTS_API + "#" + v); + : NutsId.of(NutsConstants.Ids.NUTS_API + "#" + v, ws); } @Override @@ -1381,8 +1697,8 @@ public NutsId getRuntimeId() { String v = getStoredConfigApi().getRuntimeId(); NutsSession ws = NutsWorkspaceUtils.defaultSession(DefaultNutsWorkspaceConfigModel.this.ws); return v == null ? null : v.contains("#") - ? ws.id().parser().parse(v) - : ws.id().parser().parse(NutsConstants.Ids.NUTS_RUNTIME + "#" + v); + ? NutsId.of(v, ws) + : NutsId.of(NutsConstants.Ids.NUTS_RUNTIME + "#" + v, ws); } @Override @@ -1416,4 +1732,85 @@ public boolean isGlobal() { } + private class URLPathFactory implements NutsPathFactory { + @Override + public NutsSupplier createPath(String path, NutsSession session, ClassLoader classLoader) { + NutsWorkspaceUtils.checkSession(getWorkspace(), session); + try { + URL url = new URL(path); + return new NutsSupplierBase(2) { + @Override + public NutsPathSPI create() { + return new URLPath(url, session); + } + }; + } catch (Exception ex) { + //ignore + } + return null; + } + } + + private class NutsResourcePathFactory implements NutsPathFactory { + @Override + public NutsSupplier createPath(String path, NutsSession session, ClassLoader classLoader) { + NutsWorkspaceUtils.checkSession(getWorkspace(), session); + try { + if (path.startsWith("nuts-resource:")) { + return new NutsSupplierBase(2) { + @Override + public NutsPathSPI create() { + return new NutsResourcePath(path, session); + } + }; + } + } catch (Exception ex) { + //ignore + } + return null; + } + } + + private class ClasspathNutsPathFactory implements NutsPathFactory { + @Override + public NutsSupplier createPath(String path, NutsSession session, ClassLoader classLoader) { + NutsWorkspaceUtils.checkSession(getWorkspace(), session); + try { + if (path.startsWith("classpath:")) { + return new NutsSupplierBase(2) { + @Override + public NutsPathSPI create() { + return new ClassLoaderPath(path, classLoader, session); + } + }; + } + } catch (Exception ex) { + //ignore + } + return null; + } + } + + private class FilePathFactory implements NutsPathFactory { + @Override + public NutsSupplier createPath(String path, NutsSession session, ClassLoader classLoader) { + NutsWorkspaceUtils.checkSession(getWorkspace(), session); + try { + if (MOSTLY_URL_PATTERN.matcher(path).matches()) { + return null; + } + Path value = Paths.get(path); + return new NutsSupplierBase(1) { + @Override + public NutsPathSPI create() { + return new FilePath(value, session); + } + }; + } catch (Exception ex) { + //ignore + } + return null; + } + } + } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceCurrentConfig.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceCurrentConfig.java index 71cdb828a..5b5d730eb 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceCurrentConfig.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceCurrentConfig.java @@ -89,15 +89,15 @@ public DefaultNutsWorkspaceCurrentConfig merge(NutsWorkspaceOptions c, NutsSessi public void setRuntimeId(String s, NutsSession session) { this.bootRuntime = s.contains("#") - ? session.id().parser().parse(s) - : session.id().parser().parse(NutsConstants.Ids.NUTS_RUNTIME + "#" + s); + ? NutsId.of(s,session) + : NutsId.of(NutsConstants.Ids.NUTS_RUNTIME + "#" + s,session); } public DefaultNutsWorkspaceCurrentConfig mergeRuntime(NutsWorkspaceOptions c, NutsSession session) { if (c.getRuntimeId() != null) { this.bootRuntime = c.getRuntimeId().contains("#") - ? session.id().parser().parse(c.getRuntimeId()) - : session.id().parser().parse(NutsConstants.Ids.NUTS_RUNTIME + "#" + c.getRuntimeId()); + ? NutsId.of(c.getRuntimeId(),session) + : NutsId.of(NutsConstants.Ids.NUTS_RUNTIME + "#" + c.getRuntimeId(),session); } // this.bootRuntimeDependencies = c.getRuntimeDependencies(); // this.bootExtensionDependencies = c.getExtensionDependencies(); @@ -111,7 +111,7 @@ public DefaultNutsWorkspaceCurrentConfig mergeRuntime(NutsWorkspaceOptions c, Nu return this; } - public DefaultNutsWorkspaceCurrentConfig build(String workspaceLocation, NutsSession session) { + public DefaultNutsWorkspaceCurrentConfig build(NutsPath workspaceLocation, NutsSession session) { if (storeLocationStrategy == null) { storeLocationStrategy = NutsStoreLocationStrategy.EXPLODED; } @@ -119,7 +119,7 @@ public DefaultNutsWorkspaceCurrentConfig build(String workspaceLocation, NutsSes repositoryStoreLocationStrategy = NutsStoreLocationStrategy.EXPLODED; } Map storeLocations = NutsUtilPlatforms.buildLocations(getStoreLocationLayout(), storeLocationStrategy, - getStoreLocations(), homeLocations, isGlobal(), workspaceLocation, + getStoreLocations(), homeLocations, isGlobal(), workspaceLocation.toString(), session ); this.effStoreLocationsMap.clear(); @@ -128,7 +128,7 @@ public DefaultNutsWorkspaceCurrentConfig build(String workspaceLocation, NutsSes effStoreLocationPath[i] = Paths.get(effStoreLocationsMap.get(NutsStoreLocation.values()[i])); } if (apiId == null) { - apiId = session.id().parser().parse(NutsConstants.Ids.NUTS_API + "#" + Nuts.getVersion()); + apiId = NutsId.of(NutsConstants.Ids.NUTS_API + "#" + Nuts.getVersion(),session); } if (storeLocationLayout == null) { storeLocationLayout = session.env().getOsFamily(); @@ -137,7 +137,7 @@ public DefaultNutsWorkspaceCurrentConfig build(String workspaceLocation, NutsSes } public DefaultNutsWorkspaceCurrentConfig merge(NutsWorkspaceConfigApi c, NutsSession session) { - NutsIdParser parser = session.id().parser(); + NutsIdParser parser = NutsIdParser.of(session); if (c.getApiVersion() != null) { this.apiId = parser.parse(NutsConstants.Ids.NUTS_API + "#" + c.getApiVersion()); } @@ -160,7 +160,7 @@ public DefaultNutsWorkspaceCurrentConfig merge(NutsWorkspaceConfigApi c, NutsSes public DefaultNutsWorkspaceCurrentConfig merge(NutsWorkspaceConfigRuntime c, NutsSession session) { if (c.getId() != null) { - this.bootRuntime = session.id().parser().parse(c.getId()); + this.bootRuntime = NutsId.of(c.getId(),session); } if (c.getDependencies() != null) { this.runtimeBootDescriptor = new NutsBootDescriptor( @@ -207,7 +207,7 @@ public DefaultNutsWorkspaceCurrentConfig merge(NutsWorkspaceConfigBoot c, NutsSe public DefaultNutsWorkspaceCurrentConfig merge(NutsBootConfig c, NutsSession session) { this.name = c.getName(); - NutsIdParser parser = session.id().parser(); + NutsIdParser parser = NutsIdParser.of(session); if (c.getApiVersion() != null) { this.apiId = parser.parse(NutsConstants.Ids.NUTS_API + "#" + c.getApiVersion()); } @@ -474,7 +474,7 @@ public DefaultNutsWorkspaceCurrentConfig setBootJavaOptions(String bootJavaOptio // public String getStoreLocation(String id, NutsStoreLocation folderType, NutsSession session) { - return getStoreLocation(session.id().parser().parse(id), folderType, session); + return getStoreLocation(NutsId.of(id,session), folderType, session); } // diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceEnvManagerModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceEnvManagerModel.java index a12f21576..13fc87e80 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceEnvManagerModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/DefaultNutsWorkspaceEnvManagerModel.java @@ -83,7 +83,7 @@ public DefaultNutsWorkspaceEnvManagerModel(NutsWorkspace ws, NutsWorkspaceInitIn } osDist = nip.parse(platformOsDist); platform = NutsJavaSdkUtils.of(session).createJdkId(System.getProperty("java.version"), session); - arch = session.id().parser().parse(System.getProperty("os.arch")); + arch = NutsId.of(System.getProperty("os.arch"),session); } @@ -241,7 +241,7 @@ protected NutsId[] getDesktopEnvironmentsXDGOrEmpty(NutsSession session) { ).toArray(new String[0]); String sd = _XDG_SESSION_DESKTOP.toLowerCase(); for (int i = 0; i < supportedSessions.length; i++) { - NutsIdBuilder nb = session.id().builder().setArtifactId(supportedSessions[i]); + NutsIdBuilder nb = NutsIdBuilder.of(session).setArtifactId(supportedSessions[i]); if ("kde".equals(sd)) { String _KDE_FULL_SESSION = System.getenv("KDE_FULL_SESSION"); String _KDE_SESSION_VERSION = System.getenv("KDE_SESSION_VERSION"); @@ -270,30 +270,30 @@ protected NutsId[] getDesktopEnvironmentsXDGOrEmpty(NutsSession session) { protected NutsId[] getDesktopEnvironments0(NutsSession session) { if (!isGraphicalDesktopEnvironment()) { return new NutsId[]{ - session.id().builder().setArtifactId(NutsDesktopEnvironmentFamily.WINDOWS_SHELL.id()).build() + NutsIdBuilder.of(session).setArtifactId(NutsDesktopEnvironmentFamily.WINDOWS_SHELL.id()).build() }; } switch (session.env().getOsFamily()) { case WINDOWS: { return new NutsId[]{ - session.id().builder().setArtifactId(NutsDesktopEnvironmentFamily.WINDOWS_SHELL.id()).build() + NutsIdBuilder.of(session).setArtifactId(NutsDesktopEnvironmentFamily.WINDOWS_SHELL.id()).build() }; } case MACOS: { return new NutsId[]{ - session.id().builder().setArtifactId(NutsDesktopEnvironmentFamily.MACOS_AQUA.id()).build() + NutsIdBuilder.of(session).setArtifactId(NutsDesktopEnvironmentFamily.MACOS_AQUA.id()).build() }; } case UNIX: case LINUX: { NutsId[] all = getDesktopEnvironmentsXDGOrEmpty(session); if (all.length == 0) { - return new NutsId[]{session.id().builder().setArtifactId(NutsDesktopEnvironmentFamily.UNKNOWN.id()).build()}; + return new NutsId[]{NutsIdBuilder.of(session).setArtifactId(NutsDesktopEnvironmentFamily.UNKNOWN.id()).build()}; } return all; } default: { - return new NutsId[]{session.id().builder().setArtifactId(NutsDesktopEnvironmentFamily.UNKNOWN.id()).build()}; + return new NutsId[]{NutsIdBuilder.of(session).setArtifactId(NutsDesktopEnvironmentFamily.UNKNOWN.id()).build()}; } } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/NutsPlatformLocationSelectComparator.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/NutsPlatformLocationSelectComparator.java index fde649baa..aafd72f7f 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/NutsPlatformLocationSelectComparator.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/NutsPlatformLocationSelectComparator.java @@ -20,8 +20,8 @@ public int compare(NutsPlatformLocation o1, NutsPlatformLocation o2) { if(x!=0){ return x; } - NutsVersion v1 = ws.version().parser().parse(o1.getVersion()); - NutsVersion v2 = ws.version().parser().parse(o2.getVersion()); + NutsVersion v1 = NutsVersion.of(o1.getVersion(),ws); + NutsVersion v2 = NutsVersion.of(o2.getVersion(),ws); x = (v1 == null || v2 == null) ? 0 : (v1 != null && v2 != null) ? v2.compareTo(v1) : v2 == null ? -1 : 1; if (x != 0) { return x; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/NutsSdkLocationComparator.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/NutsSdkLocationComparator.java index 5a3c5084d..6bd7a963d 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/NutsSdkLocationComparator.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/NutsSdkLocationComparator.java @@ -12,8 +12,8 @@ public NutsSdkLocationComparator(NutsSession session) { @Override public int compare(NutsPlatformLocation o1, NutsPlatformLocation o2) { - NutsVersion v1 = session.version().parser().parse(o1.getVersion()); - NutsVersion v2 = session.version().parser().parse(o2.getVersion()); + NutsVersion v1 = NutsVersion.of(o1.getVersion(),session); + NutsVersion v2 = NutsVersion.of(o2.getVersion(),session); int x = (v1 == null || v2 == null) ? 0 : (v1 != null && v2 != null) ? v1.compareTo(v2) : v2 == null ? 1 : -1; if (x != 0) { return x; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v502/NutsVersionCompat502.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v502/NutsVersionCompat502.java index 31828361d..ac96007e9 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v502/NutsVersionCompat502.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v502/NutsVersionCompat502.java @@ -23,7 +23,7 @@ public NutsWorkspaceConfigApi parseApiConfig(NutsSession session) { NutsWorkspaceConfigApi cc = new NutsWorkspaceConfigApi(); cc.setApiVersion(getApiVersion()); NutsWorkspaceConfigBoot502 c = parseConfig502(CompatUtils.readAllBytes( - Paths.get(session.locations().getWorkspaceLocation()) + session.locations().getWorkspaceLocation().toFile() .resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME)), session); if (c != null) { cc.setApiVersion(c.getBootApiVersion()); @@ -39,7 +39,7 @@ public NutsWorkspaceConfigRuntime parseRuntimeConfig(NutsSession session) { NutsWorkspaceConfigRuntime cc = new NutsWorkspaceConfigRuntime(); // cc.setApiVersion(getApiVersion()); NutsWorkspaceConfigBoot502 c = parseConfig502(CompatUtils.readAllBytes( - Paths.get(session.locations().getWorkspaceLocation()) + session.locations().getWorkspaceLocation().toFile() .resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME)), session); if (c != null) { cc.setDependencies(c.getBootRuntimeDependencies()); @@ -52,7 +52,7 @@ public NutsWorkspaceConfigRuntime parseRuntimeConfig(NutsSession session) { public NutsWorkspaceConfigSecurity parseSecurityConfig(NutsSession session) { NutsWorkspaceConfigSecurity cc = new NutsWorkspaceConfigSecurity(); NutsWorkspaceConfigBoot502 c = parseConfig502(CompatUtils.readAllBytes( - Paths.get(session.locations().getWorkspaceLocation()) + session.locations().getWorkspaceLocation().toFile() .resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME)), session); if (c != null) { // cc.setConfigVersion(???); @@ -68,7 +68,7 @@ public NutsWorkspaceConfigSecurity parseSecurityConfig(NutsSession session) { public NutsWorkspaceConfigMain parseMainConfig(NutsSession session) { NutsWorkspaceConfigMain cc = new NutsWorkspaceConfigMain(); NutsWorkspaceConfigBoot502 c = parseConfig502(CompatUtils.readAllBytes( - Paths.get(session.locations().getWorkspaceLocation()) + session.locations().getWorkspaceLocation().toFile() .resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME)), session); if (c != null) { c.setRepositories(CompatUtils.copyNutsRepositoryRefList(c.getRepositories())); @@ -81,7 +81,7 @@ public NutsWorkspaceConfigMain parseMainConfig(NutsSession session) { } private NutsWorkspaceConfigBoot502 parseConfig502(byte[] bytes, NutsSession session) { - return session.elem().setContentType(NutsContentType.JSON).parse(bytes, NutsWorkspaceConfigBoot502.class); + return NutsElements.of(session).json().parse(bytes, NutsWorkspaceConfigBoot502.class); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v506/NutsVersionCompat506.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v506/NutsVersionCompat506.java index 7f10c3762..73bada7a0 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v506/NutsVersionCompat506.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v506/NutsVersionCompat506.java @@ -23,7 +23,7 @@ public NutsWorkspaceConfigApi parseApiConfig(NutsSession session) { NutsWorkspaceConfigApi cc = new NutsWorkspaceConfigApi(); cc.setApiVersion(getApiVersion()); NutsWorkspaceConfigBoot506 c = parseConfig506(CompatUtils.readAllBytes( - Paths.get(session.locations().getWorkspaceLocation()) + session.locations().getWorkspaceLocation().toFile() .resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME))); if (c != null) { // cc.setConfigVersion(???); @@ -41,7 +41,7 @@ public NutsWorkspaceConfigRuntime parseRuntimeConfig(NutsSession session) { NutsWorkspaceConfigRuntime cc = new NutsWorkspaceConfigRuntime(); // cc.setApiVersion(getApiVersion()); NutsWorkspaceConfigBoot506 c = parseConfig506(CompatUtils.readAllBytes( - Paths.get(session.locations().getWorkspaceLocation()) + session.locations().getWorkspaceLocation().toFile() .resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME))); if (c != null) { // cc.setConfigVersion(???); @@ -59,7 +59,7 @@ public NutsWorkspaceConfigRuntime parseRuntimeConfig(NutsSession session) { public NutsWorkspaceConfigSecurity parseSecurityConfig(NutsSession session) { NutsWorkspaceConfigSecurity cc = new NutsWorkspaceConfigSecurity(); NutsWorkspaceConfigBoot506 c = parseConfig506(CompatUtils.readAllBytes( - Paths.get(session.locations().getWorkspaceLocation()) + session.locations().getWorkspaceLocation().toFile() .resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME))); if (c != null) { // cc.setConfigVersion(???); @@ -75,7 +75,7 @@ public NutsWorkspaceConfigSecurity parseSecurityConfig(NutsSession session) { public NutsWorkspaceConfigMain parseMainConfig(NutsSession session) { NutsWorkspaceConfigMain cc = new NutsWorkspaceConfigMain(); NutsWorkspaceConfigBoot506 c = parseConfig506(CompatUtils.readAllBytes( - Paths.get(session.locations().getWorkspaceLocation()) + session.locations().getWorkspaceLocation().toFile() .resolve(NutsConstants.Files.WORKSPACE_CONFIG_FILE_NAME))); if (c != null) { c.setRepositories(CompatUtils.copyNutsRepositoryRefList(c.getRepositories())); @@ -88,7 +88,7 @@ public NutsWorkspaceConfigMain parseMainConfig(NutsSession session) { } private NutsWorkspaceConfigBoot506 parseConfig506(byte[] bytes) { - return getSession().elem().setContentType(NutsContentType.JSON).parse(bytes, NutsWorkspaceConfigBoot506.class); + return NutsElements.of(getSession()).json().parse(bytes, NutsWorkspaceConfigBoot506.class); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v507/NutsVersionCompat507.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v507/NutsVersionCompat507.java index 2353e74fc..030a7b333 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v507/NutsVersionCompat507.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/config/compat/v507/NutsVersionCompat507.java @@ -20,7 +20,7 @@ public NutsWorkspaceConfigBoot parseConfig(byte[] bytes, NutsSession session) { } public NutsWorkspaceConfigBoot parseConfig507(byte[] bytes, NutsSession session) { - return bytes==null?null:session.elem().setContentType(NutsContentType.JSON).parse(bytes, NutsWorkspaceConfigBoot.class); + return bytes==null?null:NutsElements.of(session).json().parse(bytes, NutsWorkspaceConfigBoot.class); } @Override @@ -28,9 +28,9 @@ public NutsWorkspaceConfigApi parseApiConfig(NutsSession session) { Path path = Paths.get(session.locations().getStoreLocation(session.getWorkspace().getApiId(), NutsStoreLocation.CONFIG)) .resolve(NutsConstants.Files.WORKSPACE_API_CONFIG_FILE_NAME); byte[] bytes = CompatUtils.readAllBytes(path); - NutsWorkspaceConfigApi c = bytes==null?null:session.elem() + NutsWorkspaceConfigApi c = bytes==null?null:NutsElements.of(session) .setSession(session) - .setContentType(NutsContentType.JSON).parse(bytes, NutsWorkspaceConfigApi.class); + .json().parse(bytes, NutsWorkspaceConfigApi.class); if (c != null) { c.setApiVersion(getApiVersion()); } @@ -42,9 +42,9 @@ public NutsWorkspaceConfigRuntime parseRuntimeConfig(NutsSession session) { Path path = Paths.get(session.locations().getStoreLocation(session.getWorkspace().getRuntimeId(), NutsStoreLocation.CONFIG)) .resolve(NutsConstants.Files.WORKSPACE_RUNTIME_CONFIG_FILE_NAME); byte[] bytes = CompatUtils.readAllBytes(path); - NutsWorkspaceConfigRuntime c = bytes==null?null:session.elem() + NutsWorkspaceConfigRuntime c = bytes==null?null:NutsElements.of(session) .setSession(session) - .setContentType(NutsContentType.JSON).parse(bytes, NutsWorkspaceConfigRuntime.class); + .json().parse(bytes, NutsWorkspaceConfigRuntime.class); // if (c != null) { // c.setApiVersion(getApiVersion()); // } @@ -57,9 +57,9 @@ public NutsWorkspaceConfigSecurity parseSecurityConfig(NutsSession session) { .builder().setVersion(NutsConstants.Versions.RELEASE).build(), NutsStoreLocation.CONFIG)) .resolve(CoreNutsConstants.Files.WORKSPACE_SECURITY_CONFIG_FILE_NAME); byte[] bytes = CompatUtils.readAllBytes(path); - NutsWorkspaceConfigSecurity c = bytes==null?null:session.elem() + NutsWorkspaceConfigSecurity c = bytes==null?null:NutsElements.of(session) .setSession(session) - .setContentType(NutsContentType.JSON).parse(bytes, NutsWorkspaceConfigSecurity.class); + .json().parse(bytes, NutsWorkspaceConfigSecurity.class); return c; } @@ -71,9 +71,9 @@ public NutsWorkspaceConfigMain parseMainConfig(NutsSession session) { , NutsStoreLocation.CONFIG)) .resolve(CoreNutsConstants.Files.WORKSPACE_MAIN_CONFIG_FILE_NAME); byte[] bytes = CompatUtils.readAllBytes(path); - NutsWorkspaceConfigMain c = bytes==null?null:session.elem() + NutsWorkspaceConfigMain c = bytes==null?null:NutsElements.of(session) .setSession(session) - .setContentType(NutsContentType.JSON).parse(bytes, NutsWorkspaceConfigMain.class); + .json().parse(bytes, NutsWorkspaceConfigMain.class); return c; } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/AbstractSyncIProcessExecHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/AbstractSyncIProcessExecHelper.java index 89197f763..f488d38ea 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/AbstractSyncIProcessExecHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/AbstractSyncIProcessExecHelper.java @@ -19,7 +19,7 @@ public NutsSession getSession() { @Override public Future execAsync() { - return session.concurrent().executorService().submit(new Callable() { + return session.config().executorService().submit(new Callable() { @Override public Integer call() throws Exception { return exec(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/ClassloaderAwareRunnable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/ClassloaderAwareRunnable.java index 623153c42..b253adeb4 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/ClassloaderAwareRunnable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/ClassloaderAwareRunnable.java @@ -80,7 +80,7 @@ public Object getResult() { public void runAndWaitFor() throws Throwable { try { - getSession().concurrent().executorService().submit(this).get(); + getSession().config().executorService().submit(this).get(); } catch (InterruptedException ex) { setError(ex); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaExecutorComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaExecutorComponent.java index f0aac02f8..fc2c75d80 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaExecutorComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaExecutorComponent.java @@ -29,9 +29,7 @@ import net.thevpc.nuts.runtime.core.DefaultNutsClassLoader; import net.thevpc.nuts.runtime.core.util.*; import net.thevpc.nuts.runtime.standalone.ext.DefaultNutsWorkspaceExtensionManager; -import net.thevpc.nuts.spi.NutsExecutorComponent; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.spi.NutsSupportLevelContext; +import net.thevpc.nuts.spi.*; import java.io.File; import java.lang.reflect.InvocationTargetException; @@ -49,7 +47,7 @@ /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class JavaExecutorComponent implements NutsExecutorComponent { public static NutsId ID; @@ -74,7 +72,7 @@ public void dryExec(NutsExecutionContext executionContext) throws NutsExecutionE public int getSupportLevel(NutsSupportLevelContext nutsDefinition) { this.ws = nutsDefinition.getSession(); if (ID == null) { - ID = ws.id().parser().parse("net.thevpc.nuts.exec:java"); + ID = NutsId.of("net.thevpc.nuts.exec:java",ws); } String shortName = nutsDefinition.getConstraints().getId().getShortName(); //for executors @@ -96,13 +94,14 @@ public IProcessExecHelper execHelper(NutsExecutionContext executionContext) { // boolean inheritSystemIO=CoreCommonUtils.parseBoolean(String.valueOf(executionContext.getExecutorProperties().get("inheritSystemIO")),false); // final NutsWorkspace ws = executionContext.getWorkspace(); Path contentFile = def.getPath(); + NutsSession session = executionContext.getTraceSession(); final JavaExecutorOptions joptions = new JavaExecutorOptions( def, executionContext.isTemporary(), executionContext.getArguments(), executionContext.getExecutorArguments(), NutsBlankable.isBlank(executionContext.getCwd()) ? System.getProperty("user.dir") : executionContext.getCwd(), - executionContext.getTraceSession()/*.copy().setProgressOptions("none")*/); + session/*.copy().setProgressOptions("none")*/); final NutsSession execSession = executionContext.getExecSession(); switch (executionContext.getExecutionType()) { case EMBEDDED: { @@ -154,13 +153,13 @@ public IProcessExecHelper execHelper(NutsExecutionContext executionContext) { for (String s : joptions.getClassPathNidStrings()) { if (s.startsWith("net.thevpc.nuts:nuts#")) { String v = s.substring("net.thevpc.nuts:nuts#".length()); - nutsDependencyVersion = executionContext.getTraceSession().version().parser().parse(v); + nutsDependencyVersion = NutsVersion.of(v,session); } else { Pattern pp = Pattern.compile(".*[/\\\\]nuts-(?[0-9.]+)[.]jar"); Matcher mm = pp.matcher(s); if (mm.find()) { String v = mm.group("v"); - nutsDependencyVersion = executionContext.getTraceSession().version().parser().parse(v); + nutsDependencyVersion = NutsVersion.of(v,session); break; } } @@ -248,7 +247,7 @@ public IProcessExecHelper execHelper(NutsExecutionContext executionContext) { List xargs = new ArrayList<>(); List args = new ArrayList<>(); - NutsTextManager txt = execSession.text(); + NutsTexts txt = NutsTexts.of(session); xargs.add(txt.ofPlain(joptions.getJavaHome())); xargs.addAll( joptions.getJvmArgs().stream() @@ -264,7 +263,7 @@ public IProcessExecHelper execHelper(NutsExecutionContext executionContext) { // xargs.add(Dnuts_boot_args); // args.add(Dnuts_boot_args); // } - String jdb = executionContext.getTraceSession().boot().getCustomBootOption("jdb").getString(); + String jdb = session.boot().getCustomBootOption("jdb").getString(); if (jdb != null) { boolean suspend = true; int port = 5005; @@ -298,7 +297,7 @@ public IProcessExecHelper execHelper(NutsExecutionContext executionContext) { if (joptions.isJar()) { xargs.add(txt.ofPlain("-jar")); - xargs.add(executionContext.getTraceSession().id().formatter(def.getId()).format()); + xargs.add(def.getId().formatter().format()); args.add("-jar"); args.add(contentFile.toString()); @@ -324,7 +323,7 @@ public IProcessExecHelper execHelper(NutsExecutionContext executionContext) { .collect(Collectors.toList()) ); args.addAll(joptions.getApp()); - return new JavaProcessExecHelper(execSession, execSession, xargs, joptions, executionContext.getTraceSession(), executionContext, def, args, osEnv); + return new JavaProcessExecHelper(execSession, execSession, xargs, joptions, session, executionContext, def, args, osEnv); } @@ -346,7 +345,8 @@ public EmbeddedProcessExecHelper(NutsDefinition def, NutsSession session, JavaEx @Override public void dryExec() { - NutsTextManager text = getSession().text(); + NutsSession session = getSession(); + NutsTexts text = NutsTexts.of(session); List cmdLine = new ArrayList<>(); cmdLine.add("embedded-java"); cmdLine.add("-cp"); @@ -354,11 +354,11 @@ public void dryExec() { cmdLine.add(joptions.getMainClass()); cmdLine.addAll(joptions.getApp()); - getSession().out().printf("[dry] %s%n", + session.out().printf("[dry] %s%n", text.builder() .append("exec", NutsTextStyle.pale()) .append(" ") - .append(getSession().commandLine().create(cmdLine)) + .append(NutsCommandLine.of(cmdLine,session)) ); } @@ -551,7 +551,7 @@ public void dryExec() { out.println("\t\t " + xarg); // } } - String directory = NutsBlankable.isBlank(joptions.getDir()) ? null : ws.io().path(joptions.getDir()).builder().withAppBaseDir().build().toString(); + String directory = NutsBlankable.isBlank(joptions.getDir()) ? null : NutsPath.of(joptions.getDir(),ws).builder().withAppBaseDir().build().toString(); ProcessExecHelper.ofDefinition(def, args.toArray(new String[0]), osEnv, directory, executionContext.getExecutorProperties(), joptions.isShowCommand(), true, executionContext.getSleepMillis(), executionContext.isInheritSystemIO(), false, NutsBlankable.isBlank(executionContext.getRedirectOutputFile()) ? null : new File(executionContext.getRedirectOutputFile()), NutsBlankable.isBlank(executionContext.getRedirectInputFile()) ? null : new File(executionContext.getRedirectInputFile()), executionContext.getRunAs(), executionContext.getTraceSession(), execSession @@ -566,7 +566,7 @@ public int exec() { private ProcessExecHelper preExec() { if (joptions.isShowCommand() || CoreBooleanUtils.getSysBoolNutsProperty("show-command", false)) { NutsPrintStream out = execSession.out(); - out.printf("%s %n", ws.text().ofStyled("nuts-exec", NutsTextStyle.primary1())); + out.printf("%s %n", NutsTexts.of(ws).ofStyled("nuts-exec", NutsTextStyle.primary1())); for (int i = 0; i < xargs.size(); i++) { NutsString xarg = xargs.get(i); // if (i > 0 && xargs.get(i - 1).equals("--nuts-path")) { @@ -578,7 +578,7 @@ private ProcessExecHelper preExec() { // } } } - String directory = NutsBlankable.isBlank(joptions.getDir()) ? null : ws.io().path(joptions.getDir()).builder().withAppBaseDir().build().toString(); + String directory = NutsBlankable.isBlank(joptions.getDir()) ? null : NutsPath.of(joptions.getDir(),ws).builder().withAppBaseDir().build().toString(); return ProcessExecHelper.ofDefinition(def, args.toArray(new String[0]), osEnv, directory, executionContext.getExecutorProperties(), joptions.isShowCommand(), true, executionContext.getSleepMillis(), executionContext.isInheritSystemIO(), false, NutsBlankable.isBlank(executionContext.getRedirectOutputFile()) ? null : new File(executionContext.getRedirectOutputFile()), NutsBlankable.isBlank(executionContext.getRedirectInputFile()) ? null : new File(executionContext.getRedirectInputFile()), executionContext.getRunAs(), executionContext.getTraceSession(), execSession diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaExecutorOptions.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaExecutorOptions.java index 92dc3e03d..acf71b614 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaExecutorOptions.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaExecutorOptions.java @@ -56,9 +56,8 @@ public JavaExecutorOptions(NutsDefinition def, boolean tempId, String[] args, St this.execArgs = executorOptions; // List classPath0 = new ArrayList<>(); // List extraCp = new ArrayList<>(); - NutsIdFormat nutsIdFormat = session.id().formatter().setOmitRepository(true); //will accept all -- and - based options! - NutsCommandLine cmdLine = session.commandLine().create(getExecArgs()).setExpandSimpleOptions(false); + NutsCommandLine cmdLine = NutsCommandLine.of(getExecArgs(),session).setExpandSimpleOptions(false); NutsArgument a; List currentCP = new ArrayList<>(); while (cmdLine.hasNext()) { @@ -194,7 +193,7 @@ public JavaExecutorOptions(NutsDefinition def, boolean tempId, String[] args, St if (mainClass == null) { if (path != null) { //check manifest! - NutsExecutionEntry[] classes = session.apps().execEntries().parse(path); + NutsExecutionEntry[] classes = NutsExecutionEntries.of(session).parse(path); if (classes.length > 0) { mainClass = String.join(":", Arrays.stream(classes).map(NutsExecutionEntry::getName) @@ -203,7 +202,7 @@ public JavaExecutorOptions(NutsDefinition def, boolean tempId, String[] args, St } } } else if (!mainClass.contains(".")) { - NutsExecutionEntry[] classes = session.apps().execEntries().parse(path); + NutsExecutionEntry[] classes = NutsExecutionEntries.of(session).parse(path); List possibleClasses = Arrays.stream(classes).map(NutsExecutionEntry::getName) .collect(Collectors.toList()); String r = resolveMainClass(mainClass, possibleClasses); @@ -255,7 +254,7 @@ public JavaExecutorOptions(NutsDefinition def, boolean tempId, String[] args, St ) { throw new NutsExecutionException(session, NutsMessage.cstyle("multiple runnable classes detected : %s" + possibleClasses), 102); } - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); NutsTextBuilder msgString = text.builder(); msgString.append("multiple runnable classes detected - actually ") @@ -382,7 +381,7 @@ private void addCp(List classPath, String value) { } catch (MalformedURLException ex) { throw new IllegalArgumentException("invalid url " + url); } - classPath.add(new NutsClassLoaderNode("", url, true)); + classPath.add(new NutsClassLoaderNode("", url, true,true)); } } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaSourceExecutorComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaSourceExecutorComponent.java index c912202f6..8eccbb513 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaSourceExecutorComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/JavaSourceExecutorComponent.java @@ -25,7 +25,7 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.model.DefaultNutsDefinition; -import net.thevpc.nuts.spi.NutsExecutorComponent; +import net.thevpc.nuts.spi.*; import javax.tools.JavaCompiler; import javax.tools.ToolProvider; @@ -34,13 +34,11 @@ import net.thevpc.nuts.runtime.core.NutsWorkspaceExt; import net.thevpc.nuts.runtime.core.util.CoreArrayUtils; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.spi.NutsSupportLevelContext; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class JavaSourceExecutorComponent implements NutsExecutorComponent { public static NutsId ID; @@ -55,7 +53,7 @@ public NutsId getId() { public int getSupportLevel(NutsSupportLevelContext nutsDefinition) { this.ws = nutsDefinition.getSession(); if (ID == null) { - ID = ws.id().parser().parse("net.thevpc.nuts.exec:exec-java-src"); + ID = NutsId.of("net.thevpc.nuts.exec:exec-java-src",ws); } if ("java".equals(nutsDefinition.getConstraints().getDescriptor().getPackaging())) { return DEFAULT_SUPPORT + 1; @@ -70,20 +68,22 @@ public void dryExec(NutsExecutionContext executionContext) throws NutsExecutionE // JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); String folder = "__temp_folder"; NutsPrintStream out = executionContext.getTraceSession().out(); - out.println(executionContext.getTraceSession().text().ofStyled("compile", NutsTextStyle.primary4())); + out.println(NutsTexts.of(executionContext.getTraceSession()).ofStyled("compile", NutsTextStyle.primary4())); out.printf("%s%n", - executionContext.getTraceSession().commandLine().create( - "embedded-javac", - "-d", - "", - javaFile.toString() + NutsCommandLine.of( + new String[]{ + "embedded-javac", + "-d", + "", + javaFile.toString() + },executionContext.getTraceSession() ) ); JavaExecutorComponent cc = new JavaExecutorComponent(); NutsDefinition d = executionContext.getDefinition(); d = new DefaultNutsDefinition(d, executionContext.getTraceSession()); ((DefaultNutsDefinition) d).setContent(new NutsDefaultContent( - executionContext.getTraceSession().io().path(folder), + NutsPath.of(folder,executionContext.getTraceSession()), false, true )); @@ -113,8 +113,7 @@ public void exec(NutsExecutionContext executionContext) { Path javaFile = nutMainFile.getPath(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); NutsSession session = executionContext.getTraceSession(); - Path folder = session.io().tmp() - .setSession(session) + Path folder = NutsTmp.of(session) .createTempFolder("jj").toFile(); int res = compiler.run(null, null, null, "-d", folder.toString(), javaFile.toString()); if (res != 0) { @@ -124,7 +123,7 @@ public void exec(NutsExecutionContext executionContext) { NutsDefinition d = executionContext.getDefinition(); d = new DefaultNutsDefinition(d, session); ((DefaultNutsDefinition) d).setContent(new NutsDefaultContent( - session.io().path(folder.toString()), + NutsPath.of(folder,session), false, true )); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/ProcessExecutorComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/ProcessExecutorComponent.java index 01e780178..fc4c3f31d 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/ProcessExecutorComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/executors/ProcessExecutorComponent.java @@ -28,17 +28,15 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.util.ProcessExecHelper; import net.thevpc.nuts.runtime.bundles.io.IProcessExecHelper; -import net.thevpc.nuts.spi.NutsExecutorComponent; +import net.thevpc.nuts.spi.*; import java.util.*; import net.thevpc.nuts.runtime.core.util.CoreBooleanUtils; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.spi.NutsSupportLevelContext; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class ProcessExecutorComponent implements NutsExecutorComponent { public static NutsId ID; @@ -53,7 +51,7 @@ public NutsId getId() { public int getSupportLevel(NutsSupportLevelContext nutsDefinition) { this.ws=nutsDefinition.getSession(); if(ID==null){ - ID=ws.id().parser().parse("net.thevpc.nuts.exec:exec-native"); + ID=NutsId.of("net.thevpc.nuts.exec:exec-native",ws); } return DEFAULT_SUPPORT; } @@ -100,7 +98,8 @@ public IProcessExecHelper execHelper(NutsExecutionContext executionContext) { dir = execArgs[i].substring(arg.indexOf('=') + 1); } } - String directory = NutsBlankable.isBlank(dir) ? null : executionContext.getTraceSession().io().path(dir).builder().withAppBaseDir().build().toString(); + String directory = NutsBlankable.isBlank(dir) ? null : + NutsPath.of(dir,executionContext.getTraceSession()).builder().withAppBaseDir().build().toString(); return ProcessExecHelper.ofDefinition(nutMainFile, app.toArray(new String[0]), osEnv, directory, executionContext.getExecutorProperties(), showCommand, true, executionContext.getSleepMillis(), false, false, null, null, executionContext.getRunAs(), executionContext.getTraceSession(), executionContext.getExecSession() diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/ext/DefaultNutsWorkspaceExtensionManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/ext/DefaultNutsWorkspaceExtensionManager.java index 813c142be..fed4f409d 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/ext/DefaultNutsWorkspaceExtensionManager.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/ext/DefaultNutsWorkspaceExtensionManager.java @@ -30,7 +30,7 @@ public DefaultNutsWorkspaceExtensionModel getModel() { @Override public Set getCompanionIds() { NutsWorkspaceUtils.checkSession(model.getWorkspace(),getSession()); - NutsIdParser parser = session.id().parser(); + NutsIdParser parser = NutsIdParser.of(getSession()); return Collections.unmodifiableSet(new HashSet<>( Arrays.asList(parser.parse("net.thevpc.nuts.toolbox:nsh")) ) @@ -66,16 +66,16 @@ public , B> NutsServiceLoader createServiceLoad return model.createServiceLoader(serviceType, criteriaType, classLoader, session); } - public , V> T createSupported(Class serviceType, V criteriaType) { + public , V> T createSupported(Class serviceType, boolean required, V criteriaType) { checkSession(); - return model.createSupported(serviceType, criteriaType, session); + return model.createSupported(serviceType, criteriaType, required, session); } - @Override - public , V> T createSupported(Class serviceType, V criteriaType, Class[] constructorParameterTypes, Object[] constructorParameters) { - checkSession(); - return model.createSupported(serviceType, criteriaType, constructorParameterTypes, constructorParameters, session); - } +// @Override +// public , V> T createSupported(Class serviceType, V criteriaType, Class[] constructorParameterTypes, boolean required, Object[] constructorParameters) { +// checkSession(); +// return model.createSupported(serviceType, criteriaType, constructorParameterTypes, constructorParameters, required, session); +// } @Override public , V> List createAllSupported(Class serviceType, V criteriaType) { @@ -180,5 +180,4 @@ public T create(Class type, String name, Class[] argTypes, Object[] args) checkSession(); return model.createApiTypeInstance(type, name, argTypes, args,session); } - } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/ext/DefaultNutsWorkspaceExtensionModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/ext/DefaultNutsWorkspaceExtensionModel.java index 77865ede2..fcbe14d96 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/ext/DefaultNutsWorkspaceExtensionModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/ext/DefaultNutsWorkspaceExtensionModel.java @@ -85,7 +85,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsWorkspaceExtensionModel.class); + LOG = NutsLogger.of(DefaultNutsWorkspaceExtensionModel.class,session); } return LOG; } @@ -99,7 +99,7 @@ public void setExcludedExtensions(String[] excluded, NutsSession session) { if (excluded != null) { for (String ex : excluded) { for (String e : StringTokenizerUtils.split(ex, ",; ")) { - NutsId ee = session.id().parser().parse(e); + NutsId ee = NutsId.of(e,session); if (ee != null) { this.exclusions.add(ee.getShortName()); } @@ -124,7 +124,7 @@ public List findWorkspaceExtensions(String version, Nu //@Override public List findExtensions(String id, String extensionType, NutsSession session) { - return findExtensions(session.id().parser().setLenient(false).parse(id), extensionType, session); + return findExtensions(NutsId.of(id,session), extensionType, session); } // @Override @@ -141,7 +141,7 @@ public List findExtensions(NutsId id, String extension if (u != null) { NutsExtensionInformation[] s = new NutsExtensionInformation[0]; try (Reader rr = new InputStreamReader(NutsWorkspaceUtils.of(session).openURL(u))) { - s = session.elem().setContentType(NutsContentType.JSON).parse(rr, DefaultNutsExtensionInformation[].class); + s = NutsElements.of(session).json().parse(rr, DefaultNutsExtensionInformation[].class); } catch (IOException ex) { _LOGOP(session).level(Level.SEVERE).error(ex) .log(NutsMessage.jstyle("failed to parse NutsExtensionInformation from {0} : {1}", u, ex)); @@ -173,15 +173,14 @@ public List buildRegInfos(NutsSession session) { } public void onInitializeWorkspace(NutsWorkspaceInitInformation info, ClassLoader bootClassLoader, NutsSession session) { - //now will iterate over Extension classes to wire them ... objectFactory.discoverTypes( - session.id().setSession(session).parser().parse(info.getRuntimeBootDependencyNode().getId()), + NutsId.of(info.getRuntimeBootDependencyNode().getId(),session), info.getRuntimeBootDependencyNode().getURL(), bootClassLoader, session); for (NutsClassLoaderNode idurl : info.getExtensionBootDependencyNodes()) { objectFactory.discoverTypes( - session.id().setSession(session).parser().parse(idurl.getId()), + NutsId.of(idurl.getId(),session), idurl.getURL(), bootClassLoader, session); @@ -252,13 +251,13 @@ public , B> NutsServiceLoader createServiceLoad return new DefaultNutsServiceLoader(session, serviceType, criteriaType, classLoader); } - public , V> T createSupported(Class type, V supportCriteria, NutsSession session) { - return objectFactory.createSupported(type, supportCriteria, session); + public , V> T createSupported(Class type, V supportCriteria, boolean required, NutsSession session) { + return objectFactory.createSupported(type, supportCriteria, required, session); } - public , V> T createSupported(Class type, V supportCriteria, Class[] constructorParameterTypes, Object[] constructorParameters, NutsSession session) { - return objectFactory.createSupported(type, supportCriteria, constructorParameterTypes, constructorParameters, session); - } +// public , V> T createSupported(Class type, V supportCriteria, Class[] constructorParameterTypes, Object[] constructorParameters, boolean required, NutsSession session) { +// return objectFactory.createSupported(type, supportCriteria, constructorParameterTypes, constructorParameters, required, session); +// } public , V> List createAllSupported(Class type, V supportCriteria, NutsSession session) { return objectFactory.createAllSupported(type, supportCriteria, session); @@ -489,7 +488,7 @@ public NutsWorkspaceExtension wireExtension(NutsId id, NutsFetchCommand options) private boolean isLoadedClassPath(NutsDefinition file, NutsSession session) { //session = CoreNutsUtils.validateSession(session,ws); - if (file.getId().equalsShortId(session.id().parser().setLenient(false).parse(NutsConstants.Ids.NUTS_API))) { + if (file.getId().equalsShortId(NutsId.of(NutsConstants.Ids.NUTS_API,session))) { return true; } try { @@ -567,10 +566,7 @@ public List resolveComponentTypes(Class o) { // throw new ClassCastException(NutsComponent.class.getName()); // } public NutsSessionTerminal createTerminal(NutsTerminalSpec spec, NutsSession session) { - NutsSystemTerminalBase termb= createSupported(NutsSystemTerminalBase.class, spec, session); - if (termb == null) { - throw new NutsExtensionNotFoundException(session, NutsSystemTerminalBase.class, "TerminalBase"); - } + NutsSystemTerminalBase termb= createSupported(NutsSystemTerminalBase.class, spec, true, session); if (spec != null && spec.get("ignoreClass") != null && spec.get("ignoreClass").equals(termb.getClass())) { return null; } @@ -607,7 +603,7 @@ public String[] getExtensionRepositoryLocations(NutsId appId) { protected URL expandURL(String url, NutsSession session) { try { - url = session.io().path(url).builder().withWorkspaceBaseDir().build().toString(); + url = NutsPathBuilder.of(url,session).withWorkspaceBaseDir().build().toString(); if (CoreIOUtils.isPathHttp(url)) { return new URL(url); } @@ -778,6 +774,10 @@ public NutsWorkspace getWorkspace() { //TODO fix me! + public T createFirst(Class type,NutsSession session){ + return objectFactory.createFirst(type, session); + } + public T createApiTypeInstance(Class type,String name,Class[] argTypes,Object[] args,NutsSession session){ if(name==null || name.equals("")){ name="default"; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/gui/CoreNutsUtilGui.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/gui/CoreNutsUtilGui.java index 2f9095c31..2209a0e21 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/gui/CoreNutsUtilGui.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/gui/CoreNutsUtilGui.java @@ -3,7 +3,7 @@ import net.thevpc.nuts.Nuts; import net.thevpc.nuts.NutsMessage; import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsTextManager; +import net.thevpc.nuts.NutsTexts; import javax.swing.*; @@ -34,7 +34,7 @@ public static boolean isGraphicalDesktopEnvironment() { public static String inputString(NutsMessage message, NutsMessage title, NutsSession session) { try { - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); if (title == null) { title = NutsMessage.cstyle("Nuts Package Manager - %s", Nuts.getVersion()); } @@ -60,7 +60,7 @@ public static String inputPassword(NutsMessage message, NutsMessage title, NutsS if (message == null) { message = NutsMessage.plain(""); } - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); String messageString = text.toText(message).filteredText(); String titleString = text.toText(title).filteredText(); try { @@ -88,7 +88,7 @@ public static void showMessage(NutsMessage message, NutsMessage title, NutsSessi if (title == null) { title = NutsMessage.cstyle("Nuts Package Manager - %s", Nuts.getVersion()); } - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); String messageString = text.toText(message==null?"":message).filteredText(); String titleString = text.toText(title).filteredText(); try { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/index/NanoDBNutsIdSerializer.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/index/NanoDBNutsIdSerializer.java index 72abc5b28..2a06e129e 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/index/NanoDBNutsIdSerializer.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/index/NanoDBNutsIdSerializer.java @@ -23,7 +23,6 @@ public void write(NutsId obj, NanoDBOutputStream out) { @Override public NutsId read(NanoDBInputStream in) { - NutsIdParser parser = session.id().parser(); - return parser.parse(in.readUTF()); + return NutsId.of(in.readUTF(),session); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/installers/CommandForIdNutsInstallerComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/installers/CommandForIdNutsInstallerComponent.java index 5962ec6b1..517bfad4b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/installers/CommandForIdNutsInstallerComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/installers/CommandForIdNutsInstallerComponent.java @@ -107,7 +107,7 @@ public void uninstall(NutsExecutionContext executionContext, boolean deleteData) NutsWorkspaceUtils.of(executionContext.getTraceSession()).checkReadOnly(); NutsId id = executionContext.getDefinition().getId(); if ("jar".equals(executionContext.getDefinition().getDescriptor().getPackaging())) { - NutsExecutionEntry[] executionEntries = session.apps().execEntries().parse(executionContext.getDefinition().getPath()); + NutsExecutionEntry[] executionEntries = NutsExecutionEntries.of(session).parse(executionContext.getDefinition().getPath()); for (NutsExecutionEntry executionEntry : executionEntries) { if (executionEntry.isApp()) { // diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/installers/ZipInstallerComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/installers/ZipInstallerComponent.java index ce8b551d4..0cc2e7ba3 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/installers/ZipInstallerComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/installers/ZipInstallerComponent.java @@ -33,14 +33,12 @@ import net.thevpc.nuts.runtime.bundles.io.UnzipOptions; import net.thevpc.nuts.runtime.bundles.io.ZipUtils; import net.thevpc.nuts.runtime.core.model.DefaultNutsDefinition; -import net.thevpc.nuts.spi.NutsInstallerComponent; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.spi.NutsSupportLevelContext; +import net.thevpc.nuts.spi.*; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class ZipInstallerComponent implements NutsInstallerComponent { @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsIOLockAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsLocks.java similarity index 70% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsIOLockAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsLocks.java index a9de32be0..f41737853 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsIOLockAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsLocks.java @@ -1,6 +1,6 @@ package net.thevpc.nuts.runtime.standalone.io; -import net.thevpc.nuts.NutsIOLockAction; +import net.thevpc.nuts.NutsLocks; import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.NutsWorkspace; @@ -8,14 +8,15 @@ import java.nio.file.Path; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; -public abstract class AbstractNutsIOLockAction implements NutsIOLockAction { +public abstract class AbstractNutsLocks implements NutsLocks { private NutsWorkspace ws; private Object source; private Object resource; private NutsSession session; - public AbstractNutsIOLockAction(NutsWorkspace ws) { - this.ws = ws; + public AbstractNutsLocks(NutsSession session) { + this.session = session; + this.ws = session.getWorkspace(); } protected void checkSession() { @@ -33,25 +34,25 @@ public Object getResource() { } @Override - public NutsIOLockAction setSource(Object source) { + public NutsLocks setSource(Object source) { this.source=source; return this; } @Override - public NutsIOLockAction setResource(File source) { + public NutsLocks setResource(File source) { this.resource=source; return this; } @Override - public NutsIOLockAction setResource(Path source) { + public NutsLocks setResource(Path source) { this.resource=source; return this; } @Override - public NutsIOLockAction setResource(Object source) { + public NutsLocks setResource(Object source) { this.resource=source; return this; } @@ -62,7 +63,7 @@ public NutsSession getSession() { } @Override - public NutsIOLockAction setSession(NutsSession session) { + public NutsLocks setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(ws, session); return this; } @@ -70,4 +71,5 @@ public NutsIOLockAction setSession(NutsSession session) { public NutsWorkspace getWs() { return ws; } + } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsIODeleteAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsRm.java similarity index 76% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsIODeleteAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsRm.java index 6617a4421..307ff3700 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsIODeleteAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/AbstractNutsRm.java @@ -6,14 +6,15 @@ import java.nio.file.Path; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; -public abstract class AbstractNutsIODeleteAction implements NutsIODeleteAction { +public abstract class AbstractNutsRm implements NutsRm { private NutsWorkspace ws; private Object target; private NutsSession session; private boolean failFast; - public AbstractNutsIODeleteAction(NutsWorkspace ws) { - this.ws = ws; + public AbstractNutsRm(NutsSession session) { + this.session = session; + this.ws = session.getWorkspace(); } protected void checkSession() { @@ -26,7 +27,7 @@ public NutsSession getSession() { } @Override - public NutsIODeleteAction setSession(NutsSession session) { + public NutsRm setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(ws, session); return this; } @@ -41,7 +42,7 @@ public Object getTarget() { } @Override - public NutsIODeleteAction setTarget(Object target) { + public NutsRm setTarget(Object target) { NutsWorkspaceUtils.checkSession(ws, session); if (target == null) { this.target = null; @@ -57,13 +58,13 @@ public NutsIODeleteAction setTarget(Object target) { } @Override - public NutsIODeleteAction setTarget(File target) { + public NutsRm setTarget(File target) { this.target = target; return this; } @Override - public NutsIODeleteAction setTarget(Path target) { + public NutsRm setTarget(Path target) { this.target = target; return this; } @@ -74,7 +75,7 @@ public boolean isFailFast() { } @Override - public NutsIODeleteAction setFailFast(boolean failFast) { + public NutsRm setFailFast(boolean failFast) { this.failFast = failFast; return this; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultHttpTransportComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultHttpTransportComponent.java index 29f9b9d5a..7f7221de7 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultHttpTransportComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultHttpTransportComponent.java @@ -38,7 +38,7 @@ /** * Created by vpc on 1/21/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class DefaultHttpTransportComponent implements NutsTransportComponent { public static final NutsTransportComponent INSTANCE = new DefaultHttpTransportComponent(); @@ -79,7 +79,7 @@ public InputStream open() { @Override public NutsPath getPath() { - return session.io().path(url); + return NutsPath.of(url,session); } public InputStream upload(NutsTransportParamPart... parts) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOCompressAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsCompress.java similarity index 84% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOCompressAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsCompress.java index 5aaf65b62..97e3be219 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOCompressAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsCompress.java @@ -9,12 +9,12 @@ import net.thevpc.nuts.runtime.bundles.io.NutsStreamOrPath; import net.thevpc.nuts.runtime.core.util.CoreIOUtils; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.*; 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.ArrayList; import java.util.Arrays; @@ -26,11 +26,11 @@ /** * @author thevpc */ -public class DefaultNutsIOCompressAction implements NutsIOCompressAction { +public class DefaultNutsCompress implements NutsCompress { - private NutsLogger LOG; private final List sources = new ArrayList<>(); private final NutsWorkspace ws; + private NutsLogger LOG; private boolean safe = true; private boolean logProgress = false; private NutsStreamOrPath target; @@ -39,14 +39,14 @@ public class DefaultNutsIOCompressAction implements NutsIOCompressAction { private NutsProgressFactory progressMonitorFactory; private String format = "zip"; - public DefaultNutsIOCompressAction(NutsWorkspace ws) { - this.ws = ws; + public DefaultNutsCompress(NutsSession session) { + this.session = session; + this.ws = session.getWorkspace(); } - protected NutsLogger _LOG(NutsSession session) { - if (LOG == null) { - LOG = session.log().of(DefaultNutsIOCompressAction.class); - } - return LOG; + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; } private static String concatPath(String a, String b) { @@ -65,6 +65,13 @@ private static String concatPath(String a, String b) { } } + protected NutsLogger _LOG(NutsSession session) { + if (LOG == null) { + LOG = NutsLogger.of(DefaultNutsCompress.class,session); + } + return LOG; + } + private void checkSession() { NutsWorkspaceUtils.checkSession(ws, session); } @@ -87,7 +94,7 @@ public void runZip() { if (this.target.isPath()) { Path tempPath = null; if (isSafe()) { - tempPath = session.io().tmp() + tempPath = NutsTmp.of(session) .createTempFile("zip").toFile(); } if (this.target.isPath()) { @@ -214,7 +221,7 @@ private void addFileToZip(String path, Item srcFile, ZipOutputStream zip, boolea } @Override - public NutsIOCompressAction setFormatOption(String option, Object value) { + public NutsCompress setFormatOption(String option, Object value) { return this; } @@ -229,7 +236,7 @@ public String getFormat() { } @Override - public NutsIOCompressAction setFormat(String format) { + public NutsCompress setFormat(String format) { checkSession(); if (NutsBlankable.isBlank(format)) { format = "zip"; @@ -253,23 +260,15 @@ public List getSources() { return (List) sources; } - @Override - public NutsIOCompressAction addSource(NutsPath source) { - if (source != null) { - this.sources.add(NutsStreamOrPath.of(source)); - } - return this; - } - - public NutsIOCompressAction addSource(String source) { + public NutsCompress addSource(String source) { if (source != null) { - this.sources.add(NutsStreamOrPath.of(session.io().path(source))); + this.sources.add(NutsStreamOrPath.of(NutsPath.of(source, session))); } return this; } @Override - public NutsIOCompressAction addSource(InputStream source) { + public NutsCompress addSource(InputStream source) { if (source == null) { checkSession(); throw new NutsIllegalArgumentException(session, NutsMessage.plain("null source")); @@ -279,32 +278,40 @@ public NutsIOCompressAction addSource(InputStream source) { } @Override - public NutsIOCompressAction addSource(File source) { + public NutsCompress addSource(File source) { if (source == null) { checkSession(); throw new NutsIllegalArgumentException(session, NutsMessage.plain("null source")); } - this.sources.add(NutsStreamOrPath.of(session.io().path(source))); + this.sources.add(NutsStreamOrPath.of(NutsPath.of(source,session))); return this; } @Override - public NutsIOCompressAction addSource(Path source) { + public NutsCompress addSource(Path source) { if (source == null) { checkSession(); throw new NutsIllegalArgumentException(session, NutsMessage.plain("null source")); } - this.sources.add(NutsStreamOrPath.of(session.io().path(source))); + this.sources.add(NutsStreamOrPath.of(NutsPath.of(source,session))); return this; } @Override - public NutsIOCompressAction addSource(URL source) { + public NutsCompress addSource(URL source) { if (source == null) { checkSession(); throw new NutsIllegalArgumentException(session, NutsMessage.plain("null source")); } - this.sources.add(NutsStreamOrPath.of(session.io().path(source))); + this.sources.add(NutsStreamOrPath.of(NutsPath.of(source,session))); + return this; + } + + @Override + public NutsCompress addSource(NutsPath source) { + if (source != null) { + this.sources.add(NutsStreamOrPath.of(source)); + } return this; } @@ -314,7 +321,7 @@ public Object getTarget() { } @Override - public NutsIOCompressAction setTarget(OutputStream target) { + public NutsCompress setTarget(OutputStream target) { if (target == null) { this.target = null; } else { @@ -324,67 +331,67 @@ public NutsIOCompressAction setTarget(OutputStream target) { } @Override - public NutsIOCompressAction setTarget(NutsPath target) { + public NutsCompress setTarget(Path target) { if (target == null) { this.target = null; } else { - this.target = NutsStreamOrPath.of(target); + this.target = NutsStreamOrPath.of(NutsPath.of(target,session)); } return this; } @Override - public NutsIOCompressAction setTarget(Path target) { + public NutsCompress setTarget(File target) { if (target == null) { this.target = null; } else { - this.target = NutsStreamOrPath.of(session.io().path(target)); + this.target = NutsStreamOrPath.of(NutsPath.of(target,session)); } return this; } @Override - public NutsIOCompressAction setTarget(File target) { + public NutsCompress setTarget(String target) { if (target == null) { this.target = null; } else { - this.target = NutsStreamOrPath.of(session.io().path(target)); + this.target = NutsStreamOrPath.of(NutsPath.of(target,session)); } return this; } @Override - public NutsIOCompressAction setTarget(String target) { + public NutsCompress setTarget(NutsPath target) { if (target == null) { this.target = null; } else { - this.target = NutsStreamOrPath.of(session.io().path(target)); + this.target = NutsStreamOrPath.of(target); } return this; } @Override - public NutsIOCompressAction to(NutsPath target) { + public NutsCompress to(NutsPath target) { return setTarget(target); } @Override - public NutsIOCompressAction to(OutputStream target) { + public NutsCompress to(OutputStream target) { return setTarget(target); } @Override - public NutsIOCompressAction to(String target) { + public NutsCompress to(String target) { return setTarget(target); } @Override - public NutsIOCompressAction to(Path target) { + public NutsCompress to(Path target) { return setTarget(target); } @Override - public NutsIOCompressAction to(File target) { + public NutsCompress to(File target) { return setTarget(target); } @@ -394,13 +401,13 @@ public NutsSession getSession() { } @Override - public NutsIOCompressAction setSession(NutsSession session) { + public NutsCompress setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(ws, session); return this; } @Override - public NutsIOCompressAction run() { + public NutsCompress run() { checkSession(); switch (getFormat()) { case "zip": @@ -422,7 +429,7 @@ public boolean isLogProgress() { } @Override - public DefaultNutsIOCompressAction setLogProgress(boolean value) { + public DefaultNutsCompress setLogProgress(boolean value) { this.logProgress = value; return this; } @@ -446,7 +453,7 @@ public NutsProgressFactory getProgressMonitorFactory() { * @since 0.5.8 */ @Override - public NutsIOCompressAction setProgressMonitorFactory(NutsProgressFactory value) { + public NutsCompress setProgressMonitorFactory(NutsProgressFactory value) { this.progressMonitorFactory = value; return this; } @@ -459,7 +466,7 @@ public NutsIOCompressAction setProgressMonitorFactory(NutsProgressFactory value) * @since 0.5.8 */ @Override - public NutsIOCompressAction setProgressMonitor(NutsProgressMonitor value) { + public NutsCompress setProgressMonitor(NutsProgressMonitor value) { this.progressMonitorFactory = value == null ? null : new SingletonNutsInputStreamProgressFactory(value); return this; } @@ -479,7 +486,7 @@ public boolean isSafe() { } @Override - public NutsIOCompressAction setSafe(boolean value) { + public NutsCompress setSafe(boolean value) { this.safe = value; return this; } @@ -490,7 +497,7 @@ public boolean isSkipRoot() { } @Override - public NutsIOCompressAction setSkipRoot(boolean value) { + public NutsCompress setSkipRoot(boolean value) { this.skipRoot = true; return this; } @@ -510,14 +517,14 @@ public boolean isDirectory() { private Item[] list() { if (o.isPath()) { NutsPath p = o.getPath(); - return Arrays.stream(p.getChildren()).map(x->new Item(NutsStreamOrPath.of(x))) + return Arrays.stream(p.getChildren()).map(x -> new Item(NutsStreamOrPath.of(x))) .toArray(Item[]::new); } return new Item[0]; } public InputStream open() { - if(o.isInputStream()){ + if (o.isInputStream()) { return o.getInputStream(); } return o.getPath().getInputStream(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOCopyAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsCp.java similarity index 86% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOCopyAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsCp.java index 333714b99..cd4d7158b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOCopyAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsCp.java @@ -12,6 +12,7 @@ import net.thevpc.nuts.runtime.core.util.CoreIOUtils; import net.thevpc.nuts.runtime.standalone.io.progress.DefaultNutsProgressEvent; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.*; import java.net.URL; @@ -23,7 +24,7 @@ /** * @author thevpc */ -public class DefaultNutsIOCopyAction implements NutsIOCopyAction { +public class DefaultNutsCp implements NutsCp { private NutsLogger LOG; @@ -42,8 +43,14 @@ public class DefaultNutsIOCopyAction implements NutsIOCopyAction { private Interruptible interruptibleInstance; private NutsWorkspace ws; - public DefaultNutsIOCopyAction(NutsWorkspace ws) { - this.ws = ws; + public DefaultNutsCp(NutsSession session) { + this.session = session; + this.ws = session.getWorkspace(); + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; } private static Path transformPath(Path f, Path sourceBase, Path targetBase) { @@ -66,7 +73,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsIOCopyAction.class); + LOG = NutsLogger.of(DefaultNutsCp.class,session); } return LOG; } @@ -80,87 +87,87 @@ public Object getSource() { return source; } -// public DefaultNutsIOCopyAction setSource(Object source) { +// public DefaultNutsCp setSource(Object source) { // this.source = _input().of(source); // return this; // } @Override - public NutsIOCopyAction from(byte[] source) { + public NutsCp from(byte[] source) { return setSource(source); } @Override - public NutsIOCopyAction setSource(byte[] source) { + public NutsCp setSource(byte[] source) { this.source = source==null?null:NutsStreamOrPath.of(new ByteArrayInputStream(source)); return this; } @Override - public NutsIOCopyAction setSource(NutsPath source) { + public NutsCp setSource(NutsPath source) { this.source = source==null?null:NutsStreamOrPath.of(source); return this; } @Override - public NutsIOCopyAction setSource(InputStream source) { + public NutsCp setSource(InputStream source) { this.source = source==null?null:NutsStreamOrPath.of(source); return this; } @Override - public NutsIOCopyAction setSource(File source) { - this.source = source==null?null:NutsStreamOrPath.of(session.io().path(source)); + public NutsCp setSource(File source) { + this.source = source==null?null:NutsStreamOrPath.of(NutsPath.of(source,session)); return this; } @Override - public NutsIOCopyAction setSource(Path source) { - this.source = source==null?null:NutsStreamOrPath.of(session.io().path(source)); + public NutsCp setSource(Path source) { + this.source = source==null?null:NutsStreamOrPath.of(NutsPath.of(source,session)); return this; } @Override - public NutsIOCopyAction setSource(URL source) { - this.source = source==null?null:NutsStreamOrPath.of(session.io().path(source)); + public NutsCp setSource(URL source) { + this.source = source==null?null:NutsStreamOrPath.of(NutsPath.of(source,session)); return this; } @Override - public NutsIOCopyAction setSource(String source) { - this.source = source==null?null:NutsStreamOrPath.of(session.io().path(source)); + public NutsCp setSource(String source) { + this.source = source==null?null:NutsStreamOrPath.of(NutsPath.of(source,session)); return this; } @Override - public NutsIOCopyAction from(NutsPath source) { + public NutsCp from(NutsPath source) { this.source = source==null?null:NutsStreamOrPath.of(source); return this; } @Override - public NutsIOCopyAction from(String source) { - this.source = source==null?null:NutsStreamOrPath.of(session.io().path(source)); + public NutsCp from(String source) { + this.source = source==null?null:NutsStreamOrPath.of(NutsPath.of(source,session)); return this; } @Override - public NutsIOCopyAction from(InputStream source) { + public NutsCp from(InputStream source) { return setSource(source); } @Override - public NutsIOCopyAction from(File source) { + public NutsCp from(File source) { return setSource(source); } @Override - public NutsIOCopyAction from(Path source) { + public NutsCp from(Path source) { return setSource(source); } @Override - public NutsIOCopyAction from(URL source) { + public NutsCp from(URL source) { return setSource(source); } @@ -170,71 +177,71 @@ public Object getTarget() { } @Override - public NutsIOCopyAction setTarget(OutputStream target) { + public NutsCp setTarget(OutputStream target) { this.target = target==null?null:NutsStreamOrPath.of(target); return this; } @Override - public NutsIOCopyAction setTarget(NutsPrintStream target) { + public NutsCp setTarget(NutsPrintStream target) { this.target = target==null?null:NutsStreamOrPath.of(target); return this; } @Override - public NutsIOCopyAction to(NutsPrintStream target) { + public NutsCp to(NutsPrintStream target) { this.target = target==null?null:NutsStreamOrPath.of(target); return this; } @Override - public NutsIOCopyAction setTarget(NutsPath target) { + public NutsCp setTarget(NutsPath target) { this.target = target==null?null:NutsStreamOrPath.of(target); return this; } @Override - public NutsIOCopyAction setTarget(Path target) { - this.target = target==null?null:NutsStreamOrPath.of(session.io().path(target)); + public NutsCp setTarget(Path target) { + this.target = target==null?null:NutsStreamOrPath.of(NutsPath.of(target,session)); return this; } @Override - public NutsIOCopyAction setTarget(String target) { - this.target = target==null?null:NutsStreamOrPath.of(session.io().path(target)); + public NutsCp setTarget(String target) { + this.target = target==null?null:NutsStreamOrPath.of(target,session); return this; } @Override - public NutsIOCopyAction setTarget(File target) { - this.target = target==null?null:NutsStreamOrPath.of(session.io().path(target)); + public NutsCp setTarget(File target) { + this.target = target==null?null:NutsStreamOrPath.of(target,session); return this; } @Override - public NutsIOCopyAction to(NutsPath target) { + public NutsCp to(NutsPath target) { this.target = target==null?null:NutsStreamOrPath.of(target); return this; } @Override - public NutsIOCopyAction to(OutputStream target) { + public NutsCp to(OutputStream target) { return setTarget(target); } @Override - public NutsIOCopyAction to(String target) { - this.target = target==null?null:NutsStreamOrPath.of(session.io().path(target)); + public NutsCp to(String target) { + this.target = target==null?null:NutsStreamOrPath.of(target,session); return this; } @Override - public NutsIOCopyAction to(Path target) { + public NutsCp to(Path target) { return setTarget(target); } @Override - public NutsIOCopyAction to(File target) { + public NutsCp to(File target) { return setTarget(target); } @@ -244,7 +251,7 @@ public NutsIOCopyValidator getValidator() { } @Override - public DefaultNutsIOCopyAction setValidator(NutsIOCopyValidator checker) { + public DefaultNutsCp setValidator(NutsIOCopyValidator checker) { this.checker = checker; return this; } @@ -255,7 +262,7 @@ public boolean isRecursive() { } @Override - public NutsIOCopyAction setRecursive(boolean recursive) { + public NutsCp setRecursive(boolean recursive) { this.recursive = recursive; return this; } @@ -266,7 +273,7 @@ public boolean isMkdirs() { } @Override - public NutsIOCopyAction setMkdirs(boolean mkdirs) { + public NutsCp setMkdirs(boolean mkdirs) { this.mkdirs = mkdirs; return this; } @@ -277,7 +284,7 @@ public boolean isSafe() { } @Override - public DefaultNutsIOCopyAction setSafe(boolean value) { + public DefaultNutsCp setSafe(boolean value) { this.safe = value; return this; } @@ -288,7 +295,7 @@ public NutsSession getSession() { } @Override - public NutsIOCopyAction setSession(NutsSession session) { + public NutsCp setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(ws, session); return this; } @@ -303,7 +310,7 @@ public byte[] getByteArrayResult() { } @Override - public NutsIOCopyAction run() { + public NutsCp run() { checkSession(); NutsStreamOrPath _source = source; if (_source == null) { @@ -338,7 +345,7 @@ public boolean isLogProgress() { } @Override - public DefaultNutsIOCopyAction setLogProgress(boolean value) { + public DefaultNutsCp setLogProgress(boolean value) { this.logProgress = value; return this; } @@ -362,7 +369,7 @@ public NutsProgressFactory getProgressMonitorFactory() { * @since 0.5.8 */ @Override - public NutsIOCopyAction setProgressMonitorFactory(NutsProgressFactory value) { + public NutsCp setProgressMonitorFactory(NutsProgressFactory value) { this.progressMonitorFactory = value; return this; } @@ -375,13 +382,13 @@ public NutsIOCopyAction setProgressMonitorFactory(NutsProgressFactory value) { * @since 0.5.8 */ @Override - public NutsIOCopyAction setProgressMonitor(NutsProgressMonitor value) { + public NutsCp setProgressMonitor(NutsProgressMonitor value) { this.progressMonitorFactory = value == null ? null : new SingletonNutsInputStreamProgressFactory(value); return this; } @Override - public NutsIOCopyAction setSkipRoot(boolean skipRoot) { + public NutsCp setSkipRoot(boolean skipRoot) { this.skipRoot = skipRoot; return this; } @@ -395,12 +402,12 @@ public boolean isInterruptible() { return interruptible; } - public NutsIOCopyAction setInterruptible(boolean interruptible) { + public NutsCp setInterruptible(boolean interruptible) { this.interruptible = interruptible; return this; } - public NutsIOCopyAction interrupt() { + public NutsCp interrupt() { if (interruptibleInstance != null) { interruptibleInstance.interrupt(); } @@ -453,7 +460,7 @@ private void copyFolderWithMonitor(Path srcBase, Path targetBase, CopyData f) { NutsSession session = getSession(); long start = System.currentTimeMillis(); NutsProgressMonitor m = CoreIOUtils.createProgressMonitor(CoreIOUtils.MonitorType.DEFAULT, srcBase, srcBase, session, isLogProgress(), getProgressMonitorFactory()); - NutsText srcBaseMessage = session.text().toText(srcBase); + NutsText srcBaseMessage = NutsTexts.of(session).toText(srcBase); m.onStart(new DefaultNutsProgressEvent(srcBase, srcBaseMessage , 0, 0, 0, 0, f.files + f.folders, null, session, false)); @@ -600,7 +607,7 @@ private void copyStream() { throw new NutsIllegalArgumentException(getSession(), NutsMessage.formatted("unsupported validation if neither safeCopy is armed nor path is defined")); } if (isLogProgress() || getProgressMonitorFactory() != null) { - NutsMonitorAction monitor = getSession().io().monitor(); + NutsInputStreamMonitor monitor = NutsInputStreamMonitor.of(session); if(_source.isInputStream()){ monitor.setSource(_source.getInputStream()); }else{ @@ -622,8 +629,7 @@ private void copyStream() { CoreIOUtils.mkdirs(to.getParent(),session); temp = to.resolveSibling(to.getFileName() + "~"); } else { - temp = getSession().io().tmp() - .setSession(session) + temp = NutsTmp.of(getSession()) .createTempFile("temp~").toFile(); } try { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsExecutionEntryAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsExecutionEntries.java similarity index 81% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsExecutionEntryAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsExecutionEntries.java index 3e97278d1..36cd6aed2 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsExecutionEntryAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsExecutionEntries.java @@ -1,10 +1,11 @@ package net.thevpc.nuts.runtime.standalone.io; -import net.thevpc.nuts.NutsExecutionEntryAction; +import net.thevpc.nuts.NutsExecutionEntries; import net.thevpc.nuts.NutsExecutionEntry; import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.NutsWorkspace; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.File; import java.io.IOException; @@ -13,12 +14,13 @@ import java.nio.file.Files; import java.nio.file.Path; -public class DefaultNutsExecutionEntryAction implements NutsExecutionEntryAction { +public class DefaultNutsExecutionEntries implements NutsExecutionEntries { private NutsWorkspace ws; private NutsSession session; - public DefaultNutsExecutionEntryAction(NutsWorkspace ws) { - this.ws = ws; + public DefaultNutsExecutionEntries(NutsSession session) { + this.ws = session.getWorkspace(); + this.session = session; } @Override @@ -66,8 +68,13 @@ public NutsSession getSession() { } @Override - public NutsExecutionEntryAction setSession(NutsSession session) { + public NutsExecutionEntries setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(ws, session); return this; } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOHashAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsHash.java similarity index 81% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOHashAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsHash.java index 34d7ac9f8..ad4970e15 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOHashAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsHash.java @@ -29,9 +29,9 @@ import net.thevpc.nuts.runtime.bundles.io.NutsStreamOrPath; import net.thevpc.nuts.runtime.core.util.CoreIOUtils; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.*; -import java.nio.file.Files; import java.nio.file.Path; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -39,49 +39,50 @@ /** * @author thevpc */ -public class DefaultNutsIOHashAction implements NutsIOHashAction { +public class DefaultNutsHash implements NutsHash { private NutsStreamOrPath source; private String algorithm; private NutsWorkspace ws; private NutsSession session; - public DefaultNutsIOHashAction(NutsWorkspace ws) { - this.ws = ws; + public DefaultNutsHash(NutsSession session) { + this.session = session; + this.ws = session.getWorkspace(); } @Override - public NutsIOHashAction setSource(InputStream source) { + public NutsHash setSource(InputStream source) { this.source = source==null?null:NutsStreamOrPath.of(source); return this; } @Override - public NutsIOHashAction setSource(byte[] source) { + public NutsHash setSource(byte[] source) { this.source = source==null?null:NutsStreamOrPath.of(new ByteArrayInputStream(source)); return null; } @Override - public NutsIOHashAction setSource(File source) { - this.source = source==null?null:NutsStreamOrPath.of(session.io().path(source)); + public NutsHash setSource(File source) { + this.source = source==null?null:NutsStreamOrPath.of(source,getSession()); return this; } @Override - public NutsIOHashAction setSource(Path source) { - this.source = source==null?null:NutsStreamOrPath.of(session.io().path(source)); + public NutsHash setSource(Path source) { + this.source = source==null?null:NutsStreamOrPath.of(source,getSession()); return this; } @Override - public NutsIOHashAction setSource(NutsPath source) { + public NutsHash setSource(NutsPath source) { this.source = source==null?null:NutsStreamOrPath.of(source); return this; } @Override - public NutsIOHashAction setSource(NutsDescriptor source) { + public NutsHash setSource(NutsDescriptor source) { this.source = source==null?null:NutsStreamOrPath.ofSpecial(source, NutsStreamOrPath.Type.DESCRIPTOR); return this; } @@ -110,7 +111,7 @@ public byte[] computeBytes() { } case DESCRIPTOR: { ByteArrayOutputStream o = new ByteArrayOutputStream(); - getSession().descriptor().formatter((NutsDescriptor) source.getValue()) + ((NutsDescriptor) source.getValue()).formatter().setSession(session) .compact().setSession(session).print(new OutputStreamWriter(o)); try (InputStream is = new ByteArrayInputStream(o.toByteArray())) { return CoreIOUtils.evalHash(is, getValidAlgo()); @@ -125,7 +126,7 @@ public byte[] computeBytes() { } @Override - public NutsIOHashAction writeHash(OutputStream out) { + public NutsHash writeHash(OutputStream out) { try { out.write(computeBytes()); } catch (IOException ex) { @@ -135,7 +136,7 @@ public NutsIOHashAction writeHash(OutputStream out) { } @Override - public NutsIOHashAction md5() { + public NutsHash md5() { return setAlgorithm("MD5"); } @@ -145,23 +146,23 @@ public NutsSession getSession() { } @Override - public NutsIOHashAction setSession(NutsSession session) { + public NutsHash setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(ws, session); return this; } @Override - public NutsIOHashAction sha1() { + public NutsHash sha1() { return setAlgorithm("SHA1"); } @Override - public NutsIOHashAction sha256() { + public NutsHash sha256() { return setAlgorithm("SHA256"); } @Override - public NutsIOHashAction setAlgorithm(String algorithm) { + public NutsHash setAlgorithm(String algorithm) { if (NutsBlankable.isBlank(algorithm)) { algorithm = null; } @@ -175,7 +176,7 @@ public NutsIOHashAction setAlgorithm(String algorithm) { } @Override - public NutsIOHashAction algorithm(String algorithm) { + public NutsHash algorithm(String algorithm) { return setAlgorithm(algorithm); } @@ -194,4 +195,9 @@ protected String getValidAlgo() { protected void checkSession() { NutsWorkspaceUtils.checkSession(ws, session); } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOManager.java deleted file mode 100755 index 57d319585..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOManager.java +++ /dev/null @@ -1,270 +0,0 @@ -package net.thevpc.nuts.runtime.standalone.io; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.core.io.FilePath; -import net.thevpc.nuts.runtime.core.io.NutsPathFromSPI; -import net.thevpc.nuts.runtime.core.io.URLPath; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; -import net.thevpc.nuts.spi.NutsPathFactory; -import net.thevpc.nuts.spi.NutsSupportLevelContext; - -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Writer; -import java.net.URL; -import java.nio.file.Path; - -public class DefaultNutsIOManager implements NutsIOManager { - - private DefaultNutsIOModel model; - private NutsSession session; - - public DefaultNutsIOManager(DefaultNutsIOModel model) { - this.model = model; - } - - public DefaultNutsIOModel getModel() { - return model; - } - - @Override - public int getSupportLevel(NutsSupportLevelContext criteria) { - return DEFAULT_SUPPORT; - } - - @Override - public NutsPath path(String path) { - checkSession(); - return path(path,null); - } - - @Override - public NutsPath path(File path) { - checkSession(); - if (path == null) { - return null; - } - return new NutsPathFromSPI(new FilePath(path.toPath(),getSession())); - } - - @Override - public NutsPath path(Path path) { - checkSession(); - if (path == null) { - return null; - } - return new NutsPathFromSPI(new FilePath(path,getSession())); - } - - @Override - public NutsPath path(URL path) { - checkSession(); - if (path == null) { - return null; - } - return new NutsPathFromSPI(new URLPath(path,getSession())); - } - - @Override - public NutsPath path(String path, ClassLoader classLoader) { - checkSession(); - if (path == null || path.trim().isEmpty()) { - return null; - } - NutsPath p = model.resolve(path, getSession(), classLoader); - if (p == null) { - throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("unable to resolve path from %s", path)); - } - return p; - } - - @Override - public InputStream createNullInputStream() { - checkSession(); - return model.nullInputStream(); - } - - @Override - public NutsPrintStream createNullPrintStream() { - checkSession(); - return model.nullPrintStream(); - } - - @Override - public NutsPrintStream createPrintStream(OutputStream out, NutsTerminalMode expectedMode) { - checkSession(); - return model.createPrintStream(out, expectedMode, session); - } - - @Override - public NutsPrintStream createPrintStream(OutputStream out) { - checkSession(); - return new NutsPrintStreamRaw(out, null, null, session, new NutsPrintStreamBase.Bindings()); - } - - @Override - public NutsPrintStream createPrintStream(Writer out) { - checkSession(); - return model.createPrintStream(out, NutsTerminalMode.INHERITED, session); - } - - @Override - public NutsMemoryPrintStream createMemoryPrintStream() { - checkSession(); - return new NutsByteArrayPrintStream(getSession()); - } - - @Override - public NutsTempAction tmp() { - checkSession(); - return model.tmp().setSession(session); - } - - // @Override -// public PrintStream createPrintStream(Path out) { -// if (out == null) { -// return null; -// } -// try { -// return new PrintStream(Files.newOutputStream(out)); -// } catch (IOException ex) { -// throw new IllegalArgumentException(ex); -// } -// } -// -// @Override -// public PrintStream createPrintStream(File out) { -// if (out == null) { -// return null; -// } -// try { -// return new PrintStream(out); -// } catch (IOException ex) { -// throw new IllegalArgumentException(ex); -// } -// } - @Override - public NutsIOCopyAction copy() { - return model.copy().setSession(session); - } - - @Override - public NutsIOProcessAction ps() { - return model.ps().setSession(session); - } - - @Override - public NutsIOCompressAction compress() { - return model.compress().setSession(session); - } - - @Override - public NutsIOUncompressAction uncompress() { - return model.uncompress().setSession(session); - } - - @Override - public NutsIODeleteAction delete() { - return model.delete().setSession(session); - } - - @Override - public NutsMonitorAction monitor() { - return model.monitor().setSession(session); - } - - @Override - public NutsIOHashAction hash() { - return model.hash().setSession(session); - } - -// @Override -// public NutsInputAction input() { -// return model.input().setSession(session); -// } -// -// @Override -// public NutsOutputAction output() { -// return model.output().setSession(session); -// } - - public NutsSession getSession() { - return session; - } - - public NutsIOManager setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(model.getWorkspace(), session); - return this; - } - - @Override - public NutsPrintStream stdout() { - return model.stdout(); - } - - @Override - public NutsPrintStream stderr() { - return model.stderr(); - } - - @Override - public InputStream stdin() { - return model.stdin(); - } - - @Override - public boolean isStandardOutputStream(NutsPrintStream out) { - if (out == null) { - return false; - } - if (out == model.stdout()) { - return true; - } - if (out == model.bootModel.stdout()) { - return true; - } - if (out instanceof NutsPrintStreamRendered) { - return isStandardOutputStream(((NutsPrintStreamRendered) out).getBase()); - } - return false; - } - - @Override - public boolean isStandardErrorStream(NutsPrintStream out) { - if (out == null) { - return false; - } - if (out == model.stderr()) { - return true; - } - if (out == model.bootModel.stderr()) { - return true; - } - if (out instanceof NutsPrintStreamRendered) { - return isStandardOutputStream(((NutsPrintStreamRendered) out).getBase()); - } - return false; - } - - @Override - public boolean isStandardInputStream(InputStream in) { - return in == model.stdin(); - } - - @Override - public NutsIOManager addPathFactory(NutsPathFactory pathFactory) { - model.addPathFactory(pathFactory); - return this; - } - - @Override - public NutsIOManager removePathFactory(NutsPathFactory pathFactory) { - model.removePathFactory(pathFactory); - return this; - } - - private void checkSession() { - NutsWorkspaceUtils.checkSession(model.getWorkspace(), getSession()); - } -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOModel.java deleted file mode 100644 index 43e939b84..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOModel.java +++ /dev/null @@ -1,350 +0,0 @@ -package net.thevpc.nuts.runtime.standalone.io; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.bundles.io.NullInputStream; -import net.thevpc.nuts.runtime.core.NutsSupplierBase; -import net.thevpc.nuts.runtime.core.format.text.SimpleWriterOutputStream; -import net.thevpc.nuts.runtime.core.io.*; -import net.thevpc.nuts.runtime.standalone.boot.DefaultNutsBootModel; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; -import net.thevpc.nuts.spi.NutsPathFactory; -import net.thevpc.nuts.spi.NutsPathSPI; -import net.thevpc.nuts.spi.NutsSupportLevelContext; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Writer; -import java.net.URL; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; -import java.util.function.Function; -import java.util.regex.Pattern; - -public class DefaultNutsIOModel { - - public static final Pattern MOSTLY_URL_PATTERN = Pattern.compile("([a-zA-Z][a-zA-Z0-9_-]+):.*"); - public final NutsPrintStream nullOut; - private final Function pathExpansionConverter; - public DefaultNutsBootModel bootModel; - // private final NutsLogger LOG; - private NutsWorkspace ws; - private InputStream stdin = null; - private NutsPrintStream stdout; - private NutsPrintStream stderr; - private List pathFactories = new ArrayList<>(); - - public DefaultNutsIOModel(NutsWorkspace workspace, DefaultNutsBootModel bootModel) { - this.ws = workspace; - this.pathExpansionConverter = new NutsWorkspaceVarExpansionFunction(NutsWorkspaceUtils.defaultSession(ws)); - this.bootModel = bootModel; - this.stdout = bootModel.stdout(); - this.stderr = bootModel.stderr(); - this.stdin = bootModel.stdin(); - this.nullOut = new NutsPrintStreamNull(bootModel.bootSession()); - addPathFactory(new FilePathFactory()); - addPathFactory(new ClasspathNutsPathFactory()); - addPathFactory(new URLPathFactory()); - addPathFactory(new NutsResourcePathFactory()); - } - - public NutsWorkspace getWorkspace() { - return ws; - } - - public int getSupportLevel(NutsSupportLevelContext criteria) { - return DefaultNutsIOManager.DEFAULT_SUPPORT; - } - - public InputStream nullInputStream() { - return NullInputStream.INSTANCE; - } - - public NutsPrintStream nullPrintStream() { - return nullOut; - //return createPrintStream(NullOutputStream.INSTANCE, NutsTerminalMode.FILTERED, session); - } - - public NutsPrintStream createPrintStream(Writer out, NutsTerminalMode expectedMode, NutsSession session) { - if (out == null) { - return null; - } - if (out instanceof NutsPrintStreamAdapter) { - return ((NutsPrintStreamAdapter) out).getBaseNutsPrintStream().setMode(expectedMode); - } - SimpleWriterOutputStream w = new SimpleWriterOutputStream(out, session); - return createPrintStream(w, expectedMode, session); - } - - public NutsPrintStream createPrintStream(OutputStream out, NutsTerminalMode expectedMode, NutsSession session) { - if (out == null) { - return null; - } - NutsWorkspaceOptions woptions = session.boot().setSession(session).getBootOptions(); - NutsTerminalMode expectedMode0 = woptions.getTerminalMode(); - if (expectedMode0 == null) { - if (woptions.isBot()) { - expectedMode0 = NutsTerminalMode.FILTERED; - } else { - expectedMode0 = NutsTerminalMode.FORMATTED; - } - } - if (expectedMode == null) { - expectedMode = expectedMode0; - } - if (expectedMode == NutsTerminalMode.FORMATTED) { - if (expectedMode0 == NutsTerminalMode.FILTERED) { - //if nuts started with --no-color modifier, will disable FORMATTED terminal mode each time - expectedMode = NutsTerminalMode.FILTERED; - } - } - if (out instanceof NutsPrintStreamAdapter) { - return ((NutsPrintStreamAdapter) out).getBaseNutsPrintStream().setMode(expectedMode); - } - return - new NutsPrintStreamRaw(out, null, null, session, new NutsPrintStreamBase.Bindings()) - .setMode(expectedMode) - ; - } - - - public NutsTempAction tmp() { - return new DefaultTempAction(ws); - } - - // -// public PrintStream createPrintStream(Path out) { -// if (out == null) { -// return null; -// } -// try { -// return new PrintStream(Files.newOutputStream(out)); -// } catch (IOException ex) { -// throw new IllegalArgumentException(ex); -// } -// } -// -// -// public PrintStream createPrintStream(File out) { -// if (out == null) { -// return null; -// } -// try { -// return new PrintStream(out); -// } catch (IOException ex) { -// throw new IllegalArgumentException(ex); -// } -// } - public NutsIOCopyAction copy() { - return new DefaultNutsIOCopyAction(ws); - } - - public NutsIOProcessAction ps() { - return new DefaultNutsIOProcessAction(ws); - } - - public NutsIOCompressAction compress() { - return new DefaultNutsIOCompressAction(ws); - } - - public NutsIOUncompressAction uncompress() { - return new DefaultNutsIOUncompressAction(ws); - } - - public NutsIODeleteAction delete() { - return new DefaultNutsIODeleteAction(ws); - } - - public NutsMonitorAction monitor() { - return new DefaultNutsMonitorAction(ws); - } - - public NutsIOHashAction hash() { - return new DefaultNutsIOHashAction(ws); - } - -// public NutsInputAction input() { -// return new DefaultNutsInputAction(ws); -// } -// -// public NutsOutputAction output() { -// return new DefaultNutsOutputAction(ws); -// } - -// -// public void invokeLocked(Runnable r, Runnable rollback, NutsLock lock) { -// lock.acquire(); -// try { -// r.run(); -// } catch (Exception ex) { -// rollback.run(); -// } -// if (Files.exists(lockPath)) { -// throw new NutsLockBarrierException(ws, lockedObject, lockPath); -// } -// try { -// Files.newOutputStream(lockPath).close(); -// } catch (IOException ex) { -// throw new NutsLockException(ws, "Unable to acquire lock " + lockedObject, lockPath, ex); -// } -// } -// -// public NutsIOManager executorService(ExecutorService executor) { -// if (executor == null) { -// throw new IllegalArgumentException("Unable to set null executor"); -// } -// return this; -// } - - public InputStream stdin() { - return stdin == null ? bootModel.stdin() : stdin; - } - - public void setStdin(InputStream stdin) { - this.stdin = stdin; - } - - public NutsPrintStream stdout() { - return stdout; - } - - public void setStdout(NutsPrintStream stdout) { - this.stdout = stdout == null ? - - bootModel.stdout() : stdout; - } - - public NutsPrintStream stderr() { - return stderr; - } - - public void setStderr(NutsPrintStream stderr) { - this.stderr = stderr == null ? bootModel.stderr() : stderr; - } - - public void addPathFactory(NutsPathFactory f) { - if (f != null && !pathFactories.contains(f)) { - pathFactories.add(f); - } - } - - public void removePathFactory(NutsPathFactory f) { - pathFactories.remove(f); - } - - public NutsPath resolve(String path,NutsSession session,ClassLoader classLoader) { - if(classLoader==null){ - classLoader=Thread.currentThread().getContextClassLoader(); - } - // - ClassLoader finalClassLoader = classLoader; - NutsSupplier z = Arrays.stream(getPathFactories()) - .map(x -> { - try { - return x.createPath(path, session, finalClassLoader); - } catch (Exception ex) { - // - } - return null; - }) - .filter(x -> x != null && x.getLevel() > 0) - .max(Comparator.comparingInt(NutsSupplier::getLevel)) - .orElse(null); - NutsPathSPI s= z == null ? null : z.create(); - if(s!=null){ - if( s instanceof NutsPath){ - return (NutsPath) s; - } - return new NutsPathFromSPI(s); - } - return null; - } - - public NutsPathFactory[] getPathFactories() { - return pathFactories.toArray(new NutsPathFactory[0]); - } - - private class URLPathFactory implements NutsPathFactory { - @Override - public NutsSupplier createPath(String path, NutsSession session, ClassLoader classLoader) { - NutsWorkspaceUtils.checkSession(getWorkspace(), session); - try { - URL url=new URL(path); - return new NutsSupplierBase(2) { - @Override - public NutsPathSPI create() { - return new URLPath(url, session); - } - }; - }catch (Exception ex){ - //ignore - } - return null; - } - } - - private class NutsResourcePathFactory implements NutsPathFactory { - @Override - public NutsSupplier createPath(String path, NutsSession session, ClassLoader classLoader) { - NutsWorkspaceUtils.checkSession(getWorkspace(), session); - try { - if(path.startsWith("nuts-resource:")) { - return new NutsSupplierBase(2) { - @Override - public NutsPathSPI create() { - return new NutsResourcePath(path, session); - } - }; - } - }catch (Exception ex){ - //ignore - } - return null; - } - } - - private class ClasspathNutsPathFactory implements NutsPathFactory { - @Override - public NutsSupplier createPath(String path, NutsSession session, ClassLoader classLoader) { - NutsWorkspaceUtils.checkSession(getWorkspace(), session); - try { - if(path.startsWith("classpath:")) { - return new NutsSupplierBase(2) { - @Override - public NutsPathSPI create() { - return new ClassLoaderPath(path, classLoader, session); - } - }; - } - }catch (Exception ex){ - //ignore - } - return null; - } - } - - private class FilePathFactory implements NutsPathFactory { - @Override - public NutsSupplier createPath(String path, NutsSession session, ClassLoader classLoader) { - NutsWorkspaceUtils.checkSession(getWorkspace(), session); - try { - if(MOSTLY_URL_PATTERN.matcher(path).matches()){ - return null; - } - Path value = Paths.get(path); - return new NutsSupplierBase(1) { - @Override - public NutsPathSPI create() { - return new FilePath(value, session); - } - }; - }catch (Exception ex){ - //ignore - } - return null; - } - } -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsInputAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsInputAction.java index 49757c1c4..9907eba6f 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsInputAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsInputAction.java @@ -76,7 +76,7 @@ // checkSession(); // NutsString n = getName(); // if(n==null){ -// n=getSession().text().forStyled("",NutsTextStyle.path()); +// n=NutsTexts.of(getSession()).forStyled("",NutsTextStyle.path()); // } // NutsInput v = CoreIOUtils.createInputSource(bytes, n.filteredText(),n, getTypeName(), getSession()); // v = toMulti(v); @@ -91,7 +91,7 @@ // checkSession(); // NutsString name = getName(); // if(name==null){ -// name=getSession().text().toText(source); +// name=NutsTexts.of(getSession()).toText(source); // } // return toMulti(new CoreIOUtils.InputStream(name.filteredText(),name, source, "inputStream", getSession())); // } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsMonitorAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsInputStreamMonitor.java similarity index 80% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsMonitorAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsInputStreamMonitor.java index 0cd2013ad..ab61d7380 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsMonitorAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsInputStreamMonitor.java @@ -12,6 +12,7 @@ import net.thevpc.nuts.runtime.core.util.CoreIOUtils; import net.thevpc.nuts.runtime.standalone.io.progress.DefaultNutsProgressEvent; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.File; import java.io.InputStream; @@ -21,7 +22,7 @@ /** * @author thevpc */ -public class DefaultNutsMonitorAction implements NutsMonitorAction { +public class DefaultNutsInputStreamMonitor implements NutsInputStreamMonitor { // private final NutsLogger LOG; private final NutsWorkspace ws; @@ -34,9 +35,10 @@ public class DefaultNutsMonitorAction implements NutsMonitorAction { private boolean logProgress; private NutsProgressFactory progressFactory; - public DefaultNutsMonitorAction(NutsWorkspace ws) { - this.ws = ws; -// LOG = ws.log().of(DefaultNutsMonitorAction.class); + public DefaultNutsInputStreamMonitor(NutsSession session) { + this.session = session; + this.ws = session.getWorkspace(); +// LOG = ws.log().of(DefaultNutsInputStreamMonitor.class); } @Override @@ -45,7 +47,7 @@ public NutsSession getSession() { } @Override - public NutsMonitorAction setSession(NutsSession session) { + public NutsInputStreamMonitor setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(ws, session); return this; } @@ -56,7 +58,7 @@ public NutsString getName() { } @Override - public NutsMonitorAction setName(NutsString name) { + public NutsInputStreamMonitor setName(NutsString name) { this.sourceName = name; return this; } @@ -67,7 +69,7 @@ public Object getOrigin() { } @Override - public NutsMonitorAction setOrigin(Object origin) { + public NutsInputStreamMonitor setOrigin(Object origin) { this.sourceOrigin = origin; return this; } @@ -78,37 +80,37 @@ public long getLength() { } @Override - public NutsMonitorAction setLength(long len) { + public NutsInputStreamMonitor setLength(long len) { this.length = len; return this; } @Override - public NutsMonitorAction setSource(String path) { - this.source = path == null ? null : NutsStreamOrPath.of(session.io().path(path)); + public NutsInputStreamMonitor setSource(String path) { + this.source = path == null ? null : NutsStreamOrPath.of(path,session); return this; } @Override - public NutsMonitorAction setSource(NutsPath inputSource) { + public NutsInputStreamMonitor setSource(NutsPath inputSource) { this.source = inputSource == null ? null : NutsStreamOrPath.of(inputSource); return this; } @Override - public NutsMonitorAction setSource(Path path) { - this.source = path == null ? null : NutsStreamOrPath.of(session.io().path(path)); + public NutsInputStreamMonitor setSource(Path path) { + this.source = path == null ? null : NutsStreamOrPath.of(path,session); return this; } @Override - public NutsMonitorAction setSource(File path) { - this.source = path == null ? null : NutsStreamOrPath.of(session.io().path(path)); + public NutsInputStreamMonitor setSource(File path) { + this.source = path == null ? null : NutsStreamOrPath.of(path,session); return this; } @Override - public NutsMonitorAction setSource(InputStream path) { + public NutsInputStreamMonitor setSource(InputStream path) { this.source = path == null ? null : NutsStreamOrPath.of(path); return this; } @@ -122,13 +124,13 @@ public InputStream create() { checkSession(); NutsString sourceName = this.sourceName; if (sourceName == null || sourceName.isEmpty()) { - sourceName = session.text().toText(source); + sourceName = NutsTexts.of(session).toText(source); } if (sourceName == null || sourceName.isEmpty()) { - sourceName = session.text().toText(source.getName()); + sourceName = NutsTexts.of(session).toText(source.getName()); } if (sourceName == null || sourceName.isEmpty()) { - sourceName = session.text().toText(String.valueOf(source.getValue())); + sourceName = NutsTexts.of(session).toText(String.valueOf(source.getValue())); } NutsProgressMonitor monitor = CoreIOUtils.createProgressMonitor(CoreIOUtils.MonitorType.STREAM, source.getValue(), sourceOrigin, session, isLogProgress(), getProgressFactory()); boolean verboseMode @@ -175,7 +177,7 @@ public String getSourceTypeName() { } @Override - public NutsMonitorAction setSourceTypeName(String sourceType) { + public NutsInputStreamMonitor setSourceTypeName(String sourceType) { this.sourceTypeName = sourceType; return this; } @@ -199,7 +201,7 @@ public boolean isLogProgress() { * @since 0.5.8 */ @Override - public NutsMonitorAction setLogProgress(boolean value) { + public NutsInputStreamMonitor setLogProgress(boolean value) { this.logProgress = value; return this; } @@ -223,7 +225,7 @@ public NutsProgressFactory getProgressFactory() { * @since 0.5.8 */ @Override - public NutsMonitorAction setProgressFactory(NutsProgressFactory value) { + public NutsInputStreamMonitor setProgressFactory(NutsProgressFactory value) { this.progressFactory = value; return this; } @@ -236,7 +238,7 @@ public NutsMonitorAction setProgressFactory(NutsProgressFactory value) { * @since 0.5.8 */ @Override - public NutsMonitorAction setProgressMonitor(NutsProgressMonitor value) { + public NutsInputStreamMonitor setProgressMonitor(NutsProgressMonitor value) { this.progressFactory = value == null ? null : new SingletonNutsInputStreamProgressFactory(value); return this; } @@ -246,4 +248,8 @@ protected void checkSession() { NutsWorkspaceUtils.checkSession(ws, session); } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsInputStreams.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsInputStreams.java new file mode 100644 index 000000000..d60df2910 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsInputStreams.java @@ -0,0 +1,42 @@ +package net.thevpc.nuts.runtime.standalone.io; + +import net.thevpc.nuts.NutsInputStreams; +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.runtime.bundles.io.NullInputStream; +import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigManager; +import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigModel; +import net.thevpc.nuts.spi.NutsSupportLevelContext; + +import java.io.InputStream; + +public class DefaultNutsInputStreams implements NutsInputStreams { + private final NutsSession session; + + public DefaultNutsInputStreams(NutsSession session) { + this.session = session; + } + + @Override + public InputStream ofNull() { + return NullInputStream.INSTANCE; + } + + @Override + public boolean isStdin(InputStream in) { + return in == getModel().stdin(); + } + + @Override + public InputStream stdin() { + return getModel().stdin(); + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } + + private DefaultNutsWorkspaceConfigModel getModel() { + return ((DefaultNutsWorkspaceConfigManager) session.config()).getModel(); + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOLockAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsLocks.java similarity index 94% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOLockAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsLocks.java index 60ef813a0..89f0d2398 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOLockAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsLocks.java @@ -1,6 +1,7 @@ package net.thevpc.nuts.runtime.standalone.io; import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.File; import java.nio.file.Path; @@ -8,8 +9,8 @@ import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; -public class DefaultNutsIOLockAction extends AbstractNutsIOLockAction { - public DefaultNutsIOLockAction(NutsWorkspace ws) { +public class DefaultNutsLocks extends AbstractNutsLocks { + public DefaultNutsLocks(NutsSession ws) { super(ws); } @@ -147,4 +148,9 @@ private Path toPath(Object lockedObject) { return null; } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } + } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsPaths.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsPaths.java new file mode 100644 index 000000000..c1b4890a3 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsPaths.java @@ -0,0 +1,95 @@ +package net.thevpc.nuts.runtime.standalone.io; + +import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.io.FilePath; +import net.thevpc.nuts.runtime.core.io.NutsPathFromSPI; +import net.thevpc.nuts.runtime.core.io.URLPath; +import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigManager; +import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigModel; +import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsPaths; +import net.thevpc.nuts.spi.NutsPathFactory; +import net.thevpc.nuts.spi.NutsSupportLevelContext; + +import java.io.File; +import java.net.URL; +import java.nio.file.Path; + +public class DefaultNutsPaths implements NutsPaths { + private final NutsWorkspace ws; + + public DefaultNutsPaths(NutsWorkspace ws) { + this.ws = ws; + } + + @Override + public NutsPath createPath(String path,NutsSession session) { + checkSession(session); + return createPath(path, null,session); + } + + @Override + public NutsPath createPath(File path,NutsSession session) { + checkSession(session); + if (path == null) { + return null; + } + return new NutsPathFromSPI(new FilePath(path.toPath(), session)); + } + + @Override + public NutsPath createPath(Path path,NutsSession session) { + checkSession(session); + if (path == null) { + return null; + } + return new NutsPathFromSPI(new FilePath(path, session)); + } + + @Override + public NutsPath createPath(URL path,NutsSession session) { + checkSession(session); + if (path == null) { + return null; + } + return new NutsPathFromSPI(new URLPath(path, session)); + } + + @Override + public NutsPath createPath(String path, ClassLoader classLoader,NutsSession session) { + checkSession(session); + if (path == null || path.trim().isEmpty()) { + return null; + } + NutsPath p = getModel(session).resolve(path, session, classLoader); + if (p == null) { + throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("unable to resolve path from %s", path)); + } + return p; + } + + @Override + public NutsPaths addPathFactory(NutsPathFactory pathFactory,NutsSession session) { + getModel(session).addPathFactory(pathFactory); + return this; + } + + @Override + public NutsPaths removePathFactory(NutsPathFactory pathFactory,NutsSession session) { + getModel(session).removePathFactory(pathFactory); + return this; + } + + private void checkSession(NutsSession session) { + NutsWorkspaceUtils.checkSession(ws, session); + } + + private DefaultNutsWorkspaceConfigModel getModel(NutsSession session) { + return ((DefaultNutsWorkspaceConfigManager) session.config()).getModel(); + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsPrintStreams.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsPrintStreams.java new file mode 100644 index 000000000..a1a5a7006 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsPrintStreams.java @@ -0,0 +1,159 @@ +package net.thevpc.nuts.runtime.standalone.io; + +import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.format.text.SimpleWriterOutputStream; +import net.thevpc.nuts.runtime.standalone.boot.DefaultNutsBootManager; +import net.thevpc.nuts.runtime.standalone.boot.NutsBootModel; +import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigManager; +import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigModel; +import net.thevpc.nuts.spi.NutsSupportLevelContext; + +import java.io.OutputStream; +import java.io.Writer; + +public class DefaultNutsPrintStreams implements NutsPrintStreams { + private final NutsSession session; + + public DefaultNutsPrintStreams(NutsSession session) { + this.session = session; + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } + + @Override + public NutsPrintStream createNull() { + checkSession(); + return getConfigModel().nullPrintStream(); + } + + + @Override + public NutsPrintStream create(OutputStream out) { + checkSession(); + return new NutsPrintStreamRaw(out, null, null, session, new NutsPrintStreamBase.Bindings()); + } + + @Override + public NutsPrintStream create(Writer out) { + checkSession(); + return create(out, NutsTerminalMode.INHERITED); + } + + public NutsPrintStream create(Writer out, NutsTerminalMode mode) { + checkSession(); + if(mode ==null){ + mode =NutsTerminalMode.INHERITED; + } + if (out == null) { + return null; + } + if (out instanceof NutsPrintStreamAdapter) { + return ((NutsPrintStreamAdapter) out).getBaseNutsPrintStream().setMode(mode); + } + SimpleWriterOutputStream w = new SimpleWriterOutputStream(out, session); + return create(w, mode); + } + + @Override + public NutsPrintStream create(OutputStream out, NutsTerminalMode expectedMode) { + if (out == null) { + return null; + } + NutsWorkspaceOptions woptions = session.boot().setSession(session).getBootOptions(); + NutsTerminalMode expectedMode0 = woptions.getTerminalMode(); + if (expectedMode0 == null) { + if (woptions.isBot()) { + expectedMode0 = NutsTerminalMode.FILTERED; + } else { + expectedMode0 = NutsTerminalMode.FORMATTED; + } + } + if (expectedMode == null) { + expectedMode = expectedMode0; + } + if (expectedMode == NutsTerminalMode.FORMATTED) { + if (expectedMode0 == NutsTerminalMode.FILTERED) { + //if nuts started with --no-color modifier, will disable FORMATTED terminal mode each time + expectedMode = NutsTerminalMode.FILTERED; + } + } + if (out instanceof NutsPrintStreamAdapter) { + return ((NutsPrintStreamAdapter) out).getBaseNutsPrintStream().setMode(expectedMode); + } + return + new NutsPrintStreamRaw(out, null, null, session, new NutsPrintStreamBase.Bindings()) + .setMode(expectedMode) + ; + } + + @Override + public NutsMemoryPrintStream createInMemory() { + checkSession(); + return new NutsByteArrayPrintStream(getSession()); + } + + public NutsSession getSession() { + return session; + } + + private void checkSession() { + //NutsWorkspaceUtils.checkSession(model.getWorkspace(), getSession()); + } +// private DefaultNutsIOModel getIoModel(){ +// return ((DefaultNutsIOManager)session.io()).getModel(); +// } + private DefaultNutsWorkspaceConfigModel getConfigModel(){ + return ((DefaultNutsWorkspaceConfigManager)session.config()).getModel(); + } + private NutsBootModel getBootModel(){ + return ((DefaultNutsBootManager)session.boot()).getModel(); + } + + @Override + public boolean isStdout(NutsPrintStream out) { + if (out == null) { + return false; + } + if (out == getConfigModel().stdout()) { + return true; + } + if (out == getConfigModel().getBootModel().stdout()) { + return true; + } + if (out instanceof NutsPrintStreamRendered) { + return isStdout(((NutsPrintStreamRendered) out).getBase()); + } + return false; + } + + @Override + public boolean isStderr(NutsPrintStream out) { + if (out == null) { + return false; + } + if (out == getBootModel().stderr()) { + return true; + } + if (out == getBootModel().stderr()) { + return true; + } + if (out instanceof NutsPrintStreamRendered) { + return isStdout(((NutsPrintStreamRendered) out).getBase()); + } + return false; + } + + @Override + public NutsPrintStream stdout() { + return getConfigModel().stdout(); + } + + @Override + public NutsPrintStream stderr() { + return getConfigModel().stderr(); + } + +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOProcessAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsPs.java similarity index 88% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOProcessAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsPs.java index bbaea0435..044767303 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOProcessAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsPs.java @@ -11,16 +11,23 @@ import net.thevpc.nuts.runtime.standalone.util.NutsEmptyStream; import net.thevpc.nuts.runtime.standalone.util.NutsIteratorStream; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; -public class DefaultNutsIOProcessAction implements NutsIOProcessAction { +public class DefaultNutsPs implements NutsPs { private String processType; private NutsWorkspace ws; private NutsSession session; private boolean failFast; - public DefaultNutsIOProcessAction(NutsWorkspace ws) { - this.ws = ws; + public DefaultNutsPs(NutsSession session) { + this.session = session; + this.ws = session.getWorkspace(); + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; } protected void checkSession() { @@ -33,7 +40,7 @@ public boolean isFailFast() { } @Override - public NutsIOProcessAction setFailFast(boolean failFast) { + public NutsPs setFailFast(boolean failFast) { this.failFast = failFast; return this; } @@ -55,12 +62,12 @@ public boolean killProcess(String processId) { } @Override - public NutsIOProcessAction failFast(boolean failFast) { + public NutsPs failFast(boolean failFast) { return setFailFast(failFast); } @Override - public NutsIOProcessAction failFast() { + public NutsPs failFast() { return failFast(true); } @@ -70,7 +77,7 @@ public NutsSession getSession() { } @Override - public NutsIOProcessAction setSession(NutsSession session) { + public NutsPs setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(ws, session); return this; } @@ -80,13 +87,13 @@ public String getType() { return processType; } - public NutsIOProcessAction setType(String processType) { + public NutsPs setType(String processType) { this.processType = processType; return this; } @Override - public NutsIOProcessAction type(String processType) { + public NutsPs type(String processType) { return setType(processType); } @@ -98,9 +105,9 @@ private static String getJpsJavaHome(String version, NutsSession session) { if (v != null) { return v; } - NutsVersionFilter nvf = NutsBlankable.isBlank(version) ? null : session.version().parser().parse(version).filter(); + NutsVersionFilter nvf = NutsBlankable.isBlank(version) ? null : NutsVersion.of(version,session).filter(); NutsPlatformLocation[] availableJava = session.env().platforms().setSession(session).findPlatforms(NutsPlatformType.JAVA, - java -> "jdk".equals(java.getPackaging()) && (nvf == null || nvf.acceptVersion(session.version().parser().parse(java.getVersion()), session)) + java -> "jdk".equals(java.getPackaging()) && (nvf == null || nvf.acceptVersion(NutsVersion.of(java.getVersion(),session), session)) ); for (NutsPlatformLocation java : availableJava) { detectedJavaHomes.add(java.getPath()); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsQuestion.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsQuestion.java index 3c0b78bb9..d2d3cbece 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsQuestion.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsQuestion.java @@ -97,7 +97,7 @@ private T execute() { ByteArrayOutputStream bos = null; if (gui) { bos = new ByteArrayOutputStream(); - out = session.io().createPrintStream(bos); + out = NutsPrintStream.of(bos,session); } if (resetLine) { out.resetLine(); @@ -111,7 +111,7 @@ private T execute() { } else { out.print(", "); } - out.printf("default is %s", session.text().ofStyled(ff.format(this.getDefaultValue(), this), NutsTextStyle.primary1())); + out.printf("default is %s", NutsTexts.of(session).ofStyled(ff.format(this.getDefaultValue(), this), NutsTextStyle.primary1())); } if (getHintMessage() != null) { out.print(" ("); @@ -133,7 +133,7 @@ private T execute() { } sb.append(ff.format(acceptedValue, this)); } - out.printf("accepts %s", session.text().ofStyled(sb.toString(), NutsTextStyle.primary4())); + out.printf("accepts %s", NutsTexts.of(session).ofStyled(sb.toString(), NutsTextStyle.primary4())); } if (!first) { out.print(")"); @@ -252,7 +252,7 @@ private T execute() { } private String showGuiInput(String str, boolean pwd) { - String ft = getSession().text().parse(str).filteredText(); + String ft = NutsTexts.of(getSession()).parse(str).filteredText(); NutsMessage title = NutsMessage.cstyle("Nuts Package Manager - %s", getSession().getWorkspace().getApiId().getVersion()); if (session.getAppId() != null) { try { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIODeleteAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsRm.java similarity index 91% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIODeleteAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsRm.java index 4cb1d9d49..1a1fb6d07 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIODeleteAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsRm.java @@ -2,6 +2,7 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.util.CoreIOUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.FileNotFoundException; import java.io.IOException; @@ -13,10 +14,10 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.logging.Level; -public class DefaultNutsIODeleteAction extends AbstractNutsIODeleteAction { +public class DefaultNutsRm extends AbstractNutsRm { private Exception error; - public DefaultNutsIODeleteAction(NutsWorkspace ws) { + public DefaultNutsRm(NutsSession ws) { super(ws); } @@ -26,9 +27,13 @@ private void grabException(IOException e) { throw new UncheckedIOException(e); } } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } @Override - public NutsIODeleteAction run() { + public NutsRm run() { checkSession(); Path t = CoreIOUtils.toPath(getTarget()); if (t == null) { @@ -51,7 +56,7 @@ public NutsIODeleteAction run() { return this; } final int[] deleted = new int[]{0, 0, 0}; - NutsLogger LOG = getSession().log().of(CoreIOUtils.class); + NutsLogger LOG = NutsLogger.of(CoreIOUtils.class,getSession()); try { Files.walkFileTree(t, new FileVisitor() { @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsStreamProgressMonitor.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsStreamProgressMonitor.java index a972b3179..711e0a960 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsStreamProgressMonitor.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsStreamProgressMonitor.java @@ -61,7 +61,7 @@ public boolean onProgress(NutsProgressEvent event) { return true; } -// private String escapeText(NutsTextManager text , String str) { +// private String escapeText(NutsTexts text , String str) { // return text.builder().append(str).toString(); // } @@ -72,7 +72,7 @@ public boolean onProgress0(NutsProgressEvent event, boolean end) { } double partialSeconds = event.getPartialMillis() / 1000.0; if (event.getCurrentValue() == 0 || partialSeconds > 0.5 || event.getCurrentValue() == event.getMaxValue()) { - NutsTextManager text = event.getSession().text(); + NutsTexts text = NutsTexts.of(event.getSession()); if(!optionNewline) { out.resetLine(); // out.run(NutsTerminalCommand.MOVE_LINE_START); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminalManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminalManager.java deleted file mode 100644 index b50adb73f..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminalManager.java +++ /dev/null @@ -1,143 +0,0 @@ -package net.thevpc.nuts.runtime.standalone.io; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.core.terminals.DefaultNutsSessionTerminalFromSystem; -import net.thevpc.nuts.runtime.core.terminals.DefaultNutsSessionTerminalFromSession; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; -import net.thevpc.nuts.spi.NutsSystemTerminalBase; -import net.thevpc.nuts.spi.NutsTerminalSpec; - -import java.io.InputStream; - -public class DefaultNutsTerminalManager implements NutsTerminalManager { - - public DefaultNutsTerminalModel model; - public NutsSession session; - - public DefaultNutsTerminalManager(DefaultNutsTerminalModel model) { - this.model = model; - } - - public DefaultNutsTerminalModel getModel() { - return model; - } - - private void checkSession() { - NutsWorkspaceUtils.checkSession(model.getWorkspace(), session); - } - - @Override - public NutsSystemTerminal getSystemTerminal() { - checkSession(); - return model.getSystemTerminal(); - } - - @Override - public NutsTerminalManager setSystemTerminal(NutsSystemTerminalBase terminal) { - checkSession(); - model.setSystemTerminal(terminal, session); - return this; - } - - @Override - public NutsTerminalManager enableRichTerm() { - checkSession(); - model.enableRichTerm(session); - return this; - } - - @Override - public NutsSystemTerminal createSystemTerminal(NutsTerminalSpec spec) { - checkSession(); - return model.createSystemTerminal(spec, session); - } - - @Override - public NutsSessionTerminal getTerminal() { - checkSession(); - return model.getTerminal(); - } - - @Override - public NutsTerminalManager setTerminal(NutsSessionTerminal terminal) { - checkSession(); - model.setTerminal(terminal, session); - return this; - } - - @Override - public NutsSessionTerminal createTerminal() { - checkSession(); - return model.createTerminal(session); - } - - @Override - public NutsSessionTerminal createTerminal(InputStream in, NutsPrintStream out, NutsPrintStream err) { - checkSession(); - return model.createTerminal(in, out, err, session); - } - - @Override - public NutsSessionTerminal createTerminal(NutsSessionTerminal terminal) { - checkSession(); - if (terminal == null) { - return createTerminal(); - } - if(terminal instanceof DefaultNutsSessionTerminalFromSystem){ - DefaultNutsSessionTerminalFromSystem t = (DefaultNutsSessionTerminalFromSystem) terminal; - return new DefaultNutsSessionTerminalFromSystem(session, t); - } - if(terminal instanceof DefaultNutsSessionTerminalFromSession){ - DefaultNutsSessionTerminalFromSession t = (DefaultNutsSessionTerminalFromSession) terminal; - return new DefaultNutsSessionTerminalFromSession(session, t); - } - return new DefaultNutsSessionTerminalFromSession(session, terminal); - } - - public NutsSession getSession() { - return session; - } - - public NutsTerminalManager setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(model.getWorkspace(), session); - return this; - } - -// @Override -// public NutsSessionTerminal createTerminal(NutsSystemTerminalBase parent) { -// checkSession(); -// return model.createTerminal(parent, session); -// } - -// @Override -// public PrintStream prepare(PrintStream out) { -// checkSession(); -// return model.prepare(out, session); -// } -// -// @Override -// public PrintWriter prepare(PrintWriter out) { -// checkSession(); -// return model.prepare(out, session); -// } - -// @Override -// public boolean isFormatted(OutputStream out) { -// checkSession(); -// return model.isFormatted(out); -// } -// -// @Override -// public boolean isFormatted(Writer out) { -// checkSession(); -// return model.isFormatted(out); -// } - -// @Override -// public NutsTerminalManager sendTerminalCommand(NutsPrintStream out, NutsTerminalCommand command) { -// checkSession(); -// model.sendTerminalCommand(out, command,session); -// return this; -// } - -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminalModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminalModel.java index 316ed6482..7a8d329e8 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminalModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminalModel.java @@ -15,14 +15,10 @@ public class DefaultNutsTerminalModel { private NutsWorkspace ws; - private NutsSessionTerminal terminal; - private NutsSystemTerminal systemTerminal; - private WorkspaceSystemTerminalAdapter workspaceSystemTerminalAdapter; private NutsLogger LOG; public DefaultNutsTerminalModel(NutsWorkspace ws) { this.ws = ws; - workspaceSystemTerminalAdapter = new WorkspaceSystemTerminalAdapter(ws); } protected NutsLoggerOp _LOGOP(NutsSession session) { @@ -31,7 +27,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsTerminalModel.class); + LOG = NutsLogger.of(DefaultNutsTerminalModel.class,session); } return LOG; } @@ -40,204 +36,7 @@ public NutsWorkspace getWorkspace() { return ws; } - public NutsSystemTerminal createSystemTerminal(NutsTerminalSpec spec, NutsSession session) { - NutsSystemTerminalBase termb = session.extensions() - .setSession(session) - .createSupported(NutsSystemTerminalBase.class, spec); - if (termb == null) { - throw new NutsExtensionNotFoundException(session, NutsSystemTerminalBase.class, "SystemTerminalBase"); - } - return NutsSystemTerminal_of_NutsSystemTerminalBase(termb, session); - } - - public void enableRichTerm(NutsSession session) { - NutsSystemTerminal st = getSystemTerminal(); - if (st.isAutoCompleteSupported()) { - //that's ok - } else { - NutsId extId = session.id().parser().parse("net.thevpc.nuts.ext:next-term#" + session.getWorkspace().getApiVersion()); - if (!session.config().isExcludedExtension(extId.toString(), session.boot().getBootOptions())) { - NutsWorkspaceExtensionManager extensions = session.extensions(); - extensions.setSession(session).loadExtension(extId); - NutsSystemTerminal systemTerminal = createSystemTerminal( - new NutsDefaultTerminalSpec() - .setAutoComplete(true), - session - ); - setSystemTerminal(systemTerminal, session); - if (getSystemTerminal().isAutoCompleteSupported()) { - _LOGOP(session).level(Level.FINE).verb(NutsLogVerb.SUCCESS) - .log(NutsMessage.jstyle("enable rich terminal")); - } else { - _LOGOP(session).level(Level.FINE).verb(NutsLogVerb.FAIL) - .log(NutsMessage.jstyle("unable to enable rich terminal")); - } - } else { - _LOGOP(session).level(Level.FINE).verb(NutsLogVerb.WARNING) - .log(NutsMessage.jstyle("enableRichTerm discarded; next-term is excluded.")); - } - } - } - public NutsSystemTerminal getSystemTerminal() { - return systemTerminal; - } - - public NutsSessionTerminal getTerminal() { - return terminal; - } - - public void setTerminal(NutsSessionTerminal terminal, NutsSession session) { - NutsWorkspaceUtils.checkSession(ws, session); - if (terminal == null) { - terminal = createTerminal(session); - } - if (!(terminal instanceof UnmodifiableSessionTerminal)) { - terminal = new UnmodifiableSessionTerminal(terminal, session); - } - this.terminal = terminal; - } - - public NutsSessionTerminal createTerminal(InputStream in, NutsPrintStream out, NutsPrintStream err, NutsSession session) { - NutsSessionTerminal t = createTerminal(session); - if (in != null) { - t.setIn(in); - } - if (out != null) { - t.setOut(out); - } - if (err != null) { - t.setErr(err); - } - return t; - } - - public NutsSessionTerminal createTerminal(NutsSession session) { - return new DefaultNutsSessionTerminalFromSystem( - session,workspaceSystemTerminalAdapter - ); -// return createTerminal(null, session); - } -// public NutsSessionTerminal createTerminal(NutsSystemTerminalBase parent, NutsSession session) { -// if (parent == null) { -// parent = workspaceSystemTerminalAdapter; -// } -// NutsSystemTerminalBase termb = ws.extensions() -// .setSession(session) -// .createSupported(NutsSessionTerminalBase.class, null); -// if (termb == null) { -// throw new NutsExtensionNotFoundException(session, NutsSessionTerminal.class, "SessionTerminalBase"); -// } -// NutsWorkspaceUtils.setSession(termb, session); -// try { -// NutsSessionTerminal term = null; -// if (termb instanceof NutsSessionTerminal) { -// term = (NutsSessionTerminal) termb; -// NutsWorkspaceUtils.setSession(term, session); -// term.setParent(parent); -// } else { -// term = new DefaultNutsSessionTerminalFromSystem(); -// NutsWorkspaceUtils.setSession(term, session); -// term.setParent(termb); -// } -// return term; -// } catch (Exception anyException) { -// final NutsSessionTerminal c = new DefaultNutsSessionTerminalFromSystem(); -// NutsWorkspaceUtils.setSession(c, session); -// c.setParent(parent); -// return c; -// } -// } - private NutsSystemTerminal NutsSystemTerminal_of_NutsSystemTerminalBase(NutsSystemTerminalBase terminal, NutsSession session) { - if (terminal == null) { - throw new NutsExtensionNotFoundException(session, NutsSystemTerminalBase.class, "SystemTerminalBase"); - } - NutsSystemTerminal syst; - if ((terminal instanceof NutsSystemTerminal)) { - syst = (NutsSystemTerminal) terminal; - } else { - try { - syst = new DefaultSystemTerminal(terminal); - NutsWorkspaceUtils.setSession(syst, session); - } catch (Exception ex) { - _LOGOP(session).level(Level.FINEST).verb(NutsLogVerb.WARNING) - .log(NutsMessage.jstyle("unable to create system terminal : {0}", ex)); - DefaultNutsSystemTerminalBase b = new DefaultNutsSystemTerminalBase(); - NutsWorkspaceUtils.setSession(b, session); - syst = new DefaultSystemTerminal(b); - NutsWorkspaceUtils.setSession(syst, session); - } - } - return syst; - } - - public void setSystemTerminal(NutsSystemTerminalBase terminal, NutsSession session) { - if (terminal == null) { - throw new NutsExtensionNotFoundException(session, NutsSystemTerminalBase.class, "SystemTerminalBase"); - } - NutsSystemTerminal syst = NutsSystemTerminal_of_NutsSystemTerminalBase(terminal, session); - NutsSystemTerminal old = this.systemTerminal; - this.systemTerminal = syst; - - if (old != this.systemTerminal) { - NutsWorkspaceEvent event = null; - if (session != null) { - for (NutsWorkspaceListener workspaceListener : session.events().getWorkspaceListeners()) { - if (event == null) { - event = new DefaultNutsWorkspaceEvent(session, null, "systemTerminal", old, this.systemTerminal); - } - workspaceListener.onUpdateProperty(event); - } - } - } - } - -// public PrintStream prepare(PrintStream out, NutsSession session) { -// NutsWorkspaceUtils.checkSession(ws, session); -// return CoreIOUtils.toPrintStream(out, session); -// } -// -// public PrintWriter prepare(PrintWriter out, NutsSession session) { -// NutsWorkspaceUtils.checkSession(ws, session); -// return CoreIOUtils.toPrintWriter(out, session); -// } - -// public boolean isFormatted(NutsPrintStream out) { -// if (out instanceof ExtendedFormatAware) { -// NutsTerminalModeOp op = ((ExtendedFormatAware) out).getModeOp(); -// return op != NutsTerminalModeOp.NOP; -// } -// return false; -// } -// -// public boolean isFormatted(Writer out) { -// if (out instanceof ExtendedFormatAware) { -// NutsTerminalModeOp op = ((ExtendedFormatAware) out).getModeOp(); -// return op != NutsTerminalModeOp.NOP; -// } -// return false; -// } - -// public void sendTerminalCommand(NutsPrintStream out, NutsTerminalCommand command, NutsSession session) { -// if (isFormatted(out)) { -// ((PrintStream) out).printf("%s", session.text().forCommand(command)); -// out.flush(); -// } -// } - - private static class WorkspaceSystemTerminalAdapter extends AbstractSystemTerminalAdapter { - - private NutsWorkspace workspace; - - public WorkspaceSystemTerminalAdapter(NutsWorkspace workspace) { - this.workspace = workspace; - } - - public NutsSystemTerminalBase getParent() { - return NutsWorkspaceUtils.defaultSession(workspace).term() - .getSystemTerminal(); - } - } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminals.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminals.java new file mode 100644 index 000000000..49949e018 --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTerminals.java @@ -0,0 +1,73 @@ +package net.thevpc.nuts.runtime.standalone.io; + +import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.terminals.DefaultNutsSessionTerminalFromSystem; +import net.thevpc.nuts.runtime.core.terminals.DefaultNutsSessionTerminalFromSession; +import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigManager; +import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigModel; +import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; +import net.thevpc.nuts.spi.NutsTerminals; + +import java.io.InputStream; + +public class DefaultNutsTerminals implements NutsTerminals { + + public DefaultNutsWorkspaceConfigModel model; + public NutsWorkspace ws; + + public DefaultNutsTerminals(NutsSession session) { + this.ws = session.getWorkspace(); + this.model = ((DefaultNutsWorkspaceConfigManager)session.config()).getModel(); + } + + public DefaultNutsWorkspaceConfigModel getModel() { + return model; + } + + private void checkSession(NutsSession session) { + NutsWorkspaceUtils.checkSession(model.getWorkspace(), session); + } + + @Override + public NutsTerminals enableRichTerm(NutsSession session) { + checkSession(session); + model.enableRichTerm(session); + return this; + } + + + @Override + public NutsSessionTerminal createTerminal(NutsSession session) { + checkSession(session); + return model.createTerminal(session); + } + + @Override + public NutsSessionTerminal createTerminal(InputStream in, NutsPrintStream out, NutsPrintStream err,NutsSession session) { + checkSession(session); + return model.createTerminal(in, out, err, session); + } + + @Override + public NutsSessionTerminal createTerminal(NutsSessionTerminal terminal,NutsSession session) { + checkSession(session); + if (terminal == null) { + return createTerminal(session); + } + if(terminal instanceof DefaultNutsSessionTerminalFromSystem){ + DefaultNutsSessionTerminalFromSystem t = (DefaultNutsSessionTerminalFromSystem) terminal; + return new DefaultNutsSessionTerminalFromSystem(session, t); + } + if(terminal instanceof DefaultNutsSessionTerminalFromSession){ + DefaultNutsSessionTerminalFromSession t = (DefaultNutsSessionTerminalFromSession) terminal; + return new DefaultNutsSessionTerminalFromSession(session, t); + } + return new DefaultNutsSessionTerminalFromSession(session, terminal); + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultTempAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTmp.java similarity index 85% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultTempAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTmp.java index 9a6f5c77c..266d45c91 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultTempAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsTmp.java @@ -4,20 +4,26 @@ import net.thevpc.nuts.runtime.bundles.string.StringBuilder2; import net.thevpc.nuts.runtime.core.util.CoreIOUtils; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; import java.io.File; import java.io.IOException; import java.nio.file.Paths; -public class DefaultTempAction implements NutsTempAction { +public class DefaultNutsTmp implements NutsTmp { private NutsWorkspace ws; private String repositoryId; private NutsSession session; - public DefaultTempAction(NutsWorkspace ws) { - this.ws = ws; + public DefaultNutsTmp(NutsSession session) { + this.session = session; + this.ws = session.getWorkspace(); } + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } @Override public String getRepositoryId() { @@ -25,7 +31,7 @@ public String getRepositoryId() { } @Override - public NutsTempAction setRepositoryId(String repositoryId) { + public NutsTmp setRepositoryId(String repositoryId) { this.repositoryId = repositoryId; return this; } @@ -36,7 +42,7 @@ public NutsSession getSession() { } @Override - public NutsTempAction setSession(NutsSession session) { + public NutsTmp setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(ws, session); return this; } @@ -118,7 +124,7 @@ public NutsPath createTempFile(String name, boolean folder) { try { temp = File.createTempFile(prefix.toString(), ext.toString(), rootFolder); if (temp.delete() && temp.mkdir()) { - return session.io().path(temp.toPath()); + return NutsPath.of(temp.toPath(),session); } } catch (IOException ex) { // @@ -127,7 +133,7 @@ public NutsPath createTempFile(String name, boolean folder) { throw new NutsIOException(session, NutsMessage.cstyle("could not create temp directory: %s*%s", rootFolder + File.separator + prefix, ext)); } else { try { - return session.io().path(File.createTempFile(prefix.toString(), ext.toString(), rootFolder).toPath()); + return NutsPath.of(File.createTempFile(prefix.toString(), ext.toString(), rootFolder).toPath(),session); } catch (IOException e) { throw new NutsIOException(session, e); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOUncompressAction.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsUncompress.java similarity index 86% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOUncompressAction.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsUncompress.java index ec784e6c2..dd41cb681 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsIOUncompressAction.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/DefaultNutsUncompress.java @@ -19,11 +19,12 @@ import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; /** * @author thevpc */ -public class DefaultNutsIOUncompressAction implements NutsIOUncompressAction { +public class DefaultNutsUncompress implements NutsUncompress { private NutsLogger LOG; @@ -37,9 +38,15 @@ public class DefaultNutsIOUncompressAction implements NutsIOUncompressAction { private NutsSession session; private NutsProgressFactory progressMonitorFactory; - public DefaultNutsIOUncompressAction(NutsWorkspace ws) { - this.ws = ws; -// LOG = ws.log().of(DefaultNutsIOUncompressAction.class); + public DefaultNutsUncompress(NutsSession session) { + this.session = session; + this.ws = session.getWorkspace(); +// LOG = ws.log().of(DefaultNutsUncompress.class); + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; } protected NutsLoggerOp _LOGOP(NutsSession session) { @@ -48,7 +55,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsIOUncompressAction.class); + LOG = NutsLogger.of(DefaultNutsUncompress.class,session); } return LOG; } @@ -59,7 +66,7 @@ public String getFormat() { } @Override - public NutsIOUncompressAction setFormat(String format) { + public NutsUncompress setFormat(String format) { checkSession(); if (NutsBlankable.isBlank(format)) { format = "zip"; @@ -88,78 +95,78 @@ protected void checkSession() { } @Override - public NutsIOUncompressAction setSource(InputStream source) { + public NutsUncompress setSource(InputStream source) { this.source = source==null?null:NutsStreamOrPath.of(source); return this; } @Override - public NutsIOUncompressAction setSource(NutsPath source) { + public NutsUncompress setSource(NutsPath source) { this.source = source==null?null:NutsStreamOrPath.of(source); return this; } @Override - public NutsIOUncompressAction setSource(File source) { - this.source = source==null?null:NutsStreamOrPath.of(session.io().path(source)); + public NutsUncompress setSource(File source) { + this.source = source==null?null:NutsStreamOrPath.of(source,session); return this; } @Override - public NutsIOUncompressAction setSource(Path source) { - this.source = source==null?null:NutsStreamOrPath.of(session.io().path(source)); + public NutsUncompress setSource(Path source) { + this.source = source==null?null:NutsStreamOrPath.of(source,session); return this; } @Override - public NutsIOUncompressAction setSource(URL source) { - this.source = source==null?null:NutsStreamOrPath.of(session.io().path(source)); + public NutsUncompress setSource(URL source) { + this.source = source==null?null:NutsStreamOrPath.of(source,session); return this; } @Override - public NutsIOUncompressAction setTarget(Path target) { - this.target = target==null?null:NutsStreamOrPath.of(session.io().path(target)); + public NutsUncompress setTarget(Path target) { + this.target = target==null?null:NutsStreamOrPath.of(target,session); return this; } @Override - public NutsIOUncompressAction setTarget(String target) { - this.target = target==null?null:NutsStreamOrPath.of(session.io().path(target)); + public NutsUncompress setTarget(String target) { + this.target = target==null?null:NutsStreamOrPath.of(target,session); return this; } @Override - public NutsIOUncompressAction setTarget(File target) { - this.target = target==null?null:NutsStreamOrPath.of(session.io().path(target)); + public NutsUncompress setTarget(File target) { + this.target = target==null?null:NutsStreamOrPath.of(target,session); return this; } - public NutsIOUncompressAction setTarget(NutsPath target) { + public NutsUncompress setTarget(NutsPath target) { this.target = target==null?null:NutsStreamOrPath.of(target); return this; } @Override - public NutsIOUncompressAction from(String source) { - this.source = source==null?null:NutsStreamOrPath.of(session.io().path(source)); + public NutsUncompress from(String source) { + this.source = source==null?null:NutsStreamOrPath.of(source,session); return this; } @Override - public NutsIOUncompressAction to(String target) { - this.target = target==null?null:NutsStreamOrPath.of(session.io().path(target)); + public NutsUncompress to(String target) { + this.target = target==null?null:NutsStreamOrPath.of(target,session); return this; } @Override - public NutsIOUncompressAction from(NutsPath source) { + public NutsUncompress from(NutsPath source) { this.source = source==null?null:NutsStreamOrPath.of(source); return this; } @Override - public NutsIOUncompressAction to(NutsPath target) { + public NutsUncompress to(NutsPath target) { this.target = target==null?null:NutsStreamOrPath.of(target); return this; } @@ -178,38 +185,38 @@ public boolean isLogProgress() { } @Override - public DefaultNutsIOUncompressAction setLogProgress(boolean value) { + public DefaultNutsUncompress setLogProgress(boolean value) { this.logProgress = value; return this; } @Override - public NutsIOUncompressAction from(InputStream source) { + public NutsUncompress from(InputStream source) { return setSource(source); } @Override - public NutsIOUncompressAction from(File source) { + public NutsUncompress from(File source) { return setSource(source); } @Override - public NutsIOUncompressAction from(Path source) { + public NutsUncompress from(Path source) { return setSource(source); } @Override - public NutsIOUncompressAction from(URL source) { + public NutsUncompress from(URL source) { return setSource(source); } @Override - public NutsIOUncompressAction to(File target) { + public NutsUncompress to(File target) { return setTarget(target); } @Override - public NutsIOUncompressAction to(Path target) { + public NutsUncompress to(Path target) { return setTarget(target); } @@ -219,7 +226,7 @@ public boolean isSafe() { } @Override - public DefaultNutsIOUncompressAction setSafe(boolean value) { + public DefaultNutsUncompress setSafe(boolean value) { this.safe = value; return this; } @@ -230,13 +237,13 @@ public NutsSession getSession() { } @Override - public NutsIOUncompressAction setSession(NutsSession session) { + public NutsUncompress setSession(NutsSession session) { this.session = NutsWorkspaceUtils.bindSession(ws, session); return this; } @Override - public NutsIOUncompressAction run() { + public NutsUncompress run() { checkSession(); String format = getFormat(); if (NutsBlankable.isBlank(format)) { @@ -253,7 +260,7 @@ public NutsIOUncompressAction run() { throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("invalid target %s",target.getValue())); } if (isLogProgress() || getProgressMonitorFactory() != null) { - NutsMonitorAction m = session.io().monitor(); + NutsInputStreamMonitor m = NutsInputStreamMonitor.of(session); if(_source.isInputStream()){ m.setSource(_source.getInputStream()); }else{ @@ -289,7 +296,7 @@ public NutsIOUncompressAction run() { return this; } @Override - public NutsIOUncompressAction visit(NutsIOUncompressVisitor visitor) { + public NutsUncompress visit(NutsIOUncompressVisitor visitor) { checkSession(); String format = getFormat(); if (NutsBlankable.isBlank(format)) { @@ -306,7 +313,7 @@ public NutsIOUncompressAction visit(NutsIOUncompressVisitor visitor) { throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("invalid target %s",target.getValue())); } if (isLogProgress() || getProgressMonitorFactory() != null) { - NutsMonitorAction m = session.io().monitor(); + NutsInputStreamMonitor m = NutsInputStreamMonitor.of(session); if(_source.isInputStream()){ m.setSource(_source.getInputStream()); }else{ @@ -598,7 +605,7 @@ public NutsProgressFactory getProgressMonitorFactory() { * @since 0.5.8 */ @Override - public NutsIOUncompressAction setProgressMonitorFactory(NutsProgressFactory value) { + public NutsUncompress setProgressMonitorFactory(NutsProgressFactory value) { this.progressMonitorFactory = value; return this; } @@ -611,7 +618,7 @@ public NutsIOUncompressAction setProgressMonitorFactory(NutsProgressFactory valu * @since 0.5.8 */ @Override - public NutsIOUncompressAction setProgressMonitor(NutsProgressMonitor value) { + public NutsUncompress setProgressMonitor(NutsProgressMonitor value) { this.progressMonitorFactory = value == null ? null : new SingletonNutsInputStreamProgressFactory(value); return this; } @@ -624,7 +631,7 @@ public NutsIOUncompressAction setProgressMonitor(NutsProgressMonitor value) { * @since 0.5.8 */ @Override - public NutsIOUncompressAction progressMonitor(NutsProgressMonitor value) { + public NutsUncompress progressMonitor(NutsProgressMonitor value) { return setProgressMonitor(value); } @@ -634,13 +641,13 @@ public boolean isSkipRoot() { } @Override - public NutsIOUncompressAction setSkipRoot(boolean value) { + public NutsUncompress setSkipRoot(boolean value) { this.skipRoot = true; return this; } @Override - public NutsIOUncompressAction setFormatOption(String option, Object value) { + public NutsUncompress setFormatOption(String option, Object value) { return this; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamBase.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamBase.java index 1ae1fabd1..3e94d511d 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamBase.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamBase.java @@ -206,7 +206,7 @@ public NutsPrintStream resetLine() { @Override public NutsPrintStream printj(String format, Object... args) { - NutsText s = session.text().toText( + NutsText s = NutsTexts.of(session).toText( NutsMessage.jstyle( format, args ) @@ -242,7 +242,7 @@ public NutsPrintStream format(String format, Object... args) { @Override public NutsPrintStream format(Locale l, String format, Object... args) { if (l == null) { - NutsText s = session.text().toText( + NutsText s = NutsTexts.of(session).toText( NutsMessage.cstyle( format, args ) @@ -250,7 +250,7 @@ public NutsPrintStream format(Locale l, String format, Object... args) { print(s); } else { NutsSession sess = this.session.copy().setLocale(l.toString()); - NutsText s = sess.text().toText( + NutsText s = NutsTexts.of(sess).toText( NutsMessage.cstyle( format, args ) diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamFormatted.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamFormatted.java index 13870727b..6d94c6a48 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamFormatted.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamFormatted.java @@ -34,7 +34,7 @@ protected NutsPrintStream convertImpl(NutsTerminalMode other) { @Override public NutsPrintStream run(NutsTerminalCommand command) { - printf("%s", session.text().ofCommand(command)); + printf("%s", NutsTexts.of(session).ofCommand(command)); flush(); return this; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamSystem.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamSystem.java index 1d60eac99..c1f09690d 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamSystem.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/NutsPrintStreamSystem.java @@ -180,12 +180,12 @@ public NutsPrintStream run(NutsTerminalCommand command) { switch (command.getName()) { case NutsTerminalCommand.Ids .CLEAR_LINE: { - //printf("%s", session.text().forCommand(command)); + //printf("%s", NutsTexts.of(session).forCommand(command)); break; } case NutsTerminalCommand.Ids .CLEAR_LINE_FROM_CURSOR: { - //printf("%s", session.text().forCommand(command)); + //printf("%s", NutsTexts.of(session).forCommand(command)); break; } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/SilentStartNutsInputStreamProgressMonitorAdapter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/SilentStartNutsInputStreamProgressMonitorAdapter.java index 17a6cb13e..dcd102a3a 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/SilentStartNutsInputStreamProgressMonitorAdapter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/SilentStartNutsInputStreamProgressMonitorAdapter.java @@ -20,7 +20,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(SilentStartNutsInputStreamProgressMonitorAdapter.class); + LOG = NutsLogger.of(SilentStartNutsInputStreamProgressMonitorAdapter.class,session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/progress/CProgressBar.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/progress/CProgressBar.java index 09cbfd291..b09f7a62a 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/progress/CProgressBar.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/progress/CProgressBar.java @@ -336,7 +336,7 @@ public String progressWithSessionOld(int percent) { lastPrint = now; boolean indeterminate = percent < 0; if (indeterminate) { - NutsTextBuilder formattedLine = session.text().builder(); + NutsTextBuilder formattedLine = NutsTexts.of(session).builder(); formattedLine.append(getFormatter().getStart()); int indeterminateSize = (int) (this.indeterminateSize * size); boolean forward = true; @@ -388,7 +388,7 @@ public String progressWithSessionOld(int percent) { double d = (size / 100.0 * percent); int x = (int) d; float rest = (float) (d - x); - NutsTextBuilder formattedLine = session.text().builder(); + NutsTextBuilder formattedLine = NutsTexts.of(session).builder(); formattedLine.append(getFormatter().getStart()); if (x > 0) { StringBuilder sb = new StringBuilder(); @@ -422,7 +422,7 @@ public String progressWithSessionNew(int percent) { lastPrint = now; boolean indeterminate = percent < 0; if (indeterminate) { - NutsTextBuilder formattedLine = session.text().builder(); + NutsTextBuilder formattedLine = NutsTexts.of(session).builder(); formattedLine.append(getFormatter().getStart()); int indeterminateSize = (int) (this.indeterminateSize * size); boolean forward = true; @@ -474,7 +474,7 @@ public String progressWithSessionNew(int percent) { double d = (size / 100.0 * percent); int x = (int) d; float rest = (float) (d - x); - NutsTextBuilder formattedLine = session.text().builder(); + NutsTextBuilder formattedLine = NutsTexts.of(session).builder(); formattedLine.append(getFormatter().getStart()); StringBuilder sb = new StringBuilder(); if (x > 0) { @@ -516,7 +516,7 @@ public String progress(int percent, String msg) { if (msg == null) { msg = ""; } - s2 = session == null ? msg.length() : session.text().builder().append(msg).textLength(); + s2 = session == null ? msg.length() : NutsTexts.of(session).builder().append(msg).textLength(); if (isPrefixMoveLineStart()) { if (optionNewline) { if (!isSuffixMoveLineStart()) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/progress/DefaultNutsCountProgressMonitor.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/progress/DefaultNutsCountProgressMonitor.java index f9fc2a24d..3e516401b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/progress/DefaultNutsCountProgressMonitor.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/io/progress/DefaultNutsCountProgressMonitor.java @@ -61,14 +61,14 @@ public boolean onProgress(NutsProgressEvent event) { return true; } // -// private String escapeText(NutsTextManager text , String str) { +// private String escapeText(NutsTexts text , String str) { // return text.builder().append(str).toString(); // } public boolean onProgress0(NutsProgressEvent event, boolean end) { double partialSeconds = event.getPartialMillis() / 1000.0; if (event.getCurrentValue() == 0 || partialSeconds > 0.5 || event.getCurrentValue() == event.getMaxValue()) { - NutsTextManager text = event.getSession().text(); + NutsTexts text = NutsTexts.of(event.getSession()); out.resetLine(); double globalSeconds = event.getTimeMillis() / 1000.0; long globalSpeed = globalSeconds == 0 ? 0 : (long) (event.getCurrentValue() / globalSeconds); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsDependencyManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsDependencyManager.java deleted file mode 100644 index f6f6f44ee..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsDependencyManager.java +++ /dev/null @@ -1,93 +0,0 @@ -package net.thevpc.nuts.runtime.standalone.manager; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.core.model.DefaultNutsDependencyBuilder; -import net.thevpc.nuts.runtime.core.format.DefaultNutsDependencyFormat; -import net.thevpc.nuts.runtime.core.parser.DefaultNutsDependencyParser; - -import java.util.Collections; -import java.util.Set; - -import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigManager; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; -import net.thevpc.nuts.spi.NutsDependencySolver; - -public class DefaultNutsDependencyManager implements NutsDependencyManager { - - private NutsWorkspace ws; - - private NutsSession session; - - public DefaultNutsDependencyManager(NutsWorkspace workspace) { - this.ws = workspace; - } - - @Override - public NutsSession getSession() { - return session; - } - - @Override - public NutsDependencyManager setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(ws, session); - return this; - } - - public NutsWorkspace getWorkspace() { - return ws; - } - - protected void checkSession() { - NutsWorkspaceUtils.checkSession(ws, session); - } - - @Override - public NutsDependencyParser parser() { - checkSession(); - return new DefaultNutsDependencyParser(getSession()); - } - - @Override - public NutsDependencyBuilder builder() { - checkSession(); - return new DefaultNutsDependencyBuilder(getSession()); - } - - @Override - public NutsDependencyFormat formatter() { - return new DefaultNutsDependencyFormat(getWorkspace()).setSession(getSession()); - } - - @Override - public NutsDependencyFormat formatter(NutsDependency dependency) { - return formatter().setValue(dependency).setSession(getSession()); - } - - @Override - public NutsDependencyFilterManager filter() { - return getSession().filters().dependency().setSession(getSession()); - } - - @Override - public Set toScopeSet(NutsDependencyScopePattern other) { - return other==null? Collections.emptySet() : other.toScopes(); - } - - @Override - public NutsDependencySolver createSolver() { - return createSolver(getSession().getDependencySolver()); - } - - @Override - public NutsDependencySolver createSolver(String solverName) { - checkSession(); - DefaultNutsWorkspaceConfigManager config = (DefaultNutsWorkspaceConfigManager)session.config(); - return config.createDependencySolver(solverName); - } - - @Override - public String[] getSolverNames() { - DefaultNutsWorkspaceConfigManager config = (DefaultNutsWorkspaceConfigManager)session.config(); - return config.getDependencySolverNames(); - } -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsDescriptorManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsDescriptorManager.java deleted file mode 100644 index cf604cdc9..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsDescriptorManager.java +++ /dev/null @@ -1,92 +0,0 @@ -package net.thevpc.nuts.runtime.standalone.manager; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.core.format.DefaultNutsDescriptorFormat; -import net.thevpc.nuts.runtime.core.model.DefaultNutsArtifactCallBuilder; -import net.thevpc.nuts.runtime.core.model.DefaultNutsDescriptorBuilder; -import net.thevpc.nuts.runtime.core.model.DefaultNutsDescriptorPropertyBuilder; -import net.thevpc.nuts.runtime.core.model.DefaultNutsEnvConditionBuilder; -import net.thevpc.nuts.runtime.core.parser.DefaultNutsDescriptorParser; -import net.thevpc.nuts.runtime.standalone.config.DefaultNutsIdLocationBuilder; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; - -public class DefaultNutsDescriptorManager implements NutsDescriptorManager { - private NutsWorkspace workspace; - - private NutsSession session; - - public DefaultNutsDescriptorManager(NutsWorkspace workspace) { - this.workspace = workspace; - } - - public NutsWorkspace getWorkspace() { - return workspace; - } - - @Override - public NutsDescriptorParser parser() { - return new DefaultNutsDescriptorParser(workspace).setSession(getSession()); - } - - @Override - public NutsDescriptorBuilder descriptorBuilder() { - checkSession(); - return new DefaultNutsDescriptorBuilder(getSession()); - } - - @Override - public NutsEnvConditionBuilder envConditionBuilder() { - checkSession(); - return new DefaultNutsEnvConditionBuilder(getSession()); - } - - @Override - public NutsDescriptorPropertyBuilder propertyBuilder() { - checkSession(); - return new DefaultNutsDescriptorPropertyBuilder(getSession()); - } - - @Override - public NutsIdLocationBuilder locationBuilder() { - checkSession(); - return new DefaultNutsIdLocationBuilder(getSession()); - } - - @Override - public NutsArtifactCallBuilder callBuilder() { - checkSession(); - return new DefaultNutsArtifactCallBuilder(getSession()); - } - - @Override - public NutsDescriptorFormat formatter() { - checkSession(); - return new DefaultNutsDescriptorFormat(getWorkspace()).setSession(getSession()); - } - - @Override - public NutsDescriptorFormat formatter(NutsDescriptor value) { - return formatter().setValue(value); - } - - @Override - public NutsDescriptorFilterManager filter() { - checkSession(); - return getSession().filters().descriptor().setSession(getSession()); - } - - @Override - public NutsSession getSession() { - return session; - } - - @Override - public NutsDescriptorManager setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(workspace, session); - return this; - } - - protected void checkSession() { - NutsWorkspaceUtils.checkSession(workspace, session); - } -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsIdManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsIdManager.java deleted file mode 100644 index febe90563..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsIdManager.java +++ /dev/null @@ -1,91 +0,0 @@ -package net.thevpc.nuts.runtime.standalone.manager; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.core.model.DefaultNutsIdBuilder; -import net.thevpc.nuts.runtime.bundles.mvn.PomId; -import net.thevpc.nuts.runtime.core.format.DefaultNutsIdFormat; -import net.thevpc.nuts.runtime.core.parser.DefaultNutsIdParser; -import net.thevpc.nuts.runtime.standalone.bridges.maven.MavenUtils; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; - -public class DefaultNutsIdManager implements NutsIdManager { - - private NutsWorkspace ws; - private NutsSession session; - - public DefaultNutsIdManager(NutsWorkspace ws) { - this.ws = ws; - } - - @Override - public NutsSession getSession() { - return session; - } - - @Override - public NutsIdManager setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(ws, session); - return this; - } - - @Override - public NutsIdFormat formatter() { - return new DefaultNutsIdFormat(ws).setSession(getSession()); - } - - @Override - public NutsIdFormat formatter(NutsId id) { - return formatter().setValue(id); - } - - @Override - public NutsIdFilterManager filter() { - return getSession().filters().id().setSession(getSession()); - } - - @Override - public NutsIdBuilder builder() { - checkSession(); - return new DefaultNutsIdBuilder(getSession()); - } - - @Override - public NutsId resolveId(Class clazz) { - PomId u = MavenUtils.createPomIdResolver(session).resolvePomId(clazz, null, session); - if (u == null) { - return null; - } - return parser().parse(u.getGroupId() + ":" + u.getArtifactId() + "#" + u.getVersion()); - } - - @Override - public NutsId[] resolveIds(Class clazz) { - PomId[] u = MavenUtils.createPomIdResolver(session).resolvePomIds(clazz, session); - NutsId[] all = new NutsId[u.length]; - NutsIdParser parser = parser(); - for (int i = 0; i < all.length; i++) { - all[i] = parser.parse(u[i].getGroupId() + ":" + u[i].getArtifactId() + "#" + u[i].getVersion()); - } - return all; - } - - protected void checkSession() { - NutsWorkspaceUtils.checkSession(ws, session); - } - - - @Override - public NutsIdParser parser() { - checkSession(); - return new DefaultNutsIdParser(getSession()).setAcceptBlank(true).setLenient(false); - } - - @Override - public NutsId parse(String id) { - return parser().setAcceptBlank(true).setLenient(false).parse(id); - } - - public NutsWorkspace getWorkspace() { - return ws; - } -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsIdResolver.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsIdResolver.java new file mode 100644 index 000000000..b3f08e11e --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsIdResolver.java @@ -0,0 +1,44 @@ +package net.thevpc.nuts.runtime.standalone.manager; + +import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.bundles.mvn.PomId; +import net.thevpc.nuts.runtime.core.format.DefaultNutsIdFormat; +import net.thevpc.nuts.runtime.core.model.DefaultNutsIdBuilder; +import net.thevpc.nuts.runtime.core.parser.DefaultNutsIdParser; +import net.thevpc.nuts.runtime.standalone.bridges.maven.MavenUtils; +import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsSupportLevelContext; + +public class DefaultNutsIdResolver implements NutsIdResolver { + + private NutsSession session; + + public DefaultNutsIdResolver(NutsSession session) { + this.session = session; + } + + @Override + public NutsId resolveId(Class clazz) { + PomId u = MavenUtils.createPomIdResolver(session).resolvePomId(clazz, null, session); + if (u == null) { + return null; + } + return NutsIdParser.of(session).parse(u.getGroupId() + ":" + u.getArtifactId() + "#" + u.getVersion()); + } + + @Override + public NutsId[] resolveIds(Class clazz) { + PomId[] u = MavenUtils.createPomIdResolver(session).resolvePomIds(clazz, session); + NutsId[] all = new NutsId[u.length]; + NutsIdParser parser = NutsIdParser.of(session); + for (int i = 0; i < all.length; i++) { + all[i] = parser.parse(u[i].getGroupId() + ":" + u[i].getArtifactId() + "#" + u[i].getVersion()); + } + return all; + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsVersionManager.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsVersionManager.java deleted file mode 100644 index 14452ac30..000000000 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/manager/DefaultNutsVersionManager.java +++ /dev/null @@ -1,67 +0,0 @@ -package net.thevpc.nuts.runtime.standalone.manager; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.core.format.DefaultVersionFormat; -import net.thevpc.nuts.runtime.core.parser.DefaultNutsVersionParser; -import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; - -public class DefaultNutsVersionManager implements NutsVersionManager { - - private NutsWorkspace workspace; - - private NutsSession session; - - public DefaultNutsVersionManager(NutsWorkspace workspace) { - this.workspace = workspace; - } - - @Override - public NutsVersion parse(String version) { - return parser().parse(version); - } - - @Override - public NutsSession getSession() { - return session; - } - - @Override - public NutsVersionManager setSession(NutsSession session) { - this.session = NutsWorkspaceUtils.bindSession(workspace, session); - return this; - } - - protected void checkSession() { - NutsWorkspaceUtils.checkSession(workspace, session); - } - - @Override - public NutsVersionParser parser() { - checkSession(); - return new DefaultNutsVersionParser(getSession()) - .setAcceptBlank(true) - .setLenient(false) - .setAcceptBlank(true) - ; - } - - @Override - public NutsVersionFormat formatter() { - return new DefaultVersionFormat(getWorkspace()).setSession(getSession()); - } - - @Override - public NutsVersionFormat formatter(NutsVersion version) { - return formatter().setVersion(version); - } - - @Override - public NutsVersionFilterManager filter() { - return getSession().filters().version().setSession(getSession()); - } - - public NutsWorkspace getWorkspace() { - return workspace; - } - -} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/JarDescriptorContentParserComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/JarDescriptorContentParserComponent.java index c03ae3e67..a2872208f 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/JarDescriptorContentParserComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/JarDescriptorContentParserComponent.java @@ -39,15 +39,12 @@ import net.thevpc.nuts.runtime.bundles.io.InputStreamVisitor; import net.thevpc.nuts.runtime.bundles.io.ZipUtils; import net.thevpc.nuts.runtime.standalone.util.CoreDigestHelper; -import net.thevpc.nuts.spi.NutsDescriptorContentParserComponent; -import net.thevpc.nuts.spi.NutsDescriptorContentParserContext; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.spi.NutsSupportLevelContext; +import net.thevpc.nuts.spi.*; /** * Created by vpc on 1/15/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class JarDescriptorContentParserComponent implements NutsDescriptorContentParserComponent { public static final Set POSSIBLE_EXT = new HashSet<>(Collections.singletonList("jar"));//, "war", "ear" @@ -75,12 +72,13 @@ public NutsDescriptor parse(final NutsDescriptorContentParserContext parserConte if (!POSSIBLE_EXT.contains(parserContext.getFileExtension())) { return null; } - final NutsId JAVA = ws.id().parser().parse("java"); + final NutsId JAVA = NutsId.of("java",ws); final NutsRef nutsjson = new NutsRef<>(); final NutsRef metainf = new NutsRef<>(); final NutsRef maven = new NutsRef<>(); // final NutsRef mainClass = new NutsRef<>(); + NutsSession session = parserContext.getSession(); try { ZipUtils.visitZipStream(parserContext.getFullStream(), new Predicate() { @Override @@ -99,8 +97,7 @@ public boolean visit(String path, InputStream inputStream) throws IOException { switch (path) { case "META-INF/MANIFEST.MF": { try { - nutsjson.set(parserContext.getSession().descriptor().parser() - .setSession(parserContext.getSession()) + metainf.set(NutsDescriptorParser.of(session) .setDescriptorStyle(NutsDescriptorStyle.MANIFEST) .setLenient(true) .parse(inputStream)); @@ -111,8 +108,7 @@ public boolean visit(String path, InputStream inputStream) throws IOException { } case ("META-INF/" + NutsConstants.Files.DESCRIPTOR_FILE_NAME): { try { - nutsjson.set(parserContext.getSession().descriptor().parser() - .setSession(parserContext.getSession()) + nutsjson.set(NutsDescriptorParser.of(session) .setDescriptorStyle(NutsDescriptorStyle.NUTS) .parse(inputStream)); } finally { @@ -122,7 +118,7 @@ public boolean visit(String path, InputStream inputStream) throws IOException { } default: { try { - maven.set(MavenUtils.of(parserContext.getSession()).parsePomXmlAndResolveParents(inputStream, NutsFetchMode.REMOTE, path, null)); + maven.set(MavenUtils.of(session).parsePomXmlAndResolveParents(inputStream, NutsFetchMode.REMOTE, path, null)); } finally { inputStream.close(); } @@ -137,7 +133,7 @@ public boolean visit(String path, InputStream inputStream) throws IOException { throw new NutsIOException(ws, ex); } if (nutsjson.isSet()) { - return checkDescriptor(nutsjson.get(), parserContext.getSession()); + return nutsjson.get(); } String mainClassString = null; if (metainf.isSet()) { @@ -159,10 +155,8 @@ public boolean visit(String path, InputStream inputStream) throws IOException { if (maven.isSet()) { baseNutsDescriptor = maven.get(); if (!NutsBlankable.isBlank(mainClassString)) { - return checkDescriptor( - baseNutsDescriptor.builder().setExecutor(new DefaultNutsArtifactCall(JAVA, new String[]{ - "--main-class", mainClassString})).build() - , parserContext.getSession()); + return baseNutsDescriptor.builder().setExecutor(new DefaultNutsArtifactCall(JAVA, new String[]{ + "--main-class", mainClassString})).build(); } } else if (metainf.isSet()) { baseNutsDescriptor = metainf.get(); @@ -171,14 +165,14 @@ public boolean visit(String path, InputStream inputStream) throws IOException { CoreDigestHelper d = new CoreDigestHelper(); d.append(parserContext.getFullStream()); String artifactId = d.getDigest(); - baseNutsDescriptor = parserContext.getSession().descriptor().descriptorBuilder() - .setId(ws.id().builder().setGroupId("temp").setArtifactId(artifactId).setVersion("1.0").build()) + baseNutsDescriptor = NutsDescriptorBuilder.of(session) + .setId(NutsIdBuilder.of(session).setGroupId("temp").setArtifactId(artifactId).setVersion("1.0").build()) .addFlag(mainClassString != null ? NutsDescriptorFlag.EXEC : null) .setPackaging("jar") .build(); } boolean alwaysSelectAllMainClasses = false; - NutsCommandLine cmd = parserContext.getSession().commandLine().create(parserContext.getParseOptions()); + NutsCommandLine cmd = NutsCommandLine.of(parserContext.getParseOptions(),session); NutsArgument a; while (!cmd.isEmpty()) { if ((a = cmd.nextBoolean("--all-mains")) != null) { @@ -188,75 +182,21 @@ public boolean visit(String path, InputStream inputStream) throws IOException { } } if (NutsBlankable.isBlank(mainClassString) || alwaysSelectAllMainClasses) { - NutsExecutionEntry[] classes = parserContext.getSession().apps().execEntries() - .setSession(parserContext.getSession()) + NutsExecutionEntry[] classes = NutsExecutionEntries.of(session) .parse(parserContext.getFullStream(), "java", parserContext.getFullStream().toString()); if (classes.length == 0) { - return checkDescriptor(baseNutsDescriptor, parserContext.getSession()); + return baseNutsDescriptor; } else { - return checkDescriptor(baseNutsDescriptor.builder().setExecutor(new DefaultNutsArtifactCall(JAVA, new String[]{ + return baseNutsDescriptor.builder().setExecutor(new DefaultNutsArtifactCall(JAVA, new String[]{ "--main-class=" + String.join(":", Arrays.stream(classes) .map(x -> x.getName()) .collect(Collectors.toList()) - )}, null)).addFlag(NutsDescriptorFlag.EXEC).build() - , parserContext.getSession()) - ; + )}, null)).addFlag(NutsDescriptorFlag.EXEC).build(); } } else { - return checkDescriptor(baseNutsDescriptor, parserContext.getSession()); + return baseNutsDescriptor; } } - private NutsDescriptor checkDescriptor(NutsDescriptor nutsDescriptor, NutsSession session) { - NutsId id = nutsDescriptor.getId(); - String groupId = id == null ? null : id.getGroupId(); - String artifactId = id == null ? null : id.getArtifactId(); - NutsVersion version = id == null ? null : id.getVersion(); - if (groupId == null || artifactId == null || NutsBlankable.isBlank(version)) { - switch (session.getConfirm()) { - case ASK: - case ERROR: { - if (groupId == null) { - groupId = session.getTerminal().ask() - .forString(NutsMessage.cstyle("group id")) - .setDefaultValue(groupId) - .setHintMessage(NutsBlankable.isBlank(groupId) ? null : NutsMessage.plain(groupId)) - .getValue(); - } - if (artifactId == null) { - artifactId = session.getTerminal().ask() - .forString(NutsMessage.cstyle("artifact id")) - .setDefaultValue(artifactId) - .setHintMessage(NutsBlankable.isBlank(artifactId) ? null : NutsMessage.plain(artifactId)) - .getValue(); - } - if (NutsBlankable.isBlank(version)) { - String ov = version == null ? null : version.getValue(); - String v = session.getTerminal().ask() - .forString(NutsMessage.cstyle("version")) - .setDefaultValue(ov) - .setHintMessage(NutsBlankable.isBlank(ov) ? null : NutsMessage.plain(ov)) - .getValue(); - version = session.version().parser() - .setAcceptBlank(true) - .setAcceptIntervals(true) - .setLenient(true).parse(v); - } - break; - } - case NO: - case YES: { - //silently return null - } - } - } - if (groupId == null || artifactId == null || NutsBlankable.isBlank(version)) { - throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("invalid descriptor id %s:%s#%s", groupId, artifactId, version)); - } - return nutsDescriptor.builder() - .setId(session.id().builder().setGroupId(groupId).setArtifactId(artifactId).setVersion(version).build()) - .build() - ; - } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/NshDescriptorContentParserComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/NshDescriptorContentParserComponent.java index b93f08890..8ca541ea8 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/NshDescriptorContentParserComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/NshDescriptorContentParserComponent.java @@ -29,10 +29,7 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.model.DefaultNutsArtifactCall; import net.thevpc.nuts.runtime.core.format.json.JsonStringBuffer; -import net.thevpc.nuts.spi.NutsDescriptorContentParserComponent; -import net.thevpc.nuts.spi.NutsDescriptorContentParserContext; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.spi.NutsSupportLevelContext; +import net.thevpc.nuts.spi.*; import java.io.BufferedReader; import java.io.IOException; @@ -45,7 +42,7 @@ /** * Created by vpc on 1/15/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class NshDescriptorContentParserComponent implements NutsDescriptorContentParserComponent { public static NutsId NSH; @@ -66,7 +63,8 @@ public NutsDescriptor parse(NutsDescriptorContentParserContext parserContext) { @Override public int getSupportLevel(NutsSupportLevelContext criteria) { if(NSH==null){ - NSH=criteria.getSession().id().parser().parse("nsh"); + NutsSession session = criteria.getSession(); + NSH= NutsId.of("nsh",session); } String e = NutsUtilStrings.trim(criteria.getConstraints().getFileExtension()); switch (e){ @@ -150,13 +148,13 @@ private static NutsDescriptor readNutDescriptorFromBashScriptFile(NutsSession se } } if (comment.toString().trim().isEmpty()) { - return session.descriptor().descriptorBuilder() - .setId(session.id().parser().parse("temp:nsh#1.0")) + return NutsDescriptorBuilder.of(session) + .setId(NutsId.of("temp:nsh#1.0",session)) .setPackaging("nsh") - .setExecutor(new DefaultNutsArtifactCall(session.id().parser().parse("net.thevpc.nuts.toolbox:nsh"))) + .setExecutor(new DefaultNutsArtifactCall(NutsId.of("net.thevpc.nuts.toolbox:nsh",session))) .build(); } - return session.descriptor().parser().parse(comment.getValidString()); + return NutsDescriptorParser.of(session).parse(comment.getValidString()); } finally { if (r != null) { r.close(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/ZipDescriptorContentParserComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/ZipDescriptorContentParserComponent.java index 8f7991f06..e717b0323 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/ZipDescriptorContentParserComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/parsers/ZipDescriptorContentParserComponent.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
* is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -11,7 +11,7 @@ * architecture to help supporting a large range of sub managers / repositories. * *
- * + *

* Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -23,10 +23,12 @@ * governing permissions and limitations under the License. *
* ==================================================================== -*/ + */ package net.thevpc.nuts.runtime.standalone.parsers; import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.bundles.io.ZipUtils; +import net.thevpc.nuts.spi.*; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -36,16 +38,10 @@ import java.util.LinkedHashSet; import java.util.Set; -import net.thevpc.nuts.runtime.bundles.io.ZipUtils; -import net.thevpc.nuts.spi.NutsDescriptorContentParserComponent; -import net.thevpc.nuts.spi.NutsDescriptorContentParserContext; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.spi.NutsSupportLevelContext; - /** * Created by vpc on 1/15/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class ZipDescriptorContentParserComponent implements NutsDescriptorContentParserComponent { public static final Set POSSIBLE_PATHS = new LinkedHashSet<>(Arrays.asList( @@ -59,13 +55,12 @@ public class ZipDescriptorContentParserComponent implements NutsDescriptorConten @Override public int getSupportLevel(NutsSupportLevelContext criteria) { String e = NutsUtilStrings.trim(criteria.getConstraints().getFileExtension()); - switch (e){ + switch (e) { case "zip": case "gzip": case "jar": case "war": - case "ear": - { + case "ear": { return DEFAULT_SUPPORT; } } @@ -80,8 +75,8 @@ public NutsDescriptor parse(NutsDescriptorContentParserContext parserContext) { ByteArrayOutputStream buffer = new ByteArrayOutputStream(); try { if (ZipUtils.extractFirstPath(parserContext.getFullStream(), POSSIBLE_PATHS, buffer, true)) { - return parserContext.getSession().descriptor().parser() - .setSession(parserContext.getSession()) + NutsSession session = parserContext.getSession(); + return NutsDescriptorParser.of(session) .parse(buffer.toByteArray()); } } catch (IOException e) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/AbstractNutsRepositoryBase.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/AbstractNutsRepositoryBase.java index 22e340bf4..fddd94dcb 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/AbstractNutsRepositoryBase.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/AbstractNutsRepositoryBase.java @@ -50,7 +50,7 @@ public abstract class AbstractNutsRepositoryBase extends AbstractNutsRepository public AbstractNutsRepositoryBase(NutsAddRepositoryOptions options, NutsSession session, NutsRepository parentRepository, NutsSpeedQualifier speed, boolean supportedMirroring, String repositoryType) { this.initSession=session; - LOG = session.log().of(AbstractNutsRepositoryBase.class); + LOG = NutsLogger.of(AbstractNutsRepositoryBase.class,session); init(options, session, parentRepository, speed, supportedMirroring, repositoryType); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsDeployRepositoryCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsDeployRepositoryCommand.java index b9490f0a5..21b3c7ae4 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsDeployRepositoryCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsDeployRepositoryCommand.java @@ -51,7 +51,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsDeployRepositoryCommand.class); + LOG = NutsLogger.of(DefaultNutsDeployRepositoryCommand.class,session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsFetchContentRepositoryCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsFetchContentRepositoryCommand.java index edbed7365..2a7affa72 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsFetchContentRepositoryCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsFetchContentRepositoryCommand.java @@ -52,7 +52,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsFetchContentRepositoryCommand.class); + LOG = NutsLogger.of(DefaultNutsFetchContentRepositoryCommand.class,session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsFetchDescriptorRepositoryCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsFetchDescriptorRepositoryCommand.java index 37480128a..91ae811ee 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsFetchDescriptorRepositoryCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsFetchDescriptorRepositoryCommand.java @@ -53,7 +53,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsFetchDescriptorRepositoryCommand.class); + LOG = NutsLogger.of(DefaultNutsFetchDescriptorRepositoryCommand.class,session); } return LOG; } @@ -95,7 +95,7 @@ public NutsFetchDescriptorRepositoryCommand run() { id = id.builder().setFaceDescriptor().build(); d = xrepo.fetchDescriptorImpl(id, getFetchMode(), session); } else { - NutsIdFilter filter = CoreFilterUtils.idFilterOf(id.getProperties(), session.id().filter().byName(id.getFullName()), null, session); + NutsIdFilter filter = CoreFilterUtils.idFilterOf(id.getProperties(), NutsIdFilters.of(session).byName(id.getFullName()), null, session); NutsId a = xrepo.searchLatestVersion(id.builder().setVersion("").build(), filter, getFetchMode(), session); if (a == null) { throw new NutsNotFoundException(getSession(), id.getLongId()); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsInstalledRepository.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsInstalledRepository.java index ef5e77217..df42efd87 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsInstalledRepository.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsInstalledRepository.java @@ -35,7 +35,10 @@ import net.thevpc.nuts.runtime.core.repos.NutsInstalledRepository; import net.thevpc.nuts.runtime.core.repos.NutsRepositoryConfigModel; import net.thevpc.nuts.runtime.core.repos.NutsRepositoryExt0; -import net.thevpc.nuts.runtime.core.util.*; +import net.thevpc.nuts.runtime.core.util.CoreCollectionUtils; +import net.thevpc.nuts.runtime.core.util.CoreIOUtils; +import net.thevpc.nuts.runtime.core.util.CoreNutsUtils; +import net.thevpc.nuts.runtime.core.util.NutsIdFilterToPredicate; import net.thevpc.nuts.runtime.standalone.DefaultNutsInstallInfo; import net.thevpc.nuts.runtime.standalone.DefaultNutsWorkspace; import net.thevpc.nuts.runtime.standalone.repocommands.*; @@ -81,7 +84,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsInstalledRepository.class); + LOG = NutsLogger.of(DefaultNutsInstalledRepository.class,session); } return LOG; } @@ -257,8 +260,8 @@ public void uninstall(NutsDefinition def, NutsSession session) { String v = getDefaultVersion(def.getId(), session); if (v != null && v.equals(def.getId().getVersion().getValue())) { Iterator versions = searchVersions().setId(def.getId()) - .setFilter(session.id().filter().byInstallStatus( - session.filters().installStatus().byInstalled(true) + .setFilter(NutsIdFilters.of(session).byInstallStatus( + NutsInstallStatusFilters.of(session).byInstalled(true) )) //search only in installed, ignore deployed! .setFetchMode(NutsFetchMode.LOCAL) .setSession(session).getResult(); @@ -296,7 +299,7 @@ public NutsId pathToId(Path path, NutsSession session) { String p = path.toString().substring(rootFolder.toString().length()); List split = StringTokenizerUtils.split(p, "/\\"); if (split.size() >= 4) { - return session.id().builder().setArtifactId(split.get(split.size() - 3)) + return NutsIdBuilder.of(session).setArtifactId(split.get(split.size() - 3)) .setGroupId(String.join(".", split.subList(0, split.size() - 3))) .setVersion(split.get(split.size() - 2)).build(); @@ -353,10 +356,10 @@ public synchronized void addDependency(NutsId from, NutsId to, NutsDependencySco printJson(from, NUTS_INSTALL_FILE, fi, session); } Set list = loadDependenciesFrom(from, scope, session); - NutsElementFormat element = session.elem().setSession(session); + NutsElements element = NutsElements.of(session); if (!list.contains(to)) { list.add(to); - element.setContentType(NutsContentType.JSON).setValue(list.toArray(new NutsId[0])) + element.json().setValue(list.toArray(new NutsId[0])) .setSession(session) .setNtf(false) .print(getDepsPath(from, true, scope, session)); @@ -364,7 +367,7 @@ public synchronized void addDependency(NutsId from, NutsId to, NutsDependencySco list = loadfindDependenciesTo(to, scope, session); if (!list.contains(from)) { list.add(from); - element.setContentType(NutsContentType.JSON).setValue(list.toArray(new NutsId[0])) + element.json().setValue(list.toArray(new NutsId[0])) .setSession(session) .setNtf(false) .print(getDepsPath(to, false, scope, session)); @@ -385,17 +388,18 @@ public synchronized void removeDependency(NutsId from, NutsId to, NutsDependency } Set list = loadDependenciesFrom(from, scope, session); boolean stillRequired = false; + NutsElements elem = NutsElements.of(session); if (list.contains(to)) { list.remove(to); stillRequired = list.size() > 0; - session.elem().setContentType(NutsContentType.JSON).setValue(list.toArray(new NutsId[0])) + elem.json().setValue(list.toArray(new NutsId[0])) .setNtf(false) .print(getDepsPath(from, true, scope, session)); } list = loadfindDependenciesTo(to, scope, session); if (list.contains(from)) { list.remove(from); - session.elem().setContentType(NutsContentType.JSON).setValue(list.toArray(new NutsId[0])) + elem.json().setValue(list.toArray(new NutsId[0])) .setNtf(false) .print(getDepsPath(to, false, scope, session)); } @@ -408,7 +412,7 @@ public synchronized void removeDependency(NutsId from, NutsId to, NutsDependency public synchronized Set loadDependenciesFrom(NutsId from, NutsDependencyScope scope, NutsSession session) { Path path = getDepsPath(from, true, scope, session); if (Files.isRegularFile(path)) { - NutsId[] old = session.elem().setSession(session).setContentType(NutsContentType.JSON).parse(path, NutsId[].class); + NutsId[] old = NutsElements.of(session).setSession(session).json().parse(path, NutsId[].class); return new HashSet(Arrays.asList(old)); } return new HashSet<>(); @@ -417,7 +421,7 @@ public synchronized Set loadDependenciesFrom(NutsId from, NutsDependency public synchronized Set loadfindDependenciesTo(NutsId from, NutsDependencyScope scope, NutsSession session) { Path path = getDepsPath(from, false, scope, session); if (Files.isRegularFile(path)) { - NutsId[] old = session.elem().setSession(session).setContentType(NutsContentType.JSON).parse(path, NutsId[].class); + NutsId[] old = NutsElements.of(session).setSession(session).json().parse(path, NutsId[].class); return new HashSet(Arrays.asList(old)); } return new HashSet<>(); @@ -435,13 +439,14 @@ public InstallInfoConfig getInstallInfoConfig(NutsId id, Path path, NutsSession // } Path finalPath = path; if (Files.isRegularFile(path)) { - InstallInfoConfig c = session.concurrent().lock().setSource(path).setSession(session).call( - () -> session.elem().setContentType(NutsContentType.JSON).parse(finalPath, InstallInfoConfig.class), + NutsElements elem = NutsElements.of(session); + InstallInfoConfig c = NutsLocks.of(session).setSource(path).call( + () -> elem.json().parse(finalPath, InstallInfoConfig.class), CoreNutsUtils.LOCK_TIME, CoreNutsUtils.LOCK_TIME_UNIT ); if (c != null) { boolean changeStatus = false; - NutsVersion v = session.version().parser().parse(c.getConfigVersion()); + NutsVersion v = NutsVersion.of(c.getConfigVersion(),session); if (v.isBlank()) { c.setInstalled(true); c.setConfigVersion("0.5.8"); //last version before 0.6 @@ -463,11 +468,11 @@ public InstallInfoConfig getInstallInfoConfig(NutsId id, Path path, NutsSession } } if (changeStatus && !session.config().isReadOnly()) { - session.concurrent().lock().setSource(path).call(() -> { + NutsLocks.of(session).setSource(path).call(() -> { _LOGOP(session).level(Level.CONFIG) .log(NutsMessage.jstyle("install-info upgraded {0}", finalPath)); c.setConfigVersion(workspace.getApiVersion().toString()); - session.elem().setContentType(NutsContentType.JSON).setValue(c) + elem.json().setValue(c) .setNtf(false) .print(finalPath); return null; @@ -631,15 +636,15 @@ public void addString(NutsId id, String name, String value, NutsSession session) } public T readJson(NutsId id, String name, Class clazz, NutsSession session) { - return session.elem() - .setSession(session).setContentType(NutsContentType.JSON) + return NutsElements.of(session) + .setSession(session).json() .parse(getPath(id, name, session), clazz); } public void printJson(NutsId id, String name, InstallInfoConfig value, NutsSession session) { value.setConfigVersion(workspace.getApiVersion().toString()); - session.elem().setNtf(false) - .setSession(session).setContentType(NutsContentType.JSON).setValue(value) + NutsElements.of(session).setNtf(false) + .setSession(session).json().setValue(value) .print(getPath(id, name, session)); } @@ -767,7 +772,7 @@ protected Iterator iterator() { public NutsId apply(File folder) { if (folder.isDirectory() && new File(folder, NUTS_INSTALL_FILE).isFile()) { - NutsVersion vv = getSession().version().parser().parse(folder.getName()); + NutsVersion vv = NutsVersion.of(folder.getName(),getSession()); NutsIdFilter filter = getFilter(); NutsSession session = getSession(); if (filter0.acceptVersion(vv, session) && (filter == null || filter.acceptId( diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsPushRepositoryCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsPushRepositoryCommand.java index c9545ea93..d957c895d 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsPushRepositoryCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsPushRepositoryCommand.java @@ -32,7 +32,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsPushRepositoryCommand.class); + LOG = NutsLogger.of(DefaultNutsPushRepositoryCommand.class,session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepoFactoryComponent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepoFactoryComponent.java index f0087a7b4..9d5541ba6 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepoFactoryComponent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepoFactoryComponent.java @@ -23,25 +23,26 @@ */ package net.thevpc.nuts.runtime.standalone.repos; -import java.io.File; import net.thevpc.nuts.*; +import net.thevpc.nuts.runtime.core.repos.NutsRepositorySelector; +import net.thevpc.nuts.runtime.core.repos.NutsRepositoryType; +import net.thevpc.nuts.runtime.core.repos.NutsRepositoryURL; import net.thevpc.nuts.runtime.core.util.CoreIOUtils; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.spi.NutsRepositoryFactoryComponent; +import net.thevpc.nuts.spi.NutsSupportLevelContext; +import java.io.File; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Map; -import net.thevpc.nuts.runtime.core.repos.NutsRepositorySelector; -import net.thevpc.nuts.runtime.core.repos.NutsRepositoryType; -import net.thevpc.nuts.runtime.core.repos.NutsRepositoryURL; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.spi.NutsSupportLevelContext; /** * Created by vpc on 1/15/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class DefaultNutsRepoFactoryComponent implements NutsRepositoryFactoryComponent { @Override @@ -60,11 +61,9 @@ public int getSupportLevel(NutsSupportLevelContext criteri return DEFAULT_SUPPORT; } if (nru.isHttp()) { - NutsPath in = criteria.getSession().io().path( - nru.getLocation() + "/nuts-repository.json" - ); + NutsPath in = NutsPath.of(nru.getLocation(), criteria.getSession()).resolve("nuts-repository.json"); try (InputStream s = in.getInputStream()) { - Map m = criteria.getSession().elem().setSession(criteria.getSession()).setContentType(NutsContentType.JSON) + Map m = NutsElements.of(criteria.getSession()).setSession(criteria.getSession()).setContentType(NutsContentType.JSON) .parse(s, Map.class); if (m != null) { String type = (String) m.get("type"); @@ -122,7 +121,7 @@ public int getSupportLevel(NutsSupportLevelContext criteri public NutsAddRepositoryOptions[] getDefaultRepositories(NutsSession session) { if (!session.config().isGlobal()) { return new NutsAddRepositoryOptions[]{ - NutsRepositorySelector.createRepositoryOptions(NutsRepositorySelector.parseSelection("system"), true, session) + NutsRepositorySelector.createRepositoryOptions(NutsRepositorySelector.parseSelection("system"), true, session) }; } return new NutsAddRepositoryOptions[0]; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepositoryConfigModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepositoryConfigModel.java index d78d1f17a..86071bbd7 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepositoryConfigModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepositoryConfigModel.java @@ -97,7 +97,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsRepositoryConfigModel.class); + LOG = NutsLogger.of(DefaultNutsRepositoryConfigModel.class,session); } return LOG; } @@ -210,7 +210,7 @@ public String getGroups(NutsSession session) { public String getLocation(boolean expand,NutsSession session) { String s = config.getLocation(); if (s != null && expand) { - s = session.io().path(s).builder().withWorkspaceBaseDir().build().toString(); + s = NutsPath.of(s,session).builder().withWorkspaceBaseDir().build().toString(); } return s; } @@ -430,7 +430,7 @@ public boolean save(boolean force, NutsSession session) { // if (NutsBlankable.isBlank(config.getConfigVersion())) { // config.setConfigVersion(repository.getWorkspace().getApiVersion()); // } - session.elem().setSession(session).setContentType(NutsContentType.JSON).setValue(config) + NutsElements.of(session).setSession(session).json().setValue(config) .setNtf(false) .print(file); configurationChanged = false; @@ -440,13 +440,13 @@ public boolean save(boolean force, NutsSession session) { .log(NutsMessage.jstyle( "{0} created repository {1} at {2}", CoreStringUtils.alignLeft(repository.getName(), 20) , repository.getName() , - session.text().ofStyled(getStoreLocation(),NutsTextStyle.path()) + NutsTexts.of(session).ofStyled(getStoreLocation(),NutsTextStyle.path()) )); } else { _LOGOP(session).level(Level.CONFIG).verb(NutsLogVerb.SUCCESS).log(NutsMessage.jstyle( "{0} updated repository {1} at {2}", CoreStringUtils.alignLeft(repository.getName(), 20) , repository.getName() , - session.text().ofStyled(getStoreLocation(),NutsTextStyle.path()) + NutsTexts.of(session).ofStyled(getStoreLocation(),NutsTextStyle.path()) )); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepositoryUndeployCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepositoryUndeployCommand.java index e241a5cfb..14cddb36b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepositoryUndeployCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsRepositoryUndeployCommand.java @@ -37,7 +37,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsRepositoryUndeployCommand.class); + LOG = NutsLogger.of(DefaultNutsRepositoryUndeployCommand.class,session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsSearchRepositoryCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsSearchRepositoryCommand.java index 7fbbd6d1f..9ca1343d8 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsSearchRepositoryCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsSearchRepositoryCommand.java @@ -34,7 +34,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsSearchRepositoryCommand.class); + LOG = NutsLogger.of(DefaultNutsSearchRepositoryCommand.class,session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsSearchVersionsRepositoryCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsSearchVersionsRepositoryCommand.java index 1d3dda0d7..dac6b738c 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsSearchVersionsRepositoryCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/DefaultNutsSearchVersionsRepositoryCommand.java @@ -37,7 +37,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsSearchVersionsRepositoryCommand.class); + LOG = NutsLogger.of(DefaultNutsSearchVersionsRepositoryCommand.class,session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/FilesFoldersApi.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/FilesFoldersApi.java index 98339dea1..6e10b03b8 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/FilesFoldersApi.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/FilesFoldersApi.java @@ -31,14 +31,13 @@ public class FilesFoldersApi { private static Item[] getDirList(boolean folders, boolean files, String baseUrl, NutsSession session) { // List all = new ArrayList<>(); - NutsWorkspace ws = session.getWorkspace(); String dotFilesUrl = baseUrl; // NutsVersion versionString = ws.version().parser().parse("0.5.5"); try { - session.getTerminal().printProgress("%-8s %s","browse", session.io().path(baseUrl).toCompressedForm()); + session.getTerminal().printProgress("%-8s %s","browse", NutsPath.of(baseUrl,session).toCompressedForm()); List splitted = null; try (InputStream foldersFileStream - = session.io().monitor().setSource(dotFilesUrl).setSession(session).create()) { + = NutsInputStreamMonitor.of(session).setSource(dotFilesUrl).create()) { splitted = new WebHtmlListParser().parse(foldersFileStream); } catch (IOException ex) { // @@ -68,7 +67,7 @@ private static Item[] getDirList(boolean folders, boolean files, String baseUrl, } } } catch (UncheckedIOException | NutsIOException ex) { - session.log().of(FilesFoldersApi.class).with().level(Level.FINE).verb(NutsLogVerb.FAIL) + NutsLoggerOp.of(FilesFoldersApi.class,session).level(Level.FINE).verb(NutsLogVerb.FAIL) .log(NutsMessage.jstyle("unable to navigate : file not found {0}", dotFilesUrl)); } return all.toArray(new Item[0]); @@ -91,10 +90,10 @@ private static Item[] getDirText(boolean folders, boolean files, String baseUrl, NutsWorkspace ws = session.getWorkspace(); InputStream foldersFileStream = null; String dotFilesUrl = baseUrl + "/" + CoreNutsConstants.Files.DOT_FILES; - NutsVersion versionString = session.version().parser().parse("0.5.5"); + NutsVersion versionString = NutsVersion.of("0.5.5",session); try { - session.getTerminal().printProgress("%-8s %s", "browse",session.io().path(baseUrl).toCompressedForm()); - foldersFileStream = session.io().monitor().setSource(dotFilesUrl).setSession(session).create(); + session.getTerminal().printProgress("%-8s %s", "browse",NutsPath.of(baseUrl,session).toCompressedForm()); + foldersFileStream = NutsInputStreamMonitor.of(session).setSource(dotFilesUrl).create(); List splitted = StringTokenizerUtils.split(CoreIOUtils.loadString(foldersFileStream, true), "\n\r"); for (String s : splitted) { s = s.trim(); @@ -103,7 +102,7 @@ private static Item[] getDirText(boolean folders, boolean files, String baseUrl, if (all.isEmpty()) { s = s.substring(1).trim(); if (s.startsWith("version=")) { - versionString = session.version().parser().parse(s.substring("version=".length()).trim()); + versionString = NutsVersion.of(s.substring("version=".length()).trim(),session); } } } else { @@ -141,19 +140,19 @@ private static Item[] getDirText(boolean folders, boolean files, String baseUrl, } } } catch (UncheckedIOException | NutsIOException ex) { - session.log().of(FilesFoldersApi.class).with().level(Level.FINE).verb(NutsLogVerb.FAIL) + NutsLoggerOp.of(FilesFoldersApi.class,session).level(Level.FINE).verb(NutsLogVerb.FAIL) .log(NutsMessage.jstyle("unable to navigate : file not found {0}", dotFilesUrl)); } if (versionString.compareTo("0.5.7") < 0) { if (folders) { String[] foldersFileContent = null; String dotFolderUrl = baseUrl + "/" + CoreNutsConstants.Files.DOT_FOLDERS; - try (InputStream stream = session.io().monitor().setSource(dotFolderUrl) - .setSession(session).create()) { + try (InputStream stream = NutsInputStreamMonitor.of(session).setSource(dotFolderUrl) + .create()) { foldersFileContent = StringTokenizerUtils.split(CoreIOUtils.loadString(stream, true), "\n\r") .stream().map(x -> x.trim()).filter(x -> x.length() > 0).toArray(String[]::new); } catch (IOException | UncheckedIOException | NutsIOException ex) { - session.log().of(FilesFoldersApi.class).with().level(Level.FINE).verb(NutsLogVerb.FAIL) + NutsLoggerOp.of(FilesFoldersApi.class,session).level(Level.FINE).verb(NutsLogVerb.FAIL) .log(NutsMessage.jstyle("unable to navigate : file not found {0}", dotFolderUrl)); } if (foldersFileContent != null) { @@ -181,7 +180,7 @@ public NutsId validate(NutsId id, NutsDescriptor t, String pathname, String root try { nutsDescriptor = NutsWorkspaceExt.of(session.getWorkspace()).resolveEffectiveDescriptor(t, session); } catch (Exception ex) { - session.log().of(FilesFoldersApi.class).with().session(session).level(Level.FINE).error(ex).log( + NutsLoggerOp.of(FilesFoldersApi.class,session).level(Level.FINE).error(ex).log( NutsMessage.jstyle("error resolving effective descriptor for {0} in url {1} : {2}", t.getId(), pathname, ex));//e.printStackTrace(); @@ -206,11 +205,10 @@ public NutsId validate(NutsId id, NutsDescriptor t, String pathname, String root public NutsId parseId(String pathname, String rootPath, NutsIdFilter filter, NutsRepository repository, NutsSession session) throws IOException { NutsDescriptor t = null; try { - t = parseDescriptor(pathname, session.io() - .monitor().setSource(pathname).setSession(session).create(), + t = parseDescriptor(pathname, NutsInputStreamMonitor.of(session).setSource(pathname).create(), NutsFetchMode.LOCAL, repository, session, rootPath); } catch (Exception ex) { - session.log().of(FilesFoldersApi.class).with().session(session).level(Level.FINE).error(ex) + NutsLoggerOp.of(FilesFoldersApi.class,session).level(Level.FINE).error(ex) .log(NutsMessage.jstyle("error parsing url : {0} : {1}", pathname, toString()));//e.printStackTrace(); } if (t != null) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/FilesFoldersApiIdIterator.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/FilesFoldersApiIdIterator.java index 949b06d40..ed7416e6a 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/FilesFoldersApiIdIterator.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/FilesFoldersApiIdIterator.java @@ -113,7 +113,7 @@ public boolean hasNext() { try { t = model.parseId(file.path, rootUrl, filter, repository, session); } catch (Exception ex) { - session.log().of(FilesFoldersApi.class).with().session(session).level(Level.FINE).error(ex) + NutsLoggerOp.of(FilesFoldersApi.class,session).level(Level.FINE).error(ex) .log(NutsMessage.jstyle("error parsing url : {0} : {1}", file.path, toString()));//e.printStackTrace(); } if (t != null) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsCachedRepository.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsCachedRepository.java index b065ecb9c..c42e7f2e9 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsCachedRepository.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsCachedRepository.java @@ -66,7 +66,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(NutsCachedRepository.class); + LOG = NutsLogger.of(NutsCachedRepository.class,session); } return LOG; } @@ -87,7 +87,7 @@ public NutsDescriptor fetchDescriptorImpl(NutsId id, NutsFetchMode fetchMode, Nu } RuntimeException mirrorsEx = null; - SuccessFailResult res = session.concurrent().lock().setSource(id.builder().setFaceDescriptor().build()).call(() -> { + SuccessFailResult res = NutsLocks.of(session).setSource(id.builder().setFaceDescriptor().build()).call(() -> { try { NutsDescriptor success = fetchDescriptorCore(id, fetchMode, session); if (success != null) { @@ -186,7 +186,7 @@ public final NutsContent fetchContentImpl(NutsId id, NutsDescriptor descriptor, RuntimeException mirrorsEx = null; NutsContent c = null; - SuccessFailResult res = session.concurrent().lock().setSource(id.builder().setFaceContent().build()).call(() -> { + SuccessFailResult res = NutsLocks.of(session).setSource(id.builder().setFaceContent().build()).call(() -> { if (cache.isWriteEnabled()) { Path cachePath = cache.getLongIdLocalFile(id, session); NutsContent c2 = fetchContentCore(id, descriptor, cachePath.toString(), fetchMode, session); @@ -195,13 +195,13 @@ public final NutsContent fetchContentImpl(NutsId id, NutsDescriptor descriptor, //already deployed because fetchContentImpl2 is run against cachePath // cache.deployContent(id, c.getPath(), session); if (localPath2 != null) { - session.io().copy() + NutsCp.of(session) .from(cachePath).to(localPath2).run(); } else { localPath2 = cachePath.toString(); } return SuccessFailResult.success(new NutsDefaultContent( - session.io().path(localPath2), true, false)); + NutsPath.of(localPath2,session), true, false)); } else { return SuccessFailResult.fail(new NutsNotFoundException(session, id)); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsHttpFolderRepository.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsHttpFolderRepository.java index 2b38e68b4..d2abaa358 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsHttpFolderRepository.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsHttpFolderRepository.java @@ -62,7 +62,7 @@ public boolean isDescFile(String pathname) { @Override public NutsDescriptor parseDescriptor(String pathname, InputStream in, NutsFetchMode fetchMode, NutsRepository repository, NutsSession session, String rootURL) throws IOException { try { - return session.descriptor().parser().setSession(session).parse(in); + return NutsDescriptorParser.of(session).parse(in); } finally { in.close(); } @@ -72,7 +72,7 @@ public NutsDescriptor parseDescriptor(String pathname, InputStream in, NutsFetch public NutsHttpFolderRepository(NutsAddRepositoryOptions options, NutsSession session, NutsRepository parentRepository) { super(options, session, parentRepository, NutsSpeedQualifier.SLOW, false, NutsConstants.RepoTypes.NUTS); - LOG = session.log().of(NutsHttpFolderRepository.class); + LOG = NutsLogger.of(NutsHttpFolderRepository.class,session); } private boolean isDescFile0(String pathname) { @@ -107,11 +107,11 @@ protected String getDescPath(NutsId id, NutsSession session) { } protected InputStream openStream(String path, Object source, String sourceTypeName, NutsSession session) { - return session.io().monitor().setSource(path).setOrigin(source).setSourceTypeName(sourceTypeName).create(); + return NutsInputStreamMonitor.of(session).setSource(path).setOrigin(source).setSourceTypeName(sourceTypeName).create(); } protected InputStream openStream(NutsId id, String path, Object source, String sourceTypeName, NutsSession session) { - return session.io().monitor().setSource(path).setOrigin(source).setSourceTypeName(sourceTypeName).create(); + return NutsInputStreamMonitor.of(session).setSource(path).setOrigin(source).setSourceTypeName(sourceTypeName).create(); } public Iterator findVersionsImplGithub(NutsId id, NutsIdFilter idFilter, NutsSession session) { @@ -132,8 +132,8 @@ public Iterator findVersionsImplGithub(NutsId id, NutsIdFilter idFilter, } catch (UncheckedIOException | NutsIOException ex) { throw new NutsNotFoundException(session, id, ex); } - List> info = session.elem() - .setContentType(NutsContentType.JSON).parse(new InputStreamReader(metadataStream), List.class); + List> info = NutsElements.of(session) + .json().parse(new InputStreamReader(metadataStream), List.class); if (info != null) { for (Map version : info) { if ("dir".equals(version.get("type"))) { @@ -143,7 +143,7 @@ public Iterator findVersionsImplGithub(NutsId id, NutsIdFilter idFilter, if (idFilter != null && !idFilter.acceptId(nutsId, session)) { continue; } - ret.add(session.id().builder() + ret.add(NutsIdBuilder.of(session) .setGroupId(groupId) .setArtifactId(artifactId) .setVersion(versionName).build() @@ -224,8 +224,8 @@ public Iterator searchVersionsCore(NutsId id, NutsIdFilter idFilter, Nut } return ret.iterator(); } else { - NutsIdFilter filter2 = session.id().filter().nonnull(idFilter).and( - session.id().filter().byName(id.getShortName()) + NutsIdFilter filter2 = NutsIdFilters.of(session).nonnull(idFilter).and( + NutsIdFilters.of(session).byName(id.getShortName()) ); switch (versionApi) { case DEFAULT: @@ -271,7 +271,7 @@ public NutsDescriptor fetchDescriptorCore(NutsId id, NutsFetchMode fetchMode, Nu throw new NutsNotFoundException(session, id, new NutsFetchModeNotSupportedException(session, this, fetchMode, id.toString(), null)); } try (InputStream stream = getDescStream(id, session)) { - return session.descriptor().parser().setSession(session).parse(stream); + return NutsDescriptorParser.of(session).parse(stream); } catch (IOException | UncheckedIOException | NutsIOException ex) { throw new NutsNotFoundException(session, id, ex); } @@ -284,16 +284,16 @@ public NutsContent fetchContentCore(NutsId id, NutsDescriptor descriptor, String } if (descriptor.getLocations().length == 0) { String path = getPath(id, session); - session.io().copy().from(path).to(localFile).setSafe(true).setLogProgress(true).run(); + NutsCp.of(session).from(path).to(localFile).setSafe(true).setLogProgress(true).run(); return new NutsDefaultContent( - session.io().path(localFile), false, false); + NutsPath.of(localFile,session), false, false); } else { for (NutsIdLocation location : descriptor.getLocations()) { if (CoreNutsUtils.acceptClassifier(location, id.getClassifier())) { try { - session.io().copy().from(location.getUrl()).to(localFile).setSafe(true).setLogProgress(true).run(); + NutsCp.of(session).from(location.getUrl()).to(localFile).setSafe(true).setLogProgress(true).run(); return new NutsDefaultContent( - session.io().path(localFile), false, false); + NutsPath.of(localFile,session), false, false); } catch (Exception ex) { LOG.with().session(session).level(Level.SEVERE).error(ex) .log(NutsMessage.jstyle("unable to download location for id {0} in location {1} : {2}", id, location.getUrl(), ex)); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsHttpSrvRepository.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsHttpSrvRepository.java index 39a59c859..b519de028 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsHttpSrvRepository.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsHttpSrvRepository.java @@ -49,9 +49,9 @@ public class NutsHttpSrvRepository extends NutsCachedRepository { public NutsHttpSrvRepository(NutsAddRepositoryOptions options, NutsSession session, NutsRepository parentRepository) { super(options, session, parentRepository, NutsSpeedQualifier.SLOW, false, "nuts:api"); - LOG = session.log().of(NutsHttpSrvRepository.class); + LOG = NutsLogger.of(NutsHttpSrvRepository.class,session); try { - remoteId = session.id().parser().setLenient(false).parse((options.getLocation() + "/version")); + remoteId = getRemoteId(session); } catch (Exception ex) { LOG.with().session(session).level(Level.WARNING).verb(NutsLogVerb.FAIL) .log(NutsMessage.jstyle("unable to initialize Repository NutsId for repository {0}", options.getLocation())); @@ -65,7 +65,7 @@ public String getUrl(String path) { public NutsId getRemoteId(NutsSession session) { if (remoteId == null) { try { - remoteId = session.id().parser().setLenient(false).parse(httpGetString(getUrl("/version"), session)); + remoteId = NutsId.of(httpGetString(getUrl("/version"), session),session); } catch (Exception ex) { LOG.with().session(session).level(Level.WARNING).verb(NutsLogVerb.FAIL) .log(NutsMessage.jstyle("unable to resolve Repository NutsId for remote repository {0}", config().getLocation(false))); @@ -84,13 +84,13 @@ public void pushImpl(NutsPushRepositoryCommand command) { } NutsWorkspaceUtils.checkSession(getWorkspace(), session); ByteArrayOutputStream descStream = new ByteArrayOutputStream(); - session.descriptor().formatter(desc).print(new OutputStreamWriter(descStream)); + desc.formatter().setSession(session).print(new OutputStreamWriter(descStream)); httpUpload(CoreIOUtils.buildUrl(config().getLocation(true), "/deploy?" + resolveAuthURLPart(session)), session, new NutsTransportParamBinaryStreamPart("descriptor", "Project.nuts", new ByteArrayInputStream(descStream.toByteArray())), new NutsTransportParamBinaryFilePart("content", content.getPath().getName(), content.getFilePath()), - new NutsTransportParamParamPart("descriptor-hash", session.io().hash().sha1().setSource(desc).computeString()), + new NutsTransportParamParamPart("descriptor-hash", NutsHash.of(session).sha1().setSource(desc).computeString()), new NutsTransportParamParamPart("content-hash", CoreIOUtils.evalSHA1Hex(content.getFilePath())), new NutsTransportParamParamPart("force", String.valueOf(session.isYes())) ); @@ -104,7 +104,7 @@ public NutsDescriptor fetchDescriptorCore(NutsId id, NutsFetchMode fetchMode, Nu boolean transitive = session.isTransitive(); session.getTerminal().printProgress("loading descriptor for ", id.getLongId()); try (InputStream stream = CoreIOUtils.getHttpClientFacade(session, getUrl("/fetch-descriptor?id=" + CoreIOUtils.urlEncodeString(id.toString()) + (transitive ? ("&transitive") : "") + "&" + resolveAuthURLPart(session))).open()) { - NutsDescriptor descriptor = session.descriptor().parser().setSession(session).parse(stream); + NutsDescriptor descriptor = NutsDescriptorParser.of(session).parse(stream); if (descriptor != null) { String hash = httpGetString(getUrl("/fetch-descriptor-hash?id=" + CoreIOUtils.urlEncodeString(id.toString()) + (transitive ? ("&transitive") : "") + "&" + resolveAuthURLPart(session)), session); if (hash.equals(descriptor.toString())) { @@ -131,8 +131,8 @@ public Iterator searchVersionsCore(NutsId id, NutsIdFilter idFilter, Nut return IteratorUtils.emptyIterator(); } Iterator it = new NamedNutIdFromStreamIterator(ret,session); - NutsIdFilter filter2 = session.id().filter().nonnull(idFilter).and( - session.id().filter().byName(id.getShortName()) + NutsIdFilter filter2 = NutsIdFilters.of(session).nonnull(idFilter).and( + NutsIdFilters.of(session).byName(id.getShortName()) ); if (filter2 != null) { it = IteratorBuilder.of(it).filter(CoreFilterUtils.createFilter(filter2, session)).iterator(); @@ -187,20 +187,19 @@ public NutsContent fetchContentCore(NutsId id, NutsDescriptor descriptor, String if (localPath == null) { temp = true; String p = getIdFilename(id, session); - localPath = session.io().tmp() - .setSession(session) + localPath = NutsTmp.of(session) .setRepositoryId(getUuid()) .createTempFile(new File(p).getName()).toString(); } try { String location = getUrl("/fetch?id=" + CoreIOUtils.urlEncodeString(id.toString()) + (transitive ? ("&transitive") : "") + "&" + resolveAuthURLPart(session)); - session.io().copy().from(location).to(localPath).setSafe(true).setLogProgress(true).run(); + NutsCp.of(session).from(location).to(localPath).setSafe(true).setLogProgress(true).run(); String rhash = httpGetString(getUrl("/fetch-hash?id=" + CoreIOUtils.urlEncodeString(id.toString()) + (transitive ? ("&transitive") : "") + "&" + resolveAuthURLPart(session)), session); String lhash = CoreIOUtils.evalSHA1Hex(Paths.get(localPath)); if (rhash.equalsIgnoreCase(lhash)) { return new NutsDefaultContent( - session.io().path(localPath) + NutsPath.of(localPath,session) , false, temp); } } catch (UncheckedIOException | NutsIOException ex) { @@ -322,7 +321,7 @@ private void close() { @Override public NutsId next() { - NutsId nutsId = session.id().parser().setLenient(false).parse(line); + NutsId nutsId = NutsId.of(line,session); return nutsId.builder().setRepository(getName()).build(); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsRepositoryFolderHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsRepositoryFolderHelper.java index ce418ccb9..089c908a9 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsRepositoryFolderHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsRepositoryFolderHelper.java @@ -99,7 +99,7 @@ public NutsContent fetchContentImpl(NutsId id, String localPath, NutsSession ses Path cacheContent = getLongIdLocalFile(id.builder().setFaceContent().build(), session); if (cacheContent != null && pathExists(cacheContent, session)) { return new NutsDefaultContent( - session.io().path(cacheContent.toString()), + NutsPath.of(cacheContent,session), cacheFolder, false); } return null; @@ -136,7 +136,7 @@ protected NutsDescriptor fetchDescriptorImpl(NutsId id, NutsSession session) { Path versionFolder = getLongIdLocalFolder(id, session); goodFile = versionFolder.resolve(idFilename); if (pathExists(goodFile, session)) { - return session.descriptor().parser().setSession(session).parse(goodFile); + return NutsDescriptorParser.of(session).parse(goodFile); } // String alt = id.getAlternative(); // String goodAlt = null; @@ -198,7 +198,7 @@ protected NutsDescriptor fetchDescriptorImpl(NutsId id, NutsSession session) { protected NutsDescriptor loadMatchingDescriptor(Path file, NutsId id, NutsSession session) { if (pathExists(file, session)) { - NutsDescriptor d = Files.isRegularFile(file) ? session.descriptor().parser().setSession(session).parse(file) : null; + NutsDescriptor d = Files.isRegularFile(file) ? NutsDescriptorParser.of(session).parse(file) : null; if (d != null) { Map query = id.getProperties(); String os = query.get(NutsConstants.IdProperties.OS); @@ -233,8 +233,8 @@ public Iterator searchVersions(NutsId id, final NutsIdFilter filter, boo return null; } NutsWorkspace ws = session.getWorkspace(); - NutsIdFilter filter2 = session.id().filter().all(filter, - session.id().filter().byName(id.getShortName()) + NutsIdFilter filter2 = NutsIdFilters.of(session).all(filter, + NutsIdFilters.of(session).byName(id.getShortName()) ); return findInFolder(getLocalGroupAndArtifactFile(id, session), filter2, deep ? Integer.MAX_VALUE : 1, @@ -283,7 +283,7 @@ public NutsDescriptor parseDescriptor(Path pathname, NutsSession session) throws //this is invalid cache! return null; } else { - return session.descriptor().parser().setSession(session).parse(pathname); + return NutsDescriptorParser.of(session).parse(pathname); } } }, maxDepth); @@ -374,14 +374,14 @@ public NutsDescriptor deploy(NutsDeployRepositoryCommand deployment, NutsConfirm Path pckFile = deployContent(id, inputSource, descriptor, writeType, session); if (repo != null) { NutsRepositoryUtils.of(repo).events().fireOnDeploy(new DefaultNutsContentEvent( - session.io().path(pckFile.toString()), deployment, session, repo)); + NutsPath.of(pckFile,session), deployment, session, repo)); } return descriptor.builder().setId(id.getLongId()).build(); } protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultNutsFetchContentRepositoryCommand.class); + LOG = NutsLogger.of(DefaultNutsFetchContentRepositoryCommand.class,session); } return LOG; } @@ -402,11 +402,11 @@ public Path deployDescriptor(NutsId id, NutsDescriptor desc, NutsConfirmationMod return descFile; } } - return session.concurrent().lock().setSource(descFile).call(() -> { + return NutsLocks.of(session).setSource(descFile).call(() -> { - session.descriptor().formatter(desc).setNtf(false).print(descFile); - byte[] bytes = session.io().hash().sha1().setSource(desc).computeString().getBytes(); - session.io().copy() + desc.formatter().setSession(session).setNtf(false).print(descFile); + byte[] bytes = NutsHash.of(session).sha1().setSource(desc).computeString().getBytes(); + NutsCp.of(session) .from( InputStreamMetadataAwareImpl.of( new ByteArrayInputStream(bytes) @@ -448,10 +448,10 @@ public Path deployContent(NutsId id, NutsStreamOrPath content, NutsDescriptor de return pckFile; } } - return session.concurrent().lock().setSource(pckFile).call(() -> { - (content.isPath() ? session.io().copy().from(content.getPath()) : session.io().copy().from(content.getInputStream())) + return NutsLocks.of(session).setSource(pckFile).call(() -> { + (content.isPath() ? NutsCp.of(session).from(content.getPath()) : NutsCp.of(session).from(content.getInputStream())) .to(pckFile).setSafe(true).run(); - session.io().copy().from( + NutsCp.of(session).from( CoreIOUtils.createBytesStream(CoreIOUtils.evalSHA1Hex(pckFile).getBytes(), NutsMessage.cstyle("sha1://%s", id), CoreIOUtils.MIME_TYPE_SHA1, @@ -469,13 +469,13 @@ public boolean undeploy(NutsRepositoryUndeployCommand command) { } Path localFolder = getLongIdLocalFile(command.getId().builder().setFaceContent().build(), command.getSession()); if (localFolder != null && Files.exists(localFolder)) { - if (command.getSession().concurrent().lock().setSource(localFolder).call(() -> { + if (NutsLocks.of(command.getSession()).setSource(localFolder).call(() -> { CoreIOUtils.delete(command.getSession(), localFolder); return false; })) { if (repo != null) { NutsRepositoryUtils.of(repo).events().fireOnUndeploy(new DefaultNutsContentEvent( - command.getSession().io().path(localFolder.toString()) + NutsPath.of(localFolder,command.getSession()) , command, command.getSession(), repo)); return true; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsRepositoryMirroringHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsRepositoryMirroringHelper.java index 8c6785050..5affd87cc 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsRepositoryMirroringHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/repos/NutsRepositoryMirroringHelper.java @@ -81,7 +81,7 @@ protected NutsContent fetchContent(NutsId id, NutsDescriptor descriptor, String .getResult(); if (c != null) { if (localPath != null) { - session.io().copy() + NutsCp.of(session) .from(c.getFilePath()).to(localPath).setSafe(true).run(); } else { return c; @@ -126,7 +126,7 @@ protected NutsDescriptor fetchDescriptorImplInMirrors(NutsId id, NutsFetchMode f // } else { // goodFile = versionFolder.resolve(NutsUtilStrings.trim(a)).resolve(idFilename); // } - session.descriptor().setSession(session).formatter(nutsDescriptor).print(goodFile); + nutsDescriptor.formatter().setSession(session).print(goodFile); return nutsDescriptor; } } @@ -231,7 +231,7 @@ public NutsId searchLatestVersion(NutsId bestId, NutsId id, NutsIdFilter filter, NutsWorkspaceExt dws = NutsWorkspaceExt.of(getWorkspace()); NutsId id2 = dws.resolveEffectiveId(nutsDescriptor, session).builder().setFaceDescriptor().build(); Path localNutFile = cache.getLongIdLocalFile(id2, session); - session.descriptor().formatter(nutsDescriptor).print(localNutFile); + nutsDescriptor.formatter().setSession(session).print(localNutFile); if (bestId == null || id2.getVersion().compareTo(bestId.getVersion()) > 0) { bestId = id2; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/DefaultNutsAuthenticationAgent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/DefaultNutsAuthenticationAgent.java index bce294e61..4331d565c 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/DefaultNutsAuthenticationAgent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/DefaultNutsAuthenticationAgent.java @@ -1,10 +1,11 @@ package net.thevpc.nuts.runtime.standalone.security; import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.spi.NutsSingleton; import net.thevpc.nuts.runtime.bundles.io.CoreSecurityUtils; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class DefaultNutsAuthenticationAgent extends AbstractNutsAuthenticationAgent { public DefaultNutsAuthenticationAgent() { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/DefaultNutsWorkspaceSecurityModel.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/DefaultNutsWorkspaceSecurityModel.java index 7c62fae18..383759ec8 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/DefaultNutsWorkspaceSecurityModel.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/DefaultNutsWorkspaceSecurityModel.java @@ -75,7 +75,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().setSession(session).of(DefaultNutsWorkspaceSecurityModel.class); + LOG = NutsLogger.of(DefaultNutsWorkspaceSecurityModel.class,session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/PlainNutsAuthenticationAgent.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/PlainNutsAuthenticationAgent.java index ddd76ea8a..598c111a4 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/PlainNutsAuthenticationAgent.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/security/PlainNutsAuthenticationAgent.java @@ -1,14 +1,12 @@ package net.thevpc.nuts.runtime.standalone.security; import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsAuthenticationAgent; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.spi.NutsSupportLevelContext; +import net.thevpc.nuts.spi.*; import java.util.Arrays; import java.util.Map; -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class PlainNutsAuthenticationAgent implements NutsAuthenticationAgent { private NutsWorkspace ws; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/DefaultNutsDependencySolvers.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/DefaultNutsDependencySolvers.java new file mode 100644 index 000000000..f5944b63c --- /dev/null +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/DefaultNutsDependencySolvers.java @@ -0,0 +1,41 @@ +package net.thevpc.nuts.runtime.standalone.solvers; + +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.runtime.standalone.config.DefaultNutsWorkspaceConfigManager; +import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; +import net.thevpc.nuts.spi.NutsDependencySolvers; +import net.thevpc.nuts.NutsWorkspace; +import net.thevpc.nuts.spi.NutsDependencySolver; +import net.thevpc.nuts.spi.NutsSupportLevelContext; + +public class DefaultNutsDependencySolvers implements NutsDependencySolvers { + private NutsWorkspace ws; + public DefaultNutsDependencySolvers(NutsWorkspace ws) { + this.ws=ws; + } + + @Override + public NutsDependencySolver createSolver(NutsSession session) { + NutsWorkspaceUtils.checkSession(ws, session); + return createSolver(session.getDependencySolver(),session); + } + + @Override + public NutsDependencySolver createSolver(String solverName,NutsSession session) { + NutsWorkspaceUtils.checkSession(ws, session); + DefaultNutsWorkspaceConfigManager config = (DefaultNutsWorkspaceConfigManager)session.config(); + return config.createDependencySolver(solverName); + } + + @Override + public String[] getSolverNames(NutsSession session) { + NutsWorkspaceUtils.checkSession(ws, session); + DefaultNutsWorkspaceConfigManager config = (DefaultNutsWorkspaceConfigManager)session.config(); + return config.getDependencySolverNames(); + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + return DEFAULT_SUPPORT; + } +} diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/MavenNutsDependencySolver.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/MavenNutsDependencySolver.java index d4baf88e4..46f956e4f 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/MavenNutsDependencySolver.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/MavenNutsDependencySolver.java @@ -66,14 +66,15 @@ public NutsDependencies solve() { NutsDependencyInfoSet mergedVisitedSet = new NutsDependencyInfoSet(); NutsDependencyInfoSet nonMergedVisitedSet = new NutsDependencyInfoSet(); NutsDependencyFilter effDependencyFilter = null; + NutsDependencyFilters filter = NutsDependencyFilters.of(session); if (dependencyFilter == null) { - effDependencyFilter = session.dependency().filter().byOs(session.env().getOsFamily()) - .and(session.dependency().filter().byArch(session.env().getArchFamily())); + effDependencyFilter = filter.byOs(session.env().getOsFamily()) + .and(filter.byArch(session.env().getArchFamily())); } else { effDependencyFilter = dependencyFilter - .and(session.dependency().filter().byOs(session.env().getOsFamily())) - .and(session.dependency().filter().byArch(session.env().getArchFamily())); + .and(filter.byOs(session.env().getOsFamily())) + .and(filter.byArch(session.env().getArchFamily())); } for (NutsDependencyTreeNodeBuild currentNode : defs) { NutsId id = currentNode.getEffectiveId(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/NutsDependencySolvers.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/NutsDependencySolverUtils.java similarity index 86% rename from core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/NutsDependencySolvers.java rename to core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/NutsDependencySolverUtils.java index 006eaee93..48b3cca28 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/NutsDependencySolvers.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/solvers/NutsDependencySolverUtils.java @@ -1,9 +1,8 @@ package net.thevpc.nuts.runtime.standalone.solvers; -import net.thevpc.nuts.NutsBlankable; import net.thevpc.nuts.NutsUtilStrings; -public class NutsDependencySolvers { +public class NutsDependencySolverUtils { public static final String DEFAULT_SOLVER_NAME = "maven"; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/DefaultSourceControlHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/DefaultSourceControlHelper.java index 791b49108..83b1fd74d 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/DefaultSourceControlHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/DefaultSourceControlHelper.java @@ -37,7 +37,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(DefaultSourceControlHelper.class); + LOG = NutsLogger.of(DefaultSourceControlHelper.class,session); } return LOG; } @@ -51,11 +51,11 @@ public NutsId commit(Path folder, NutsSession session) { } Path file = folder.resolve(NutsConstants.Files.DESCRIPTOR_FILE_NAME); - NutsDescriptor d = session.descriptor().parser().setSession(session).parse(file); + NutsDescriptor d = NutsDescriptorParser.of(session).parse(file); String oldVersion = NutsUtilStrings.trim(d.getId().getVersion().getValue()); if (oldVersion.endsWith(CoreNutsConstants.Versions.CHECKED_OUT_EXTENSION)) { oldVersion = oldVersion.substring(0, oldVersion.length() - CoreNutsConstants.Versions.CHECKED_OUT_EXTENSION.length()); - String newVersion = session.version().parser().parse(oldVersion).inc().getValue(); + String newVersion = NutsVersion.of(oldVersion,session).inc().getValue(); NutsDefinition newVersionFound = null; try { newVersionFound = session.fetch().setId(d.getId().builder().setVersion(newVersion).build()).setSession(session).getResultDefinition(); @@ -70,7 +70,7 @@ public NutsId commit(Path folder, NutsSession session) { d = d.builder().setId(d.getId().builder().setVersion(oldVersion + ".1").build()).build(); } NutsId newId = session.deploy().setContent(folder).setDescriptor(d).setSession(session).getResult()[0]; - session.descriptor().formatter(d).print(file); + d.formatter().setSession(session).print(file); CoreIOUtils.delete(session, folder); return newId; } else { @@ -80,7 +80,7 @@ public NutsId commit(Path folder, NutsSession session) { // @Override public NutsDefinition checkout(String id, Path folder, NutsSession session) { - return checkout(session.id().parser().setLenient(false).parse(id), folder, session); + return checkout(NutsId.of(id,session), folder, session); } // @Override @@ -91,19 +91,19 @@ public NutsDefinition checkout(NutsId id, Path folder, NutsSession session) { if ("zip".equals(nutToInstall.getDescriptor().getPackaging())) { try { - ZipUtils.unzip(session, nutToInstall.getPath().toString(), session.io() - .path(folder.toString()).builder().withAppBaseDir().build().toString(), new UnzipOptions().setSkipRoot(false)); + ZipUtils.unzip(session, nutToInstall.getPath().toString(), NutsPath.of(folder,session) + .builder().withAppBaseDir().build().toString(), new UnzipOptions().setSkipRoot(false)); } catch (IOException ex) { throw new UncheckedIOException(ex); } Path file = folder.resolve(NutsConstants.Files.DESCRIPTOR_FILE_NAME); - NutsDescriptor d = session.descriptor().parser().setSession(session).parse(file); + NutsDescriptor d = NutsDescriptorParser.of(session).parse(file); NutsVersion oldVersion = d.getId().getVersion(); NutsId newId = d.getId().builder().setVersion(oldVersion + CoreNutsConstants.Versions.CHECKED_OUT_EXTENSION).build(); d = d.builder().setId(newId).build(); - session.descriptor().formatter(d).print(file); + d.formatter().setSession(session).print(file); NutsIdType idType = NutsWorkspaceExt.of(ws).resolveNutsIdType(newId, session); return new DefaultNutsDefinition( @@ -112,7 +112,7 @@ public NutsDefinition checkout(NutsId id, Path folder, NutsSession session) { newId.getLongId(), d, new NutsDefaultContent( - session.io().path(folder.toString()), + NutsPath.of(folder,session), false, false), null, diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsClassLoaderUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsClassLoaderUtils.java index 00aa100f0..ec9cbbc53 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsClassLoaderUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsClassLoaderUtils.java @@ -49,6 +49,7 @@ public static NutsClassLoaderNode definitionToClassLoaderNode(NutsDefinition def def.getId().toString(), def.getContent().getURL(), true, + true, def.getDependencies().nodes().stream().map(x -> toClassLoaderNode(x, session)) .filter(Objects::nonNull) .toArray(NutsClassLoaderNode[]::new) @@ -78,7 +79,7 @@ private static NutsClassLoaderNode toClassLoaderNode(NutsDependencyTreeNode d, N throw new NutsNotFoundException(session, d.getDependency().toId()); } return new NutsClassLoaderNode( - d.getDependency().toId().toString(), url, true, + d.getDependency().toId().toString(), url, true, true, Arrays.stream(d.getChildren()).map(x -> toClassLoaderNode(x, session)).toArray(NutsClassLoaderNode[]::new) ); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsConfigurableHelper.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsConfigurableHelper.java index d2acad2ae..f872791e1 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsConfigurableHelper.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsConfigurableHelper.java @@ -49,7 +49,7 @@ public class NutsConfigurableHelper { * @return {@code this} instance */ public static T configure(NutsCommandLineConfigurable c, NutsSession session, boolean skipUnsupported, String[] args, String commandName) { - c.configure(skipUnsupported, session.commandLine().create(args).setCommandName(commandName)); + c.configure(skipUnsupported, NutsCommandLine.of(args,session).setCommandName(commandName)); return (T) c; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsJavaSdkUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsJavaSdkUtils.java index 2e915a3fe..32478575c 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsJavaSdkUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsJavaSdkUtils.java @@ -51,7 +51,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(NutsJavaSdkUtils.class); + LOG = NutsLogger.of(NutsJavaSdkUtils.class,session); } return LOG; } @@ -60,7 +60,7 @@ public NutsPlatformLocation resolveJdkLocation(String requestedJavaVersion, Nuts requestedJavaVersion = NutsUtilStrings.trim(requestedJavaVersion); NutsPlatformLocation bestJava = session.env().platforms() .findPlatformByVersion(NutsPlatformType.JAVA, - session.version().filter().byValue(requestedJavaVersion) + NutsVersionFilters.of(session).byValue(requestedJavaVersion) ); if (bestJava == null) { String appSuffix = session.env().getOsFamily() == NutsOsFamily.WINDOWS ? ".exe" : ""; @@ -79,8 +79,8 @@ public NutsPlatformLocation resolveJdkLocation(String requestedJavaVersion, Nuts 0 ); current.setConfigVersion(DefaultNutsWorkspace.VERSION_SDK_LOCATION); - NutsVersionFilter requestedJavaVersionFilter = session.version().parser().parse(requestedJavaVersion).filter(); - if (requestedJavaVersionFilter == null || requestedJavaVersionFilter.acceptVersion(session.version().parser().parse(current.getVersion()), session)) { + NutsVersionFilter requestedJavaVersionFilter = NutsVersion.of(requestedJavaVersion,session).filter(); + if (requestedJavaVersionFilter == null || requestedJavaVersionFilter.acceptVersion(NutsVersion.of(current.getVersion(),session), session)) { bestJava = current; } if (bestJava == null) { @@ -161,7 +161,7 @@ public Future searchJdkLocationsFuture(NutsSession sessi for (String s : conf) { all.add(searchJdkLocationsFuture(Paths.get(s), session)); } - return session.concurrent().executorService().submit(new Callable() { + return session.config().executorService().submit(new Callable() { @Override public NutsPlatformLocation[] call() throws Exception { List locs = new ArrayList<>(); @@ -187,7 +187,7 @@ public NutsPlatformLocation[] searchJdkLocations(String loc, NutsSession session if (r != null) { all.add(r); if (session != null && session.isPlainTrace()) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); session.out().printf("detected java %s %s at %s%n", r.getPackaging(), factory.ofStyled(r.getVersion(), NutsTextStyle.version()), factory.ofStyled(r.getPath(), NutsTextStyle.path()) @@ -211,7 +211,7 @@ public Future searchJdkLocationsFuture(Path s, NutsSessi try (final DirectoryStream it = Files.newDirectoryStream(s)) { for (Path d : it) { all.add( - session.concurrent().executorService().submit(new Callable() { + session.config().executorService().submit(new Callable() { @Override public NutsPlatformLocation call() throws Exception { NutsPlatformLocation r = null; @@ -220,7 +220,7 @@ public NutsPlatformLocation call() throws Exception { if (r != null) { if (session.isPlainTrace()) { synchronized (session.getWorkspace()) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); session.out().printf("detected java %s %s at %s%n", r.getPackaging(), factory.ofStyled(r.getVersion(), NutsTextStyle.version()), factory.ofStyled(r.getPath(), NutsTextStyle.path()) @@ -240,7 +240,7 @@ public NutsPlatformLocation call() throws Exception { throw new UncheckedIOException(ex); } } - return session.concurrent().executorService().submit(new Callable() { + return session.config().executorService().submit(new Callable() { @Override public NutsPlatformLocation[] call() throws Exception { List locs = new ArrayList<>(); @@ -353,7 +353,7 @@ public NutsId createJdkId(String version, NutsSession session) { if (NutsBlankable.isBlank(version)) { throw new NutsException(session, NutsMessage.formatted("missing version")); } - NutsVersion jv = session.version().parser().parse(version); + NutsVersion jv = NutsVersion.of(version,session); long n1 = jv.getNumber(0, BigInteger.ZERO).longValue(); long n2 = jv.getNumber(1, BigInteger.ZERO).longValue(); long classFileId = 0; @@ -364,7 +364,7 @@ public NutsId createJdkId(String version, NutsSession session) { if (classFileId == 0) { classFileId = 52; } - return session.id().builder().setArtifactId("java") + return NutsIdBuilder.of(session).setArtifactId("java") .setProperty("s", standard) .setProperty("c", String.valueOf(classFileId)) .setVersion(version) @@ -374,8 +374,8 @@ public NutsId createJdkId(String version, NutsSession session) { public String resolveJavaCommandByVersion(String requestedJavaVersion, boolean javaw, NutsSession session) { String bestJavaPath = resolveJdkLocation(requestedJavaVersion, session).getPath(); if (bestJavaPath.contains("/") || bestJavaPath.contains("\\") || bestJavaPath.equals(".") || bestJavaPath.equals("..")) { - Path file = Paths.get(session.locations().getWorkspaceLocation()).resolve(bestJavaPath); - if (Files.isDirectory(file) && Files.isDirectory(file.resolve("bin"))) { + NutsPath file = session.locations().getWorkspaceLocation().resolve(bestJavaPath); + if (file.isDirectory() && file.resolve("bin").isDirectory()) { boolean winOs = session.env().getOsFamily() == NutsOsFamily.WINDOWS; if (winOs) { if (javaw) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsWorkspaceUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsWorkspaceUtils.java index 4313f2fca..b63647b2d 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsWorkspaceUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/util/NutsWorkspaceUtils.java @@ -119,7 +119,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(NutsWorkspaceUtils.class); + LOG = NutsLogger.of(NutsWorkspaceUtils.class,session); } return LOG; } @@ -152,7 +152,7 @@ public NutsId createSdkId(String type, String version) { if ("java".equalsIgnoreCase(type)) { return NutsJavaSdkUtils.of(ws).createJdkId(version, session); } else { - return session.id().builder().setArtifactId(type) + return NutsIdBuilder.of(session).setArtifactId(type) .setVersion(version) .build(); } @@ -160,7 +160,7 @@ public NutsId createSdkId(String type, String version) { public void checkReadOnly() { if (session.config().isReadOnly()) { - throw new NutsReadOnlyException(session, session.locations().getWorkspaceLocation()); + throw new NutsReadOnlyException(session, session.locations().getWorkspaceLocation().toString()); } } @@ -230,7 +230,7 @@ public List _getEnabledRepositories(NutsRepositoryFilter reposit } public List filterRepositoriesDeploy(NutsId id, NutsRepositoryFilter repositoryFilter) { - NutsRepositoryFilter f = session.filters().repository().installedRepo().neg().and(repositoryFilter); + NutsRepositoryFilter f = NutsRepositoryFilters.of(session).installedRepo().neg().and(repositoryFilter); return filterRepositories(NutsRepositorySupportedAction.DEPLOY, id, f, NutsFetchMode.LOCAL); } @@ -329,7 +329,7 @@ public NutsIdFormat getIdFormat() { String k = DefaultSearchFormatPlain.class.getName() + "#NutsIdFormat"; NutsIdFormat f = (NutsIdFormat) session.env().getProperty(k).getObject(); if (f == null) { - f = session.id().formatter(); + f = NutsIdFormat.of(session); session.env().setProperty(k, f); } return f; @@ -339,7 +339,7 @@ public NutsDescriptorFormat getDescriptorFormat() { String k = DefaultSearchFormatPlain.class.getName() + "#NutsDescriptorFormat"; NutsDescriptorFormat f = (NutsDescriptorFormat) session.env().getProperty(k).getObject(); if (f == null) { - f = session.descriptor().formatter(); + f = NutsDescriptorFormat.of(session); session.env().setProperty(k, f); } return f; @@ -636,7 +636,7 @@ public void installAllJVM() { someAdded++; } } - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (session.isPlainTrace()) { if (someAdded == 0) { session.out().print("```error no new``` java installation locations found...\n"); @@ -677,7 +677,7 @@ public void installCurrentJVM() { someAdded++; } } - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (session.isPlainTrace()) { if (someAdded == 0) { session.out().print("```error no new``` java installation locations found...\n"); @@ -727,7 +727,7 @@ public void installLaunchers(boolean gui) { } public void installCompanions() { - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); Set companionIds = session.extensions().getCompanionIds(); if (companionIds.isEmpty()) { return; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/NutsWorkspaceCommandBase.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/NutsWorkspaceCommandBase.java index 9c7a68b37..03b2c97cf 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/NutsWorkspaceCommandBase.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/NutsWorkspaceCommandBase.java @@ -34,7 +34,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().of(getClass()); + LOG = NutsLogger.of(getClass(),session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/deploy/AbstractNutsDeployCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/deploy/AbstractNutsDeployCommand.java index 05518f24f..6a6f5d0c3 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/deploy/AbstractNutsDeployCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/deploy/AbstractNutsDeployCommand.java @@ -64,7 +64,7 @@ public NutsDeployCommand setContent(InputStream stream) { @Override public NutsDeployCommand setContent(String path) { - content = path==null?null:NutsStreamOrPath.of(getSession().io().path(path)); + content = path==null?null:NutsStreamOrPath.of(path,getSession()); return this; } @@ -82,14 +82,14 @@ public NutsDeployCommand setContent(byte[] content) { @Override public NutsDeployCommand setContent(File file) { - content = file==null?null:NutsStreamOrPath.of(getSession().io().path(file)); + content = file==null?null:NutsStreamOrPath.of(file,getSession()); invalidateResult(); return this; } @Override public NutsDeployCommand setContent(Path file) { - content = file==null?null:NutsStreamOrPath.of(getSession().io().path(file)); + content = file==null?null:NutsStreamOrPath.of(file,getSession()); invalidateResult(); return this; } @@ -151,7 +151,7 @@ public NutsStreamOrPath getContent() { @Override public NutsDeployCommand setContent(URL url) { - content = url==null?null:NutsStreamOrPath.of(getSession().io().path(url)); + content = url==null?null:NutsStreamOrPath.of(url,getSession()); invalidateResult(); return this; } @@ -232,7 +232,7 @@ protected void addResult(NutsId nid,String repository,NutsString source) { // if (getSession().isPlainTrace()) { // getSession().getTerminal().out().resetLine().printf("Nuts %s deployed successfully to %s%n", // nid, -// session.text().ofStyled(toRepository == null ? "" : toRepository, NutsTextStyle.primary3()) +// NutsTexts.of(session).ofStyled(toRepository == null ? "" : toRepository, NutsTextStyle.primary3()) // ); // } } @@ -244,7 +244,7 @@ public NutsDeployCommand addIds(String... values) { if (values != null) { for (String s : values) { if (!NutsBlankable.isBlank(s)) { - ids.add(session.id().parser().setLenient(false).parse(s)); + ids.add(NutsId.of(s,session)); } } } @@ -288,8 +288,7 @@ public NutsDeployCommand removeId(NutsId id) { @Override public NutsDeployCommand removeId(String id) { checkSession(); - NutsWorkspace ws = getSession().getWorkspace(); - ids.remove(session.id().parser().parse(id)); + ids.remove(NutsId.of(id,session)); return this; } @@ -297,7 +296,7 @@ public NutsDeployCommand removeId(String id) { public NutsDeployCommand addId(String id) { checkSession(); if (!NutsBlankable.isBlank(id)) { - ids.add(session.id().parser().setLenient(false).parse(id)); + ids.add(NutsId.of(id,session)); } return this; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/deploy/DefaultNutsDeployCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/deploy/DefaultNutsDeployCommand.java index 49ac4ad42..4d3d98e90 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/deploy/DefaultNutsDeployCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/deploy/DefaultNutsDeployCommand.java @@ -43,7 +43,7 @@ private static CharacterizedDeployFile characterizeForDeploy(NutsStreamOrPath co } if (c.descriptor == null && c.contentStreamOrPath.isPath() && c.contentStreamOrPath.getPath().isURL()) { try { - c.descriptor = session.descriptor().parser().setSession(session).parse( + c.descriptor = NutsDescriptorParser.of(session).parse( c.contentStreamOrPath.getPath().resolve(NutsConstants.Files.DESCRIPTOR_FILE_NAME) ); } catch (Exception ex) { @@ -54,14 +54,14 @@ private static CharacterizedDeployFile characterizeForDeploy(NutsStreamOrPath co if (c.descriptor == null) { Path ext = c.baseFile.resolve(NutsConstants.Files.DESCRIPTOR_FILE_NAME); if (Files.exists(ext)) { - c.descriptor = session.descriptor().parser().setSession(session).parse(ext); + c.descriptor = NutsDescriptorParser.of(session).parse(ext); } else { c.descriptor = CoreIOUtils.resolveNutsDescriptorFromFileContent(c.baseFile, parseOptions, session); } } if (c.descriptor != null) { if ("zip".equals(c.descriptor.getPackaging())) { - Path zipFilePath = Paths.get(session.io().path(c.baseFile.toString() + ".zip").builder().withAppBaseDir().build().toString()); + Path zipFilePath = Paths.get(NutsPath.of(c.baseFile.toString() + ".zip",session).builder().withAppBaseDir().build().toString()); ZipUtils.zip(session, c.baseFile.toString(), new ZipOptions(), zipFilePath.toString()); c.contentStreamOrPath = NutsStreamOrPath.of(NutsPath.of(zipFilePath,session)); c.addTemp(zipFilePath); @@ -71,9 +71,9 @@ private static CharacterizedDeployFile characterizeForDeploy(NutsStreamOrPath co } } else if (Files.isRegularFile(c.baseFile)) { if (c.descriptor == null) { - File ext = new File(session.io().path(c.baseFile.toString() + "." + NutsConstants.Files.DESCRIPTOR_FILE_NAME).builder().withAppBaseDir().build().toString()); + File ext = new File(NutsPath.of(c.baseFile.toString() + "." + NutsConstants.Files.DESCRIPTOR_FILE_NAME,session).builder().withAppBaseDir().build().toString()); if (ext.exists()) { - c.descriptor = session.descriptor().parser().setSession(session).parse(ext); + c.descriptor = NutsDescriptorParser.of(session).parse(ext); } else { c.descriptor = CoreIOUtils.resolveNutsDescriptorFromFileContent(c.baseFile, parseOptions, session); } @@ -116,7 +116,7 @@ public NutsDeployCommand run() { getSession().getTerminal().out().resetLine().printf("%s deployed successfully as %s to %s%n", nid.source, nid.id, - session.text().ofStyled(nid.repository, NutsTextStyle.primary3()) + NutsTexts.of(session).ofStyled(nid.repository, NutsTextStyle.primary3()) ); } break; @@ -135,33 +135,32 @@ private NutsDeployCommand runDeployFile() { private NutsDeployCommand runDeployFile(NutsStreamOrPath content, Object descriptor0, String descSHA1) { checkSession(); - NutsSession ws = getSession(); - NutsWorkspaceExt dws = NutsWorkspaceExt.of(ws.getWorkspace()); - NutsWorkspaceUtils wu = NutsWorkspaceUtils.of(session); + NutsSession session = getSession(); + NutsWorkspaceExt dws = NutsWorkspaceExt.of(session.getWorkspace()); + NutsWorkspaceUtils wu = NutsWorkspaceUtils.of(this.session); wu.checkReadOnly(); Path tempFile = null; NutsStreamOrPath contentSource; - contentSource = content.toMultiRead(session); + contentSource = content.toMultiRead(this.session); NutsDescriptor descriptor = buildDescriptor(descriptor0, descSHA1); CharacterizedDeployFile characterizedFile = null; Path contentFile2 = null; try { if (descriptor == null) { - NutsFetchCommand p = session.fetch() - .setSession(ws.copy().setTransitive(true)); - characterizedFile = characterizeForDeploy(contentSource, p, getParseOptions(), ws); + NutsFetchCommand p = this.session.fetch() + .setSession(session.copy().setTransitive(true)); + characterizedFile = characterizeForDeploy(contentSource, p, getParseOptions(), session); if (characterizedFile.descriptor == null) { throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("missing descriptor")); } descriptor = characterizedFile.descriptor; } - String name = session.locations().getDefaultIdFilename(descriptor.getId().builder().setFaceDescriptor().build()); - tempFile = session.io().tmp() - .setSession(session) + String name = this.session.locations().getDefaultIdFilename(descriptor.getId().builder().setFaceDescriptor().build()); + tempFile = NutsTmp.of(this.session) .createTempFile(name).toFile(); - session.io().copy().setSession(ws).from(contentSource.getInputStream()).to(tempFile).setSafe(true).run(); + NutsCp.of(this.session).setSession(session).from(contentSource.getInputStream()).to(tempFile).setSafe(true).run(); contentFile2 = tempFile; Path contentFile0 = contentFile2; @@ -175,24 +174,24 @@ private NutsDeployCommand runDeployFile(NutsStreamOrPath content, Object descrip Path descFile = contentFile.resolve(NutsConstants.Files.DESCRIPTOR_FILE_NAME); NutsDescriptor descriptor2; if (Files.exists(descFile)) { - descriptor2 = ws.descriptor().parser().setSession(session).parse(descFile); + descriptor2 = NutsDescriptorParser.of(session).parse(descFile); } else { descriptor2 = CoreIOUtils.resolveNutsDescriptorFromFileContent( contentFile, - getParseOptions(), ws); + getParseOptions(), session); } if (descriptor == null) { descriptor = descriptor2; } else { if (descriptor2 != null && !descriptor2.equals(descriptor)) { - ws.descriptor().formatter(descriptor).print(descFile); + descriptor.formatter().setSession(session).print(descFile); } } if (descriptor != null) { if ("zip".equals(descriptor.getPackaging())) { - Path zipFilePath = Paths.get(ws.io().path(contentFile.toString() + ".zip").builder().withAppBaseDir().build().toString()); + Path zipFilePath = Paths.get(NutsPath.of(contentFile.toString() + ".zip", this.session).builder().withAppBaseDir().build().toString()); try { - ZipUtils.zip(ws, contentFile.toString(), new ZipOptions(), zipFilePath.toString()); + ZipUtils.zip(session, contentFile.toString(), new ZipOptions(), zipFilePath.toString()); } catch (IOException ex) { throw new UncheckedIOException(ex); } @@ -205,7 +204,7 @@ private NutsDeployCommand runDeployFile(NutsStreamOrPath content, Object descrip } else { if (descriptor == null) { descriptor = CoreIOUtils.resolveNutsDescriptorFromFileContent( - contentFile, getParseOptions(), ws); + contentFile, getParseOptions(), session); } } if (descriptor == null) { @@ -217,10 +216,10 @@ private NutsDeployCommand runDeployFile(NutsStreamOrPath content, Object descrip throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("invalid version %s", descriptor.getId().getVersion())); } - NutsId effId = dws.resolveEffectiveId(descriptor, ws); - CorePlatformUtils.checkAcceptCondition(descriptor.getCondition(),false, ws); + NutsId effId = dws.resolveEffectiveId(descriptor, session); + CorePlatformUtils.checkAcceptCondition(descriptor.getCondition(),false, session); if (NutsBlankable.isBlank(repository)) { - effId = session.config().createContentFaceId(effId.builder().setProperties("").build(), descriptor); + effId = this.session.config().createContentFaceId(effId.builder().setProperties("").build(), descriptor); for (NutsRepository repo : wu.filterRepositoriesDeploy(effId, null) .stream() @@ -230,11 +229,11 @@ private NutsDeployCommand runDeployFile(NutsStreamOrPath content, Object descrip int deployOrder = repo.config().getDeployWeight(); NutsRepositorySPI repoSPI = wu.repoSPI(repo); repoSPI.deploy() - .setSession(ws) + .setSession(session) //.setFetchMode(NutsFetchMode.LOCAL) .setId(effId).setContent(contentFile).setDescriptor(descriptor) .run(); - addResult(effId,repo.getName(),session.text().toText(content.getValue())); + addResult(effId,repo.getName(), NutsTexts.of(session).toText(content.getValue())); return this; } } else { @@ -245,15 +244,15 @@ private NutsDeployCommand runDeployFile(NutsStreamOrPath content, Object descrip if (!repo.config().isEnabled()) { throw new NutsRepositoryDisabledException(getSession(), repository); } - effId = session.config().createContentFaceId(effId.builder().setProperties("").build(), descriptor); + effId = this.session.config().createContentFaceId(effId.builder().setProperties("").build(), descriptor); NutsRepositorySPI repoSPI = wu.repoSPI(repo); repoSPI.deploy() - .setSession(ws) + .setSession(session) .setId(effId) .setContent(contentFile) .setDescriptor(descriptor) .run(); - addResult(effId,repo.getName(),session.text().toText(content.getValue())); + addResult(effId,repo.getName(), NutsTexts.of(this.session).toText(content.getValue())); return this; } throw new NutsRepositoryNotFoundException(getSession(), repository); @@ -282,25 +281,25 @@ protected NutsDescriptor buildDescriptor(Object descriptor, String descSHA1) { return null; } checkSession(); - NutsSession ws = getSession(); + NutsSession session = getSession(); NutsDescriptor mdescriptor = null; if (descriptor instanceof NutsDescriptor) { mdescriptor = (NutsDescriptor) descriptor; - if (descSHA1 != null && !ws.io().hash().sha1().setSource(mdescriptor).computeString().equalsIgnoreCase(descSHA1)) { + if (descSHA1 != null && !NutsHash.of(session).sha1().setSource(mdescriptor).computeString().equalsIgnoreCase(descSHA1)) { throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("invalid content Hash")); } return mdescriptor; } else { - NutsStreamOrPath nutsStreamOrPath = NutsStreamOrPath.ofAnyInputOrNull(descriptor, session); + NutsStreamOrPath nutsStreamOrPath = NutsStreamOrPath.ofAnyInputOrNull(descriptor, this.session); if(nutsStreamOrPath!=null) { NutsStreamOrPath d = nutsStreamOrPath.isInputStream()? - NutsStreamOrPath.of((InputStream) descriptor).toDisposable(session) + NutsStreamOrPath.of((InputStream) descriptor).toDisposable(this.session) :nutsStreamOrPath ; try { if (descSHA1 != null) { try (InputStream is = d.getInputStream()) { - if (!ws.io().hash().sha1().setSource(is).computeString().equalsIgnoreCase(descSHA1)) { + if (!NutsHash.of(session).sha1().setSource(is).computeString().equalsIgnoreCase(descSHA1)) { throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("invalid content Hash")); } } catch (IOException ex) { @@ -308,7 +307,7 @@ protected NutsDescriptor buildDescriptor(Object descriptor, String descSHA1) { } } try (InputStream is = d.getInputStream()) { - return ws.descriptor().parser().setSession(session).parse(is); + return NutsDescriptorParser.of(session).parse(is); } catch (IOException ex) { throw new UncheckedIOException(ex); } @@ -328,7 +327,7 @@ public NutsDeployCommand addIds(String... values) { if (values != null) { for (String s : values) { if (!NutsBlankable.isBlank(s)) { - ids.add(session.id().parser().parse(s)); + ids.add(NutsId.of(s,session)); } } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/AbstractNutsExecCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/AbstractNutsExecCommand.java index 5b7f09385..991fd64b8 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/AbstractNutsExecCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/AbstractNutsExecCommand.java @@ -3,7 +3,6 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.core.util.CoreStringUtils; import net.thevpc.nuts.runtime.bundles.io.ProcessBuilder2; -import net.thevpc.nuts.runtime.core.format.DefaultNutsExecCommandFormat; import net.thevpc.nuts.runtime.standalone.io.NutsByteArrayPrintStream; import net.thevpc.nuts.runtime.standalone.wscommands.NutsWorkspaceCommandBase; @@ -34,8 +33,8 @@ public abstract class AbstractNutsExecCommand extends NutsWorkspaceCommandBase executorOptionsList = new ArrayList<>(); for (String option : executorOptions) { - NutsArgument a = traceSession.commandLine().createArgument(option); + NutsArgument a = NutsArgument.of(option,traceSession); if (a.getKey().getString().equals("--nuts-auto-install")) { if (a.isKeyValue()) { autoInstall = a.isNegated() != a.getValue().getBoolean(); @@ -132,7 +132,7 @@ public void dryExecute() { @Override public String toString() { - return "NUTS " + getId().toString() + " " + execSession.commandLine().create(appArgs).toString(); + return "NUTS " + getId().toString() + " " + NutsCommandLine.of(appArgs,execSession).toString(); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsArtifactPathExecutable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsArtifactPathExecutable.java index d96b498c5..90c74c3b8 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsArtifactPathExecutable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsArtifactPathExecutable.java @@ -27,6 +27,7 @@ import net.thevpc.nuts.runtime.bundles.io.URLBuilder; import net.thevpc.nuts.runtime.bundles.io.ZipOptions; import net.thevpc.nuts.runtime.bundles.io.ZipUtils; +import net.thevpc.nuts.runtime.standalone.util.CoreDigestHelper; import net.thevpc.nuts.spi.NutsDependencySolver; /** @@ -46,9 +47,9 @@ public class DefaultNutsArtifactPathExecutable extends AbstractNutsExecutableCom public DefaultNutsArtifactPathExecutable(String cmdName, String[] args, String[] executorOptions, NutsExecutionType executionType, NutsRunAs runAs,NutsSession traceSession, NutsSession execSession, DefaultNutsExecCommand execCommand, boolean inheritSystemIO) { super(cmdName, - execSession.commandLine().create(args).toString(), + NutsCommandLine.of(args,execSession).toString(), NutsExecutableType.ARTIFACT); - LOG = execSession.log().of(DefaultNutsArtifactPathExecutable.class); + LOG = NutsLogger.of(DefaultNutsArtifactPathExecutable.class,traceSession); this.runAs = runAs; this.cmdName = cmdName; this.args = args; @@ -58,7 +59,7 @@ public DefaultNutsArtifactPathExecutable(String cmdName, String[] args, String[] this.execCommand = execCommand; List executorOptionsList = new ArrayList<>(); for (String option : executorOptions) { - NutsArgument a = traceSession.commandLine().createArgument(option); + NutsArgument a = NutsArgument.of(option,traceSession); if (a.getKey().getString().equals("--nuts-auto-install")) { if (a.isKeyValue()) { // autoInstall= a.isNegated() != a.getBooleanValue(); @@ -74,7 +75,7 @@ public DefaultNutsArtifactPathExecutable(String cmdName, String[] args, String[] @Override public NutsId getId() { - try (final CharacterizedExecFile c = characterizeForExec(NutsStreamOrPath.of(traceSession.io().path(cmdName)), traceSession, executorOptions)) { + try (final CharacterizedExecFile c = characterizeForExec(NutsStreamOrPath.of(cmdName,traceSession), traceSession, executorOptions)) { return c.descriptor == null ? null : c.descriptor.getId(); } } @@ -90,11 +91,11 @@ public void dryExecute() { } public void executeHelper(boolean dry) { - try (final CharacterizedExecFile c = characterizeForExec(NutsStreamOrPath.of(traceSession.io().path(cmdName)), traceSession, executorOptions)) { + try (final CharacterizedExecFile c = characterizeForExec(NutsStreamOrPath.of(cmdName,traceSession), traceSession, executorOptions)) { if (c.descriptor == null) { throw new NutsNotFoundException(execSession, null, NutsMessage.cstyle("unable to resolve a valid descriptor for %s",cmdName), null); } - String tempFolder = traceSession.io().tmp() + String tempFolder = NutsTmp.of(traceSession) .createTempFolder("exec-path-").toString(); NutsId _id = c.descriptor.getId(); NutsIdType idType = NutsWorkspaceExt.of(traceSession).resolveNutsIdType(_id, traceSession); @@ -104,13 +105,13 @@ public void executeHelper(boolean dry) { _id.getLongId(), c.descriptor, new NutsDefaultContent( - execSession.io().path(c.contentFile) + NutsPath.of(c.contentFile,execSession) , false, c.temps.size() > 0), DefaultNutsInstallInfo.notInstalled(_id), idType, null, traceSession ); - NutsDependencySolver resolver = traceSession.dependency().createSolver(); - NutsDependencyFilterManager ff = traceSession.dependency().filter(); + NutsDependencySolver resolver = NutsDependencySolver.of(traceSession); + NutsDependencyFilters ff = NutsDependencyFilters.of(traceSession); resolver .setFilter(ff.byScope(NutsDependencyScopePattern.RUN) @@ -149,15 +150,14 @@ public static CharacterizedExecFile characterizeForExec(NutsStreamOrPath content if (Files.isDirectory(fileSource)) { Path ext = fileSource.resolve(NutsConstants.Files.DESCRIPTOR_FILE_NAME); if (Files.exists(ext)) { - c.descriptor = session.descriptor().parser().setSession(session).parse(ext); + c.descriptor = NutsDescriptorParser.of(session).parse(ext); } else { c.descriptor = CoreIOUtils.resolveNutsDescriptorFromFileContent(c.contentFile, execOptions, session); } if (c.descriptor != null) { if ("zip".equals(c.descriptor.getPackaging())) { - Path zipFilePath = Paths.get(session.io().path(fileSource.toString() + ".zip") - .builder().withAppBaseDir().build().toString() - ); + Path zipFilePath = NutsPath.of(fileSource+ ".zip",session) + .builder().withAppBaseDir().build().toFile(); ZipUtils.zip(session, fileSource.toString(), new ZipOptions(), zipFilePath.toString()); c.contentFile = zipFilePath; c.addTemp(zipFilePath); @@ -168,7 +168,7 @@ public static CharacterizedExecFile characterizeForExec(NutsStreamOrPath content } else if (Files.isRegularFile(fileSource)) { if (c.contentFile.getFileName().toString().endsWith(NutsConstants.Files.DESCRIPTOR_FILE_NAME)) { try (InputStream in = Files.newInputStream(c.contentFile)) { - c.descriptor = session.descriptor().parser().setSession(session).parse(in); + c.descriptor = NutsDescriptorParser.of(session).parse(in); } c.contentFile = null; if (c.streamOrPath.isPath() && c.streamOrPath.getPath().isURL()) { @@ -176,7 +176,7 @@ public static CharacterizedExecFile characterizeForExec(NutsStreamOrPath content try { c.contentFile = CoreIOUtils.toPathInputSource( NutsStreamOrPath.of( - session.io().path(ub.resolveSibling(session.locations().getDefaultIdFilename(c.descriptor.getId())).toURL()) + ub.resolveSibling(session.locations().getDefaultIdFilename(c.descriptor.getId())).toURL(),session ), c.temps, session); } catch (Exception ex) { @@ -191,7 +191,7 @@ public static CharacterizedExecFile characterizeForExec(NutsStreamOrPath content if (CoreIOUtils.isPathHttp(location)) { try { c.contentFile = CoreIOUtils.toPathInputSource( - NutsStreamOrPath.of(session.io().path(new URL(location))), + NutsStreamOrPath.of(new URL(location),session), c.temps, session); } catch (Exception ex) { @@ -200,7 +200,7 @@ public static CharacterizedExecFile characterizeForExec(NutsStreamOrPath content URLBuilder ub = new URLBuilder(c.streamOrPath.getPath().toURL().toString()); try { c.contentFile = CoreIOUtils.toPathInputSource( - NutsStreamOrPath.of(session.io().path(ub.resolveSibling(session.locations().getDefaultIdFilename(c.descriptor.getId())).toURL())), + NutsStreamOrPath.of(ub.resolveSibling(session.locations().getDefaultIdFilename(c.descriptor.getId())).toURL(),session), c.temps, session); } catch (Exception ex) { @@ -218,8 +218,11 @@ public static CharacterizedExecFile characterizeForExec(NutsStreamOrPath content } else { c.descriptor = CoreIOUtils.resolveNutsDescriptorFromFileContent(c.contentFile, execOptions, session); if (c.descriptor == null) { - c.descriptor = session.descriptor().descriptorBuilder() - .setId("temp") + CoreDigestHelper d = new CoreDigestHelper(); + d.append(c.contentFile); + String artifactId = d.getDigest(); + c.descriptor = NutsDescriptorBuilder.of(session) + .setId("temp:"+artifactId+"#1.0") .setPackaging(CoreIOUtils.getFileExtension(contentFile.getName())) .build(); } @@ -235,7 +238,7 @@ public static CharacterizedExecFile characterizeForExec(NutsStreamOrPath content @Override public String toString() { - return "NUTS " + cmdName + " " + execSession.commandLine().create(args).toString(); + return "NUTS " + cmdName + " " + NutsCommandLine.of(args,execSession).toString(); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsExecCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsExecCommand.java index 14d48a655..077f1b9b5 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsExecCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsExecCommand.java @@ -53,7 +53,7 @@ public NutsExecutableInformation which() { checkSession(); NutsSession traceSession = getSession(); NutsSession execSession = traceSession.copy(); - NutsSessionTerminal terminal = execSession.term().createTerminal(traceSession.getTerminal()); + NutsSessionTerminal terminal = NutsSessionTerminal.of(traceSession.getTerminal(),execSession); if (this.in != null) { terminal.setIn(this.in); } @@ -194,12 +194,12 @@ private NutsExecutableInformationExt execEmbeddedOrExternal(String[] cmd, String String goodKw = null; boolean forceInstalled = false; if (cmdName.endsWith("!")) { - goodId = session.id().parser().setLenient(true).parse(cmdName.substring(0, cmdName.length() - 1)); + goodId = NutsIdParser.of(session).setLenient(true).parse(cmdName.substring(0, cmdName.length() - 1)); if (goodId != null) { forceInstalled = true; } } else { - goodId = session.id().parser().setLenient(true).parse(cmdName); + goodId = NutsIdParser.of(session).setLenient(true).parse(cmdName); } if (cmdName.contains("/") || cmdName.contains("\\")) { @@ -331,7 +331,7 @@ protected NutsId findExecId(NutsId nid, NutsSession traceSession, boolean forceI } NutsSession noProgressSession = traceSession.copy().setProgressOptions("none"); List ff = traceSession.search().addId(nid).setSession(noProgressSession).setOptional(false).setLatest(true).setFailFast(false) - .setInstallStatus(session.filters().installStatus().byDeployed(true)) + .setInstallStatus(NutsInstallStatusFilters.of(session).byDeployed(true)) .getResultDefinitions().stream() .sorted(Comparator.comparing(x -> !x.getInstallInformation().isDefaultVersion())) // default first .map(NutsDefinition::getId).collect(Collectors.toList()); @@ -353,7 +353,7 @@ protected NutsId findExecId(NutsId nid, NutsSession traceSession, boolean forceI if (traceSession.isPlainTrace()) { traceSession.out().resetLine().printf("%s is %s, will search for it online. Type ```error CTRL^C``` to stop...\n", nid, - session.text().ofStyled("not installed", NutsTextStyle.error()) + NutsTexts.of(session).ofStyled("not installed", NutsTextStyle.error()) ); traceSession.out().flush(); } @@ -489,10 +489,7 @@ public void ws_execId(NutsDefinition def, String commandName, String[] appArgs, } } if (execComponent == null) { - execComponent = getSession().extensions().createSupported(NutsExecutorComponent.class, def); - if (execComponent == null) { - throw new NutsNotFoundException(getSession(), def.getId()); - } + execComponent = getSession().extensions().createSupported(NutsExecutorComponent.class, true, def); } if (executorCall != null) { executorArgs.addAll(Arrays.asList(executorCall.getArguments())); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsOpenExecutable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsOpenExecutable.java index d95f62bb9..4de98085f 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsOpenExecutable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsOpenExecutable.java @@ -30,14 +30,14 @@ public DefaultNutsOpenExecutable(String[] cmd, String[] executorOptions, NutsSession traceSession, NutsSession execSession, NutsExecCommand execCommand ) { super(cmd[0], - execSession.commandLine().create(cmd).toString(), + NutsCommandLine.of(cmd,traceSession).toString(), NutsExecutableType.SYSTEM); this.cmd = cmd; this.execCommand = execCommand; this.executorOptions = executorOptions == null ? new String[0] : executorOptions; this.traceSession = traceSession; this.execSession = execSession; - NutsCommandLine cmdLine = execSession.commandLine().create(this.executorOptions); + NutsCommandLine cmdLine = NutsCommandLine.of(this.executorOptions,traceSession); while (cmdLine.hasNext()) { NutsArgument a = cmdLine.peek(); switch (a.getKey().getString()) { @@ -125,9 +125,9 @@ public String getHelpText() { @Override public String toString() { if (effectiveOpenExecutable == null) { - return "FAIL TO OPEN " + execSession.commandLine().create(cmd).toString(); + return "FAIL TO OPEN " + NutsCommandLine.of(cmd,traceSession).toString(); } - return "OPEN with " + effectiveOpenExecutable[0] + " : " + execSession.commandLine().create(cmd).toString(); + return "OPEN with " + effectiveOpenExecutable[0] + " : " + NutsCommandLine.of(cmd,traceSession).toString(); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsSystemExecutable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsSystemExecutable.java index 9d7643345..31aecc6e6 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsSystemExecutable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultNutsSystemExecutable.java @@ -27,7 +27,7 @@ public class DefaultNutsSystemExecutable extends AbstractNutsExecutableCommand { public DefaultNutsSystemExecutable(String[] cmd, String[] executorOptions, NutsSession traceSession, NutsSession execSession, NutsExecCommand execCommand) { super(cmd[0], - execSession.commandLine().create(cmd).toString(), + NutsCommandLine.of(cmd,traceSession).toString(), NutsExecutableType.SYSTEM); this.inheritSystemIO = execCommand.isInheritSystemIO(); this.cmd = cmd; @@ -35,7 +35,7 @@ public DefaultNutsSystemExecutable(String[] cmd, this.executorOptions = executorOptions == null ? new String[0] : executorOptions; this.traceSession = traceSession; this.execSession = execSession; - NutsCommandLine cmdLine = execSession.commandLine().create(this.executorOptions); + NutsCommandLine cmdLine = NutsCommandLine.of(this.executorOptions,traceSession); while (cmdLine.hasNext()) { NutsArgument a = cmdLine.peek(); switch (a.getKey().getString()) { @@ -102,7 +102,7 @@ public String getHelpText() { @Override public String toString() { - return execCommand.getRunAs() + "_CMD " + execSession.commandLine().create(cmd).toString(); + return execCommand.getRunAs() + "_CMD " + NutsCommandLine.of(cmd,traceSession).toString(); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultUnknownExecutable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultUnknownExecutable.java index 7b6dc5c11..3cf112afb 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultUnknownExecutable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/exec/DefaultUnknownExecutable.java @@ -16,7 +16,7 @@ public class DefaultUnknownExecutable extends AbstractNutsExecutableCommand { NutsSession execSession; public DefaultUnknownExecutable(String[] cmd, NutsSession execSession) { - super(cmd[0], execSession.commandLine().create(cmd).toString(), NutsExecutableType.UNKNOWN); + super(cmd[0], NutsCommandLine.of(cmd,execSession).toString(), NutsExecutableType.UNKNOWN); this.execSession = execSession; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/fetch/AbstractNutsFetchCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/fetch/AbstractNutsFetchCommand.java index fc7387414..d4fae76f4 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/fetch/AbstractNutsFetchCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/fetch/AbstractNutsFetchCommand.java @@ -16,8 +16,7 @@ public AbstractNutsFetchCommand(NutsWorkspace ws) { @Override public NutsFetchCommand setId(String id) { checkSession(); - NutsWorkspace ws = getSession().getWorkspace(); - this.id = session.id().parser().setLenient(false).parse(id); + this.id = NutsId.of(id,session); return this; } @@ -101,7 +100,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { cmdLine.skip(); if (enabled) { setRepositoryFilter( - getSession().filters().repository().installedRepo().neg() + NutsRepositoryFilters.of(getSession()).installedRepo().neg() .and(this.getRepositoryFilter()) ); } @@ -112,7 +111,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { cmdLine.skip(); if (enabled) { setRepositoryFilter( - getSession().filters().repository().installedRepo() + NutsRepositoryFilters.of(session).installedRepo() .and(this.getRepositoryFilter()) ); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/fetch/DefaultNutsFetchCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/fetch/DefaultNutsFetchCommand.java index 92a795816..5e4ab436a 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/fetch/DefaultNutsFetchCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/fetch/DefaultNutsFetchCommand.java @@ -14,6 +14,7 @@ import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; import net.thevpc.nuts.runtime.standalone.wscommands.NutsRepositoryAndFetchMode; import net.thevpc.nuts.runtime.standalone.wscommands.NutsRepositoryAndFetchModeTracker; +import net.thevpc.nuts.spi.NutsDependencySolver; import net.thevpc.nuts.spi.NutsRepositorySPI; import java.nio.file.Files; @@ -66,7 +67,7 @@ public String getResultContentHash() { checkSession(); NutsSession ws = getSession(); Path f = getResultDefinition().getPath(); - return ws.io().hash().setSource(f).computeString(); + return NutsHash.of(ws).setSource(f).computeString(); } catch (NutsNotFoundException ex) { if (!isFailFast()) { return null; @@ -79,7 +80,7 @@ public String getResultContentHash() { public String getResultDescriptorHash() { try { checkSession(); - return getSession().io().hash().setSource(getResultDescriptor()).computeString(); + return NutsHash.of(getSession()).setSource(getResultDescriptor()).computeString(); } catch (NutsNotFoundException ex) { if (!isFailFast()) { return null; @@ -177,7 +178,7 @@ public NutsDefinition fetchDefinitionNoCache(NutsId id, NutsFetchCommand options NutsFetchStrategy nutsFetchModes = NutsWorkspaceHelper.validate(_ws.getFetchStrategy()); NutsRepositoryFilter repositoryFilter = this.getRepositoryFilter(); if(!NutsBlankable.isBlank(id.getRepository())){ - NutsRepositoryFilter repositoryFilter2=_ws.filters().repository().byName(id.getRepository()); + NutsRepositoryFilter repositoryFilter2=NutsRepositoryFilters.of(_ws).byName(id.getRepository()); repositoryFilter=repositoryFilter2.and(repositoryFilter); } NutsRepositoryAndFetchModeTracker descTracker = new NutsRepositoryAndFetchModeTracker( @@ -226,7 +227,7 @@ public NutsDefinition fetchDefinitionNoCache(NutsId id, NutsFetchCommand options if (foundDefinition != null) { if (isDependencies()) { foundDefinition.setDependencies( - getSession().dependency().createSolver() + NutsDependencySolver.of(getSession()) .setFilter(buildActualDependencyFilter()) .add(id.toDependency(), foundDefinition) .solve() @@ -334,7 +335,7 @@ public NutsDefinition fetchDefinitionNoCache(NutsId id, NutsFetchCommand options private NutsDependencyFilter buildActualDependencyFilter() { checkSession(); - NutsDependencyFilterManager ff = getSession().dependency().filter(); + NutsDependencyFilters ff = NutsDependencyFilters.of(getSession()); return ff.byScope(getScope()) .and(ff.byOptional(getOptional()) ).and(getDependencyFilter()); @@ -424,10 +425,11 @@ protected NutsDescriptor resolveExecProperties(NutsDescriptor nutsDescriptor, Pa ) ); Map map = null; + NutsElements elem = NutsElements.of(session); try { if (Files.isRegularFile(cachePath)) { - map = session.elem().setSession(this.session) - .setContentType(NutsContentType.JSON).parse(cachePath, Map.class); + map = elem.setSession(this.session) + .json().parse(cachePath, Map.class); } } catch (Exception ex) { // @@ -437,7 +439,7 @@ protected NutsDescriptor resolveExecProperties(NutsDescriptor nutsDescriptor, Pa nutsApp = "true".equals(map.get("nutsApplication")); } else { try { - NutsExecutionEntry[] t = session.apps().execEntries().setSession(getSession()).parse(jar); + NutsExecutionEntry[] t = NutsExecutionEntries.of(session).setSession(getSession()).parse(jar); if (t.length > 0) { executable = true; if (t[0].isApp()) { @@ -448,7 +450,7 @@ protected NutsDescriptor resolveExecProperties(NutsDescriptor nutsDescriptor, Pa map = new LinkedHashMap<>(); map.put("executable", String.valueOf(executable)); map.put("nutsApplication", String.valueOf(nutsApp)); - session.elem().setContentType(NutsContentType.JSON).setSession(getSession()).setValue(map) + elem.json().setSession(getSession()).setValue(map) .setNtf(false) .print(cachePath); } catch (Exception ex) { @@ -471,23 +473,23 @@ protected NutsDescriptor resolveExecProperties(NutsDescriptor nutsDescriptor, Pa protected DefaultNutsDefinition fetchDescriptorAsDefinition(NutsId id, NutsSession session, NutsFetchStrategy nutsFetchModes, NutsFetchMode mode, NutsRepository repo) { checkSession(); - NutsSession ws = getSession(); NutsWorkspaceUtils.checkSession(this.ws, session); - NutsWorkspaceExt dws = NutsWorkspaceExt.of(ws); + NutsWorkspaceExt dws = NutsWorkspaceExt.of(session); boolean withCache = !(repo instanceof DefaultNutsInstalledRepository); Path cachePath = null; NutsWorkspaceUtils wu = NutsWorkspaceUtils.of(session); + NutsElements elem = NutsElements.of(getSession()); if (withCache) { - cachePath = Paths.get(ws.locations().getStoreLocation(id, NutsStoreLocation.CACHE, repo.getUuid())) - .resolve(ws.locations().getDefaultIdFilename(id.builder().setFace("def.cache").build())); + cachePath = Paths.get(session.locations().getStoreLocation(id, NutsStoreLocation.CACHE, repo.getUuid())) + .resolve(session.locations().getDefaultIdFilename(id.builder().setFace("def.cache").build())); if (Files.isRegularFile(cachePath)) { try { if (CoreIOUtils.isObsoleteInstant(session, Files.getLastModifiedTime(cachePath).toInstant())) { //this is invalid cache! Files.delete(cachePath); } else { - DefaultNutsDefinition d = ws.elem().setSession(session) - .setContentType(NutsContentType.JSON).parse(cachePath, DefaultNutsDefinition.class); + DefaultNutsDefinition d = elem.setSession(session) + .json().parse(cachePath, DefaultNutsDefinition.class); if (d != null) { NutsRepositoryManager rr = session.copy().setTransitive(true).repos(); NutsRepository repositoryById = rr.findRepositoryById(d.getRepositoryUuid()); @@ -579,7 +581,7 @@ protected DefaultNutsDefinition fetchDescriptorAsDefinition(NutsId id, NutsSessi ); if (withCache) { try { - ws.elem().setContentType(NutsContentType.JSON).setSession(session).setValue(result) + elem.json().setSession(session).setValue(result) .setNtf(false).print(cachePath); } catch (Exception ex) { // diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/help/DefaultNutsHelpInternalExecutable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/help/DefaultNutsHelpInternalExecutable.java index 1a26cb7af..ce1222ded 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/help/DefaultNutsHelpInternalExecutable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/help/DefaultNutsHelpInternalExecutable.java @@ -25,7 +25,7 @@ public class DefaultNutsHelpInternalExecutable extends DefaultInternalNutsExecut private final NutsLogger LOG; public DefaultNutsHelpInternalExecutable(String[] args, NutsSession session) { super("help", args, session); - LOG=session.log().of(DefaultNutsHelpInternalExecutable.class); + LOG=NutsLogger.of(DefaultNutsHelpInternalExecutable.class,session); } @Override @@ -35,7 +35,8 @@ public void execute() { return; } List helpFor = new ArrayList<>(); - NutsCommandLine cmdLine = getSession().commandLine().create(args); + NutsSession session = getSession(); + NutsCommandLine cmdLine = NutsCommandLine.of(args,session); NutsContentType outputFormat = NutsContentType.PLAIN; boolean helpColors=false; while (cmdLine.hasNext()) { @@ -55,7 +56,7 @@ public void execute() { break; } default: { - getSession().configureLast(cmdLine); + session.configureLast(cmdLine); } } } else { @@ -68,19 +69,19 @@ public void execute() { } if(helpColors){ - NutsTextManager txt = getSession().text(); + NutsTexts txt = NutsTexts.of(session); NutsText n = txt.parser().parseResource("/net/thevpc/nuts/runtime/ntf-help.ntf", txt.parser().createLoader(getClass().getClassLoader()) ); - getSession().getTerminal().out().print( + session.getTerminal().out().print( n==null?("no help found for " + name):n.toString() ); } switch (outputFormat) { case PLAIN: { - NutsPrintStream fout = getSession().out(); + NutsPrintStream fout = session.out(); if (!helpColors && helpFor.isEmpty()) { - fout.println(NutsWorkspaceExt.of(getSession().getWorkspace()).getHelpText(getSession())); + fout.println(NutsWorkspaceExt.of(session.getWorkspace()).getHelpText(session)); fout.flush(); } for (String arg : helpFor) { @@ -91,9 +92,9 @@ public void execute() { fout.flush(); } else { try { - w = getSession().exec().addCommand(arg).which(); + w = session.exec().addCommand(arg).which(); } catch (Exception ex) { - LOG.with().session(getSession()).level(Level.FINE).error(ex).log( NutsMessage.jstyle("failed to execute : {0}", arg)); + LOG.with().session(session).level(Level.FINE).error(ex).log( NutsMessage.jstyle("failed to execute : {0}", arg)); //ignore } if (w != null) { @@ -101,14 +102,14 @@ public void execute() { fout.println(w.getHelpText()); fout.flush(); } else { - getSession().getTerminal().err().println(arg + " : Not found"); + session.getTerminal().err().println(arg + " : Not found"); } } } break; } default: { - throw new NutsUnsupportedOperationException(getSession(), NutsMessage.cstyle("unsupported format %s",outputFormat)); + throw new NutsUnsupportedOperationException(session, NutsMessage.cstyle("unsupported format %s",outputFormat)); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/install/AbstractNutsInstallCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/install/AbstractNutsInstallCommand.java index f3af7fc74..2e8aca927 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/install/AbstractNutsInstallCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/install/AbstractNutsInstallCommand.java @@ -76,8 +76,7 @@ public AbstractNutsInstallCommand(NutsWorkspace ws) { @Override public NutsInstallCommand addId(String id) { checkSession(); - NutsWorkspace ws = getSession().getWorkspace(); - return addId(id == null ? null : session.id().parser().parse(id)); + return addId(id == null ? null : NutsId.of(id,session)); } @Override @@ -139,7 +138,7 @@ public NutsInstallCommand removeId(NutsId id) { public NutsInstallCommand removeId(String id) { checkSession(); if (id != null) { - this.ids.remove(session.id().parser().parse(id)); + this.ids.remove(NutsId.of(id,session)); } return this; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/install/DefaultNutsInstallCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/install/DefaultNutsInstallCommand.java index 63ad24677..56c15859b 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/install/DefaultNutsInstallCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/install/DefaultNutsInstallCommand.java @@ -187,7 +187,7 @@ public NutsInstallCommand run() { // Map defsOk = new LinkedHashMap<>(); if (isInstalled()) { for (NutsId resultId : session.search().setSession(session).setInstallStatus( - session.filters().installStatus().byInstalled(true)).getResultIds()) { + NutsInstallStatusFilters.of(session).byInstalled(true)).getResultIds()) { list.addForInstall(resultId, getInstalled(), true); } // This bloc is to handle packages that were installed but their jar/content was removed for any reason! @@ -348,15 +348,15 @@ public NutsInstallCommand run() { for (Map.Entry> stringListEntry : error.entrySet()) { out.resetLine().println("the following " + (stringListEntry.getValue().size() > 1 ? "artifacts are" : "artifact is") + " cannot be ```error installed``` (" + stringListEntry.getKey() + ") : " + stringListEntry.getValue().stream().map(x -> x.id) - .map(x -> session.id().formatter().setOmitImportedGroupId(true).setValue(x.getLongId()).format().toString()) + .map(x -> NutsIdFormat.of(session).setOmitImportedGroupId(true).setValue(x.getLongId()).format().toString()) .collect(Collectors.joining(", "))); sb.append("\n" + "the following ").append(stringListEntry.getValue().size() > 1 ? "artifacts are" : "artifact is").append(" cannot be installed (").append(stringListEntry.getKey()).append(") : ").append(stringListEntry.getValue().stream().map(x -> x.id) - .map(x -> session.id().formatter().setOmitImportedGroupId(true).setValue(x.getLongId()).format().toString()) + .map(x -> NutsIdFormat.of(session).setOmitImportedGroupId(true).setValue(x.getLongId()).format().toString()) .collect(Collectors.joining(", "))); } throw new NutsInstallException(getSession(), null, NutsMessage.formatted(sb.toString().trim()), null); } - NutsMemoryPrintStream mout = session.io().createMemoryPrintStream(); + NutsMemoryPrintStream mout = NutsMemoryPrintStream.of(session); if (getSession().isPlainTrace() || (!list.emptyCommand && getSession().getConfirm() == NutsConfirmationMode.ASK)) { printList(mout, "new","installed", list.ids(x -> x.doInstall && !x.isAlreadyExists())); @@ -386,7 +386,7 @@ public NutsInstallCommand run() { } mout.println("should we proceed?"); List nonIgnored = list.ids(x -> !x.ignored); - if (!nonIgnored.isEmpty() && !getSession().term().getTerminal().ask() + if (!nonIgnored.isEmpty() && !getSession().config().getDefaultTerminal().ask() .resetLine() .setSession(session) .forBoolean(mout.toString()) @@ -419,7 +419,7 @@ public NutsInstallCommand run() { .log(NutsMessage.jstyle("failed to install {0}", info.id)); failedList.add(info.id); if (session.isPlainTrace()) { - if (!getSession().term().getTerminal().ask() + if (!getSession().config().getDefaultTerminal().ask() .resetLine() .setSession(session) .forBoolean("```error failed to install``` %s and its dependencies... Continue installation?", info.id) @@ -450,7 +450,7 @@ public NutsInstallCommand run() { private void printList(NutsPrintStream out, String skind, String saction, List all) { if (all.size() > 0) { if(session.isPlainOut()) { - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); NutsText kind = text.ofStyled(skind, NutsTextStyle.primary2()); NutsText action = text.ofStyled(saction, @@ -459,26 +459,26 @@ private void printList(NutsPrintStream out, String skind, String saction, List 1 ? "artifacts are" : "artifact is")) .append(" going to be ").append(action).append(" : ") .appendJoined( - session.text().ofPlain(", "), + NutsTexts.of(session).ofPlain(", "), all.stream().map(x - -> session.text().toText( + -> NutsTexts.of(session).toText( x.builder().omitImportedGroupId().build() ) ).collect(Collectors.toList()) ); out.resetLine().println(msg); }else{ - NutsElementFormat elm = session.elem(); - session.eout().add(elm.forObject() + NutsElements elem = NutsElements.of(session); + session.eout().add(elem.forObject() .set("command","warning") .set("artifact-kind",skind) .set("action-warning",saction) - .set("artifacts",elm.forArray().addAll( + .set("artifacts",elem.forArray().addAll( all.stream().map(x->x.toString()).toArray(String[]::new) ).build()) .build() diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/license/DefaultNutsLicenseInternalExecutable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/license/DefaultNutsLicenseInternalExecutable.java index 9c4195ba7..b74a8cf93 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/license/DefaultNutsLicenseInternalExecutable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/license/DefaultNutsLicenseInternalExecutable.java @@ -26,7 +26,8 @@ public void execute() { showDefaultHelp(); return; } - NutsCommandLine commandLine = getSession().commandLine().create(args); + NutsSession session = getSession(); + NutsCommandLine commandLine = NutsCommandLine.of(args,session); while (commandLine.hasNext()) { NutsArgument a = commandLine.peek(); if (a.isOption()) { @@ -37,19 +38,19 @@ public void execute() { return; } default: { - getSession().configureLast(commandLine); + session.configureLast(commandLine); } } } else { - getSession().configureLast(commandLine); + session.configureLast(commandLine); } } - String licenseString = NutsWorkspaceExt.of(getSession().getWorkspace()).getLicenseText(getSession()); - if (getSession().isPlainOut()) { - getSession().out().println(licenseString); + String licenseString = NutsWorkspaceExt.of(session.getWorkspace()).getLicenseText(session); + if (session.isPlainOut()) { + session.out().println(licenseString); } else { - getSession().out().printlnf(licenseString); + session.out().printlnf(licenseString); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/push/AbstractDefaultNutsPushCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/push/AbstractDefaultNutsPushCommand.java index 59e1e9c8a..1ef4e0bf9 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/push/AbstractDefaultNutsPushCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/push/AbstractDefaultNutsPushCommand.java @@ -48,14 +48,14 @@ public AbstractDefaultNutsPushCommand(NutsWorkspace ws) { public NutsPushCommand addId(String id) { checkSession(); NutsSession ws = getSession(); - return addId(id == null ? null : ws.id().parser().setLenient(false).parse(id)); + return addId(id == null ? null : NutsId.of(id,ws)); } @Override public NutsPushCommand addLockedId(String id) { checkSession(); NutsSession ws = getSession(); - return addLockedId(id == null ? null : ws.id().parser().setLenient(false).parse(id)); + return addLockedId(id == null ? null : NutsId.of(id,ws)); } @Override @@ -82,7 +82,7 @@ public NutsPushCommand removeId(String id) { if (id != null) { checkSession(); NutsSession ws = getSession(); - ids.remove(ws.id().parser().parse(id)); + ids.remove(NutsId.of(id,ws)); } return this; } @@ -103,7 +103,7 @@ public NutsPushCommand removeLockedId(String id) { NutsSession ws = getSession(); if (id != null) { if (lockedIds != null) { - lockedIds.remove(ws.id().parser().parse(id)); + lockedIds.remove(NutsId.of(id,ws)); } } return this; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/search/AbstractNutsSearchCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/search/AbstractNutsSearchCommand.java index 4e1434d91..5190de75d 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/search/AbstractNutsSearchCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/search/AbstractNutsSearchCommand.java @@ -79,7 +79,7 @@ public NutsSearchCommand clearIds() { public NutsSearchCommand addId(String id) { checkSession(); if (!NutsBlankable.isBlank(id)) { - ids.add(getSession().id().parser().setLenient(false).parse(id)); + ids.add(NutsId.of(id,getSession())); } return this; } @@ -98,7 +98,7 @@ public NutsSearchCommand addIds(String... values) { if (values != null) { for (String s : values) { if (!NutsBlankable.isBlank(s)) { - ids.add(getSession().id().parser().setLenient(false).parse(s)); + ids.add(NutsId.of(s,getSession())); } } } @@ -120,7 +120,7 @@ public NutsSearchCommand addIds(NutsId... value) { @Override public NutsSearchCommand removeId(String id) { checkSession(); - ids.remove(getSession().id().parser().parse(id)); + ids.remove(NutsId.of(id,getSession())); return this; } @@ -252,7 +252,7 @@ public NutsSearchCommand addLockedIds(String... values) { if (values != null) { for (String s : values) { if (!NutsBlankable.isBlank(s)) { - lockedIds.add(getSession().id().parser().setLenient(false).parse(s)); + lockedIds.add(NutsId.of(s,getSession())); } } } @@ -362,7 +362,7 @@ public NutsSearchCommand removeLockedId(NutsId id) { @Override public NutsSearchCommand removeLockedId(String id) { checkSession(); - lockedIds.remove(getSession().id().parser().parse(id)); + lockedIds.remove(NutsId.of(id,getSession())); return this; } @@ -370,7 +370,7 @@ public NutsSearchCommand removeLockedId(String id) { public NutsSearchCommand addLockedId(String id) { checkSession(); if (!NutsBlankable.isBlank(id)) { - lockedIds.add(getSession().id().parser().setLenient(false).parse(id)); + lockedIds.add(NutsId.of(id,getSession())); } return this; } @@ -475,7 +475,7 @@ public NutsSearchCommand setDescriptorFilter(NutsDescriptorFilter filter) { @Override public NutsSearchCommand setDescriptorFilter(String filter) { checkSession(); - this.descriptorFilter = getSession().descriptor().filter().byExpression(filter); + this.descriptorFilter = NutsDescriptorFilters.of(session).parse(filter); return this; } @@ -493,7 +493,7 @@ public NutsSearchCommand setIdFilter(NutsIdFilter filter) { @Override public NutsSearchCommand setIdFilter(String filter) { checkSession(); - this.idFilter = getSession().id().filter().byExpression(filter); + this.idFilter = NutsIdFilters.of(getSession()).parse(filter); return this; } @@ -754,7 +754,7 @@ public NutsStream getResultExecutionEntries() { return postProcessResult(IteratorBuilder.of(getResultDefinitionIteratorBase(isContent(), isEffective())) .mapMulti(x -> (x.getContent() == null || x.getContent().getFilePath() == null) ? Collections.emptyList() - : Arrays.asList(getSession().apps().execEntries().setSession(getSession()).parse(x.getContent().getFilePath())))); + : Arrays.asList(NutsExecutionEntries.of(getSession()).parse(x.getContent().getFilePath())))); } @Override @@ -952,7 +952,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { case "--api-version": { String val = cmdLine.nextBoolean().getValue().getString(); if (enabled) { - this.setTargetApiVersion(getSession().version().parse(val)); + this.setTargetApiVersion(NutsVersion.of(val,getSession())); } return true; } @@ -1017,7 +1017,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { NutsArgument b = cmdLine.nextBoolean(); if (enabled) { checkSession(); - this.setInstallStatus(getSession().filters().installStatus().byDeployed(b.getValue().getBoolean())); + this.setInstallStatus(NutsInstallStatusFilters.of(session).byDeployed(b.getValue().getBoolean())); } return true; } @@ -1027,7 +1027,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { if (enabled) { checkSession(); this.setInstallStatus( - getSession().filters().installStatus().byInstalled(b.getValue().getBoolean()) + NutsInstallStatusFilters.of(session).byInstalled(b.getValue().getBoolean()) ); } return true; @@ -1036,7 +1036,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { NutsArgument b = cmdLine.nextBoolean(); if (enabled) { checkSession(); - this.setInstallStatus(getSession().filters().installStatus().byRequired(b.getValue().getBoolean())); + this.setInstallStatus(NutsInstallStatusFilters.of(session).byRequired(b.getValue().getBoolean())); } return true; } @@ -1044,7 +1044,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { NutsArgument b = cmdLine.nextBoolean(); if (enabled) { checkSession(); - this.setInstallStatus(getSession().filters().installStatus().byObsolete(b.getValue().getBoolean())); + this.setInstallStatus(NutsInstallStatusFilters.of(session).byObsolete(b.getValue().getBoolean())); } return true; } @@ -1052,7 +1052,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { NutsArgument aa = cmdLine.nextString(); if (enabled) { checkSession(); - this.setInstallStatus(getSession().filters().installStatus().parse(aa.getValue().getString())); + this.setInstallStatus(NutsInstallStatusFilters.of(session).parse(aa.getValue().getString())); } return true; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/search/DefaultNutsSearchCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/search/DefaultNutsSearchCommand.java index 286d872e9..d30a703d1 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/search/DefaultNutsSearchCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/search/DefaultNutsSearchCommand.java @@ -103,12 +103,13 @@ private NutsRepositoryFilter createRepositoryFilter(NutsInstallStatusFilter stat } } + NutsRepositoryFilters repository = NutsRepositoryFilters.of(session); if(!searchInInstalled && searchInOtherRepositories) { - otherFilters.add(session.filters().repository().installedRepo().neg()); + otherFilters.add(repository.installedRepo().neg()); }else if(searchInInstalled && !searchInOtherRepositories){ - otherFilters.add(session.filters().repository().installedRepo()); + otherFilters.add(repository.installedRepo()); }else if(!searchInInstalled && !searchInOtherRepositories){ - otherFilters.add(session.filters().repository().never()); + otherFilters.add(repository.never()); } if(otherFilters.isEmpty()){ return null; @@ -139,13 +140,13 @@ public NutsFetchCommand toFetch() { //@Override private DefaultNutsSearch build() { checkSession(); - NutsSession ws = getSession(); + NutsSession session = getSession(); HashSet someIds = new HashSet<>(); for (NutsId id : this.getIds()) { someIds.add(id.toString()); } if (this.getIds().length == 0 && isCompanion()) { - someIds.addAll(session.extensions().getCompanionIds().stream().map(NutsId::getShortName).collect(Collectors.toList())); + someIds.addAll(this.session.extensions().getCompanionIds().stream().map(NutsId::getShortName).collect(Collectors.toList())); } if (this.getIds().length == 0 && isRuntime()) { someIds.add(NutsConstants.Ids.NUTS_RUNTIME); @@ -185,28 +186,29 @@ private DefaultNutsSearch build() { if (oo.isEmpty()) { idFilter0 = null; } else { - idFilter0 = session.id().filter().any(oo.toArray(new NutsIdFilter[0])); + idFilter0 = NutsIdFilters.of(this.session).any(oo.toArray(new NutsIdFilter[0])); } } } - NutsDescriptorFilter _descriptorFilter = ws.descriptor().filter().always(); - NutsIdFilter _idFilter = session.id().filter().always(); - NutsDependencyFilter depFilter = ws.dependency().filter().always(); - NutsRepositoryFilter rfilter = session.repos().filter().always(); + NutsDescriptorFilters dfilter = NutsDescriptorFilters.of(session); + NutsDescriptorFilter _descriptorFilter = dfilter.always(); + NutsIdFilter _idFilter = NutsIdFilters.of(this.session).always(); + NutsDependencyFilter depFilter = NutsDependencyFilters.of(session).always(); + NutsRepositoryFilter rfilter = this.session.repos().filter().always(); for (String j : this.getScripts()) { if (!NutsBlankable.isBlank(j)) { if (CoreStringUtils.containsTopWord(j, "descriptor")) { - _descriptorFilter = _descriptorFilter.and(ws.descriptor().filter().byExpression(j)); + _descriptorFilter = _descriptorFilter.and(dfilter.parse(j)); } else if (CoreStringUtils.containsTopWord(j, "dependency")) { - depFilter = depFilter.and(ws.dependency().filter().byExpression(j)); + depFilter = depFilter.and(NutsDependencyFilters.of(session).parse(j)); } else { - _idFilter = _idFilter.and(ws.id().filter().byExpression(j)); + _idFilter = _idFilter.and(NutsIdFilters.of(session).parse(j)); } } } - NutsDescriptorFilter packs = ws.descriptor().filter().byPackaging(getPackaging()); - NutsDescriptorFilter archs = ws.descriptor().filter().byArch(getArch()); + NutsDescriptorFilter packs = dfilter.byPackaging(getPackaging()); + NutsDescriptorFilter archs = dfilter.byArch(getArch()); _descriptorFilter = _descriptorFilter.and(packs).and(archs); NutsRepositoryFilter _repositoryFilter = rfilter.and(this.getRepositoryFilter()); @@ -214,50 +216,50 @@ private DefaultNutsSearch build() { _idFilter = _idFilter.and(idFilter0); if (getInstallStatus() != null) { - _idFilter = _idFilter.and(ws.id().filter().byInstallStatus(getInstallStatus())); + _idFilter = _idFilter.and(NutsIdFilters.of(session).byInstallStatus(getInstallStatus())); } if (getDefaultVersions() != null) { - _idFilter = _idFilter.and(ws.id().filter().byDefaultVersion(getDefaultVersions())); + _idFilter = _idFilter.and(NutsIdFilters.of(session).byDefaultVersion(getDefaultVersions())); } if (execType != null) { switch (execType) { case "lib": { - _descriptorFilter = _descriptorFilter.and(ws.descriptor().filter().byFlag(NutsDescriptorFlag.EXEC).neg()); + _descriptorFilter = _descriptorFilter.and(dfilter.byFlag(NutsDescriptorFlag.EXEC).neg()); break; } case "exec": { - _descriptorFilter = _descriptorFilter.and(ws.descriptor().filter().byFlag(NutsDescriptorFlag.EXEC)); + _descriptorFilter = _descriptorFilter.and(dfilter.byFlag(NutsDescriptorFlag.EXEC)); break; } case "app": { - _descriptorFilter = _descriptorFilter.and(ws.descriptor().filter().byFlag(NutsDescriptorFlag.APP)); + _descriptorFilter = _descriptorFilter.and(dfilter.byFlag(NutsDescriptorFlag.APP)); break; } case "extension": { - _descriptorFilter = _descriptorFilter.and(ws.descriptor().filter().byExtension(targetApiVersion)); + _descriptorFilter = _descriptorFilter.and(dfilter.byExtension(targetApiVersion)); break; } case "runtime": { - _descriptorFilter = _descriptorFilter.and(ws.descriptor().filter().byRuntime(targetApiVersion)); + _descriptorFilter = _descriptorFilter.and(dfilter.byRuntime(targetApiVersion)); break; } case "companions": { - _descriptorFilter = _descriptorFilter.and(ws.descriptor().filter().byCompanion(targetApiVersion)); + _descriptorFilter = _descriptorFilter.and(dfilter.byCompanion(targetApiVersion)); break; } } } else { if (targetApiVersion != null) { - _descriptorFilter = _descriptorFilter.and(ws.descriptor().filter().byApiVersion(targetApiVersion)); + _descriptorFilter = _descriptorFilter.and(dfilter.byApiVersion(targetApiVersion)); } } if (!lockedIds.isEmpty()) { - _descriptorFilter = _descriptorFilter.and(ws.descriptor().filter().byLockedIds( + _descriptorFilter = _descriptorFilter.and(dfilter.byLockedIds( lockedIds.stream().map(NutsId::getFullName).toArray(String[]::new) )); } if (!wildcardIds.isEmpty()) { - _idFilter = _idFilter.and(ws.id().filter().byName(wildcardIds.toArray(new String[0]))); + _idFilter = _idFilter.and(NutsIdFilters.of(session).byName(wildcardIds.toArray(new String[0]))); } NutsRepositoryFilter extraRepositoryFilter = createRepositoryFilter(installStatus, _idFilter, getSession()); if(extraRepositoryFilter!=null){ @@ -534,7 +536,7 @@ public Iterator getResultIdIteratorBase(Boolean forceInlineDependencies) NutsWorkspaceUtils wu = NutsWorkspaceUtils.of(session); if (regularIds.length > 0) { for (String id : regularIds) { - NutsId nutsId = session.id().parser().parse(id); + NutsId nutsId = NutsId.of(id,session); if (nutsId != null) { List nutsId2 = new ArrayList<>(); if (NutsBlankable.isBlank(nutsId.getGroupId())) { @@ -546,7 +548,7 @@ public Iterator getResultIdIteratorBase(Boolean forceInlineDependencies) if (!nutsId.getArtifactId().contains("*")) { NutsRepositorySPI repoSPI = wu .repoSPI(NutsWorkspaceExt.of(getWorkspace()).getInstalledRepository()); - Iterator it = repoSPI.search().setFetchMode(NutsFetchMode.LOCAL).setFilter(session.filters().id().byName( + Iterator it = repoSPI.search().setFetchMode(NutsFetchMode.LOCAL).setFilter(NutsIdFilters.of(session).byName( nutsId.builder().setGroupId("*").build().toString() )).setSession(getSession()).getResult(); installedIds = IteratorUtils.toList(it); @@ -567,8 +569,8 @@ public Iterator getResultIdIteratorBase(Boolean forceInlineDependencies) } List> toConcat = new ArrayList<>(); for (NutsId nutsId1 : nutsId2) { - NutsIdFilter idFilter2 = session.filters().all(sIdFilter, - session.id().filter().byName(nutsId1.getFullName()) + NutsIdFilter idFilter2 = NutsFilters.of(session).all(sIdFilter, + NutsIdFilters.of(session).byName(nutsId1.getFullName()) ); NutsIdFilter filter = CoreNutsUtils.simplify(CoreFilterUtils.idFilterOf(nutsId1.getProperties(), idFilter2, sDescriptorFilter, session)); @@ -607,7 +609,7 @@ public Iterator getResultIdIteratorBase(Boolean forceInlineDependencies) .setRepositoryFilter(search.getRepositoryFilter()) .setDescriptorFilter(search.getDescriptorFilter()); search2.setIdFilter( - session.id().filter().byName(nutsId.builder().setGroupId("*").build().toString()) + NutsIdFilters.of(session).byName(nutsId.builder().setGroupId("*").build().toString()) .and(search.getIdFilter()) ); Iterator extraResult = search2.getResultIds().iterator(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/CommandNutsWorkspaceCommandFactory.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/CommandNutsWorkspaceCommandFactory.java index 04cd90aee..c16960899 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/CommandNutsWorkspaceCommandFactory.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/CommandNutsWorkspaceCommandFactory.java @@ -32,7 +32,7 @@ public void configure(NutsCommandFactoryConfig config) { findCommand = validateCommand(p.get("find")); execCommand = validateCommand(p.get("exec")); String slistCommand = p.get("list"); - listCommand = slistCommand == null ? new String[0] : ws.commandLine().parse(slistCommand).toStringArray(); + listCommand = slistCommand == null ? new String[0] : NutsCommandLine.parse(slistCommand,ws).toStringArray(); if (listCommand.length > 0 && !listCommand[0].contains(":")) { listCommand = new String[0]; } @@ -53,7 +53,7 @@ private String[] validateCommand(String command) { if (command == null) { return new String[0]; } - String[] commandArr = ws.commandLine().parse(command).toStringArray(); + String[] commandArr = NutsCommandLine.parse(command,ws).toStringArray(); if (commandArr.length == 0) { return commandArr; } @@ -98,7 +98,7 @@ public NutsCommandConfig findCommand(String name, NutsSession session) { if (r == 0) { return new NutsCommandConfig() .setFactoryId(getFactoryId()) - .setOwner(session.id().parser().parse(ec[0])) + .setOwner(NutsId.of(ec[0],session)) .setName(name) .setCommand(Arrays.copyOfRange(ec, 1, ec.length)); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/ConfigNutsWorkspaceCommandFactory.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/ConfigNutsWorkspaceCommandFactory.java index 270777d35..1043d0784 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/ConfigNutsWorkspaceCommandFactory.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/ConfigNutsWorkspaceCommandFactory.java @@ -32,7 +32,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().setSession(session).of(ConfigNutsWorkspaceCommandFactory.class); + LOG = NutsLogger.of(ConfigNutsWorkspaceCommandFactory.class,session); } return LOG; } @@ -84,7 +84,7 @@ protected void checkSession(NutsSession session) { public void installCommand(NutsCommandConfig command, NutsSession session) { checkSession(session); Path path = getCommandsFolder(session).resolve(command.getName() + NutsConstants.Files.NUTS_COMMAND_FILE_EXTENSION); - session.elem().setContentType(NutsContentType.JSON).setValue(command) + NutsElements.of(session).json().setValue(command) .setNtf(false).print(path); NutsWorkspaceConfigManagerExt.of(session.config()).getModel().fireConfigurationChanged("command", session, ConfigEventType.MAIN); } @@ -94,7 +94,7 @@ public NutsCommandConfig findCommand(String name, NutsSession session) { checkSession(session); Path file = getCommandsFolder(session).resolve(name + NutsConstants.Files.NUTS_COMMAND_FILE_EXTENSION); if (Files.exists(file)) { - NutsCommandConfig c = session.elem().setContentType(NutsContentType.JSON).parse(file, NutsCommandConfig.class); + NutsCommandConfig c = NutsElements.of(session).json().parse(file, NutsCommandConfig.class); if (c != null) { c.setName(name); return c; @@ -126,7 +126,7 @@ public List findCommands(Predicate filter, if (file.getFileName().toString().endsWith(NutsConstants.Files.NUTS_COMMAND_FILE_EXTENSION)) { NutsCommandConfig c = null; try { - c = session.elem().setContentType(NutsContentType.JSON).parse(file, NutsCommandConfig.class); + c = NutsElements.of(session).json().parse(file, NutsCommandConfig.class); } catch (Exception ex) { _LOGOP(session).level(Level.FINE).error(ex).log(NutsMessage.jstyle("unable to parse {0}", file)); // diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsAliasExecutable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsAliasExecutable.java index 590ed5dfa..0586ec256 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsAliasExecutable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsAliasExecutable.java @@ -5,11 +5,7 @@ */ package net.thevpc.nuts.runtime.standalone.wscommands.settings; -import net.thevpc.nuts.NutsCommandExecOptions; -import net.thevpc.nuts.NutsExecutableType; -import net.thevpc.nuts.NutsId; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsWorkspaceCustomCommand; +import net.thevpc.nuts.*; import net.thevpc.nuts.runtime.standalone.wscommands.exec.AbstractNutsExecutableCommand; /** @@ -25,7 +21,7 @@ public class DefaultNutsAliasExecutable extends AbstractNutsExecutableCommand { public DefaultNutsAliasExecutable(NutsWorkspaceCustomCommand command, NutsCommandExecOptions o, NutsSession session, String[] args) { super(command.getName(), - session.commandLine().create(command.getCommand()).toString(), + NutsCommandLine.of(command.getCommand(),session).toString(), NutsExecutableType.ALIAS); this.command = command; this.o = o; diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsSettingsInternalExecutable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsSettingsInternalExecutable.java index e5b241d31..51fa4b8da 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsSettingsInternalExecutable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsSettingsInternalExecutable.java @@ -33,7 +33,7 @@ public void execute() { // Thread.currentThread().getContextClassLoader()); Boolean autoSave = true; - NutsCommandLine cmd = getSession().commandLine().create(args); + NutsCommandLine cmd = NutsCommandLine.of(args,getSession()); boolean empty = true; NutsArgument a; do { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsUpdateStatisticsCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsUpdateStatisticsCommand.java index f9e01337c..dd2040a52 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsUpdateStatisticsCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsUpdateStatisticsCommand.java @@ -77,14 +77,14 @@ public NutsUpdateStatisticsCommand run() { } } } - NutsTextManager factory = getSession().text(); + NutsTexts factory = NutsTexts.of(getSession()); if (!processed) { if (session.isPlainTrace()) { - session.out().resetLine().printf("%s updating workspace stats%n", factory.ofStyled(getSession().locations().getWorkspaceLocation(), NutsTextStyle.path())); + session.out().resetLine().printf("%s updating workspace stats%n", getSession().locations().getWorkspaceLocation()); } for (NutsRepository repo : getSession().repos().getRepositories()) { if (session.isPlainTrace()) { - session.out().resetLine().printf("%s updating stats %s%n", factory.ofStyled(getSession().locations().getWorkspaceLocation(), NutsTextStyle.path()), repo); + session.out().resetLine().printf("%s updating stats %s%n", getSession().locations().getWorkspaceLocation(), repo); } NutsWorkspaceUtils.of(session).repoSPI(repo).updateStatistics() .setSession(session) diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsWorkspaceCustomCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsWorkspaceCustomCommand.java index f56cebb77..def7e3fac 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsWorkspaceCustomCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/DefaultNutsWorkspaceCustomCommand.java @@ -30,7 +30,7 @@ protected NutsLoggerOp _LOGOP(NutsSession session) { protected NutsLogger _LOG(NutsSession session) { if (LOG == null) { - LOG = session.log().setSession(session).of(DefaultNutsWorkspaceCustomCommand.class); + LOG = NutsLogger.of(DefaultNutsWorkspaceCustomCommand.class,session); } return LOG; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/alias/NutsSettingsAliasSubCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/alias/NutsSettingsAliasSubCommand.java index c60dd3849..2104f6838 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/alias/NutsSettingsAliasSubCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/alias/NutsSettingsAliasSubCommand.java @@ -38,8 +38,8 @@ public AliasInfo(String name, String command, String factoryId, NutsId owner, St public AliasInfo(NutsWorkspaceCustomCommand a, NutsSession ws) { name = a.getName(); - command = ws.commandLine().create(a.getCommand()).toString(); - executionOptions = ws.commandLine().create(a.getExecutorOptions()).toString(); + command = NutsCommandLine.of(a.getCommand(),ws).toString(); + executionOptions = NutsCommandLine.of(a.getExecutorOptions(),ws).toString(); factoryId = a.getFactoryId(); owner = a.getOwner(); } @@ -109,7 +109,7 @@ public boolean test(NutsWorkspaceCustomCommand nutsWorkspaceCommandAlias) { r.stream().collect( Collectors.toMap( NutsWorkspaceCustomCommand::getName, - x -> session.commandLine().create(x.getCommand()).toString(), + x -> NutsCommandLine.of(x.getCommand(),session).toString(), (x, y) -> { throw new NutsIllegalArgumentException(session,NutsMessage.cstyle("duplicate %s",x)); }, @@ -164,9 +164,9 @@ public boolean test(NutsWorkspaceCustomCommand nutsWorkspaceCommandAlias) { session.commands() .addCommand( new NutsCommandConfig() - .setCommand(session.commandLine().parse(value.command).toStringArray()) + .setCommand(NutsCommandLine.parse(value.command,session).toStringArray()) .setName(value.name) - .setExecutorOptions(session.commandLine().parse(value.executionOptions).toStringArray()) + .setExecutorOptions(NutsCommandLine.parse(value.executionOptions,session).toStringArray()) ); } session.config().save(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/backup/NutsSettingsBackupSubCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/backup/NutsSettingsBackupSubCommand.java index 95abbb1a6..0915111c4 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/backup/NutsSettingsBackupSubCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/backup/NutsSettingsBackupSubCommand.java @@ -38,7 +38,7 @@ public boolean exec(NutsCommandLine commandLine, Boolean autoSave, NutsSession s } if (commandLine.isExecMode()) { List all = new ArrayList<>(); - all.add(Paths.get(session.locations().getWorkspaceLocation()) + all.add(session.locations().getWorkspaceLocation().toFile() .resolve("nuts-workspace.json").toString() ); for (NutsStoreLocation value : NutsStoreLocation.values()) { @@ -57,9 +57,7 @@ public boolean exec(NutsCommandLine commandLine, Boolean autoSave, NutsSession s if (Paths.get(file).getFileName().toString().indexOf('.') < 0) { file += ".zip"; } - NutsIOCompressAction cmp = session - .io() - .compress(); + NutsCompress cmp = NutsCompress.of(session); for (String s : all) { cmp.addSource(s); } @@ -97,9 +95,8 @@ public boolean exec(NutsCommandLine commandLine, Boolean autoSave, NutsSession s } if (commandLine.isExecMode()) { NutsObjectElement[] nutsWorkspaceConfigRef = new NutsObjectElement[1]; - session - .io() - .uncompress() + NutsElements elem = NutsElements.of(session); + NutsUncompress.of(session) .from(file) .visit(new NutsIOUncompressVisitor() { @Override @@ -110,7 +107,7 @@ public boolean visitFolder(String path) { @Override public boolean visitFile(String path, InputStream inputStream) { if ("/nuts-workspace.json".equals(path)) { - NutsObjectElement e = session.elem().setContentType(NutsContentType.JSON) + NutsObjectElement e = elem.json() .parse(inputStream, NutsObjectElement.class).asObject(); nutsWorkspaceConfigRef[0] = e; return false; @@ -122,7 +119,7 @@ public boolean visitFile(String path, InputStream inputStream) { commandLine.required(NutsMessage.cstyle("not a valid file : %s", file)); } if (ws == null || ws.isEmpty()) { - NutsElementFormat prv = session.elem().setSession(session); + NutsElements prv = elem.setSession(session); ws = nutsWorkspaceConfigRef[0].get(prv.forString("name")).asString(); } if (ws == null || ws.isEmpty()) { @@ -130,9 +127,7 @@ public boolean visitFile(String path, InputStream inputStream) { } String platformHomeFolder = NutsUtilPlatforms.getWorkspaceLocation(null, session.config().stored().isGlobal(), ws); - session - .io() - .uncompress() + NutsUncompress.of(session) .from(file) .to(platformHomeFolder) .setSkipRoot(true).run(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/connect/NutsSettingsConnectSubCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/connect/NutsSettingsConnectSubCommand.java index 156550a46..77647c77c 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/connect/NutsSettingsConnectSubCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/connect/NutsSettingsConnectSubCommand.java @@ -24,7 +24,6 @@ public class NutsSettingsConnectSubCommand extends AbstractNutsSettingsSubComman @Override public boolean exec(NutsCommandLine commandLine, Boolean autoSave, NutsSession session) { - NutsCommandLineManager commandLineFormat = session.commandLine(); if (commandLine.next("connect") != null) { char[] password = null; String server = null; @@ -35,7 +34,7 @@ public boolean exec(NutsCommandLine commandLine, Boolean autoSave, NutsSession s } else if (commandLine.peek().isOption()) { session.configureLast(commandLine); } else { - server = commandLine.nextRequiredNonOption(commandLineFormat.createName("ServerAddress")).getString(); + server = commandLine.nextRequiredNonOption(NutsArgumentName.of("ServerAddress",session)).getString(); commandLine.setCommandName("settings connect").unexpectedArgument(); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/delete/NutsSettingsDeleteFoldersSubCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/delete/NutsSettingsDeleteFoldersSubCommand.java index be1637426..d510d8909 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/delete/NutsSettingsDeleteFoldersSubCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/delete/NutsSettingsDeleteFoldersSubCommand.java @@ -59,7 +59,7 @@ public boolean exec(NutsCommandLine cmdLine, Boolean autoSave, NutsSession sessi private void deleteWorkspaceFolder(NutsSession session, NutsStoreLocation folder, boolean force) { String sstoreLocation = session.locations().getStoreLocation(folder); if (sstoreLocation != null) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); Path storeLocation = Paths.get(sstoreLocation); if (Files.exists(storeLocation)) { session.out().printf("```error deleting``` %s for workspace %s folder %s ...%n", @@ -88,7 +88,7 @@ private void deleteRepoFolder(NutsRepository repository, NutsSession session, Nu String sstoreLocation = session.locations().getStoreLocation(folder); if (sstoreLocation != null) { Path storeLocation=Paths.get(sstoreLocation); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (Files.exists(storeLocation)) { session.out().printf("```error deleting``` %s for repository %s folder %s ...%n", factory.ofStyled(folder.id(),NutsTextStyle.primary1()), @@ -137,7 +137,7 @@ private static void deleteRepoCache(NutsRepository repository, NutsSession sessi if (s != null) { if (Files.exists(s)) { session.out().printf("```error deleting``` %s folder %s ...%n", - session.text().ofStyled("cache",NutsTextStyle.primary1()) + NutsTexts.of(session).ofStyled("cache",NutsTextStyle.primary1()) ,s); if (force || session.getTerminal().ask() diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/imports/NutsSettingsImportSubCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/imports/NutsSettingsImportSubCommand.java index e2edc0e76..f752bbf7d 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/imports/NutsSettingsImportSubCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/imports/NutsSettingsImportSubCommand.java @@ -5,8 +5,9 @@ */ package net.thevpc.nuts.runtime.standalone.wscommands.settings.subcommands.imports; +import net.thevpc.nuts.NutsArgumentName; import net.thevpc.nuts.NutsCommandLine; -import net.thevpc.nuts.NutsCommandLineManager; +import net.thevpc.nuts.NutsCommandLines; import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.runtime.standalone.wscommands.settings.subcommands.AbstractNutsSettingsSubCommand; @@ -18,7 +19,6 @@ public class NutsSettingsImportSubCommand extends AbstractNutsSettingsSubCommand @Override public boolean exec(NutsCommandLine cmdLine, Boolean autoSave, NutsSession session) { - NutsCommandLineManager commandLineFormat = session.commandLine(); if (cmdLine.next("list imports", "li") != null) { cmdLine.setCommandName("config list imports").unexpectedArgument(); if (cmdLine.isExecMode()) { @@ -36,7 +36,7 @@ public boolean exec(NutsCommandLine cmdLine, Boolean autoSave, NutsSession sessi return true; } else if (cmdLine.next("import", "ia") != null) { do { - String a = cmdLine.required().nextNonOption(commandLineFormat.createName("import")).getString(); + String a = cmdLine.required().nextNonOption(NutsArgumentName.of("import",session)).getString(); if (cmdLine.isExecMode()) { session.imports().add(new String[]{a}); } @@ -47,7 +47,7 @@ public boolean exec(NutsCommandLine cmdLine, Boolean autoSave, NutsSession sessi return true; } else if (cmdLine.next("unimport", "ir") != null) { while (cmdLine.hasNext()) { - String ii = cmdLine.required().nextNonOption(commandLineFormat.createName("import")).getString(); + String ii = cmdLine.required().nextNonOption(NutsArgumentName.of("import",session)).getString(); if (cmdLine.isExecMode()) { session.imports().remove(new String[]{ii}); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/log/NutsSettingsLogSubCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/log/NutsSettingsLogSubCommand.java index 4c01c7490..22c1ce2f3 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/log/NutsSettingsLogSubCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/log/NutsSettingsLogSubCommand.java @@ -21,42 +21,41 @@ public class NutsSettingsLogSubCommand extends AbstractNutsSettingsSubCommand { public boolean exec(NutsCommandLine cmdLine, Boolean autoSave, NutsSession session) { if (cmdLine.next("set loglevel", "sll") != null) { // NutsWorkspaceConfigManager configManager = context.getWorkspace().config(); - NutsLogManager lm= session.log(); if (cmdLine.next("verbose", "finest") != null) { if (cmdLine.isExecMode()) { - lm.setTermLevel(Level.FINEST); + NutsLogger.setTermLevel(Level.FINEST,session); } } else if (cmdLine.next("fine") != null) { if (cmdLine.isExecMode()) { - lm.setTermLevel(Level.FINE); + NutsLogger.setTermLevel(Level.FINE,session); } } else if (cmdLine.next("finer") != null) { if (cmdLine.isExecMode()) { - lm.setTermLevel(Level.FINER); + NutsLogger.setTermLevel(Level.FINER,session); } } else if (cmdLine.next("info") != null) { if (cmdLine.isExecMode()) { - lm.setTermLevel(Level.INFO); + NutsLogger.setTermLevel(Level.INFO,session); } } else if (cmdLine.next("warning") != null) { if (cmdLine.isExecMode()) { - lm.setTermLevel(Level.WARNING); + NutsLogger.setTermLevel(Level.WARNING,session); } } else if (cmdLine.next("severe", "error") != null) { if (cmdLine.isExecMode()) { - lm.setTermLevel(Level.SEVERE); + NutsLogger.setTermLevel(Level.SEVERE,session); } } else if (cmdLine.next("config") != null) { if (cmdLine.isExecMode()) { - lm.setTermLevel(Level.CONFIG); + NutsLogger.setTermLevel(Level.CONFIG,session); } } else if (cmdLine.next("off") != null) { if (cmdLine.isExecMode()) { - lm.setTermLevel(Level.OFF); + NutsLogger.setTermLevel(Level.OFF,session); } } else if (cmdLine.next("all") != null) { if (cmdLine.isExecMode()) { - lm.setTermLevel(Level.ALL); + NutsLogger.setTermLevel(Level.ALL,session); } } else { if (cmdLine.isExecMode()) { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/NdiScriptOptions.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/NdiScriptOptions.java index fbdea1ad5..432ad2fc0 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/NdiScriptOptions.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/NdiScriptOptions.java @@ -204,10 +204,10 @@ public NutsId resolveNutsApiId() { .getParent()) .filter( f - -> session.version().parse(f.getFileName().toString()).getLong(0, -1)==-1 + -> NutsVersion.of(f.getFileName().toString(),session).getLong(0, -1)==-1 && Files.exists(f.resolve("nuts-api-config.json")) ).map( - f -> session.version().parse(f.getFileName().toString()) + f -> NutsVersion.of(f.getFileName().toString(),session) ).sorted(Comparator.reverseOrder()).findFirst().orElse(null); } catch (IOException e) { throw new UncheckedIOException(e); @@ -230,7 +230,7 @@ public Path getWorkspaceLocation() { NutsWorkspaceBootConfig bootConfig = loadSwitchWorkspaceLocationConfig(getLauncher().getSwitchWorkspaceLocation()); return Paths.get(bootConfig.getEffectiveWorkspace()); } else { - return Paths.get(session.locations().getWorkspaceLocation()); + return session.locations().getWorkspaceLocation().toFile(); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/NutsSettingsNdiSubCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/NutsSettingsNdiSubCommand.java index c131d2303..8bdf2194e 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/NutsSettingsNdiSubCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/NutsSettingsNdiSubCommand.java @@ -154,7 +154,7 @@ public void runAddLauncher(NutsCommandLine commandLine, NutsSession session) { } else if ((a = commandLine.nextString("-i", "--installed")) != null) { session.setConfirm(NutsConfirmationMode.YES); for (NutsId resultId : session.search().setInstallStatus( - session.filters().installStatus().byInstalled(true) + NutsInstallStatusFilters.of(session).byInstalled(true) ).getResultIds()) { idsToInstall.add(resultId.getLongName()); missingAnyArgument = false; @@ -256,7 +256,6 @@ public void runRemoveLauncher(NutsCommandLine commandLine, NutsSession session) if (missingAnyArgument) { commandLine.required(); } - Path workspaceLocation = Paths.get(session.locations().getWorkspaceLocation()); if (commandLine.isExecMode()) { if (forceAll) { session.setConfirm(NutsConfirmationMode.YES); @@ -384,12 +383,12 @@ private void printResults(NutsSession session, PathInfo[] result) { session.out().resetLine().printf("%s script %-" + namesSize + "s for %s" + " at %s%n", (ndiScriptInfo.getStatus() == PathInfo.Status.OVERRIDDEN) - ? session.text().ofStyled("re-install", NutsTextStyles.of(NutsTextStyle.success(), NutsTextStyle.underlined())) - : session.text().ofStyled("install", NutsTextStyle.success()) + ? NutsTexts.of(session).ofStyled("re-install", NutsTextStyles.of(NutsTextStyle.success(), NutsTextStyle.underlined())) + : NutsTexts.of(session).ofStyled("install", NutsTextStyle.success()) , - session.text().ofStyled(ndiScriptInfo.getPath().getFileName().toString(), NutsTextStyle.path()), + NutsTexts.of(session).ofStyled(ndiScriptInfo.getPath().getFileName().toString(), NutsTextStyle.path()), ndiScriptInfo.getId(), - session.text().ofStyled(CoreIOUtils.betterPath(ndiScriptInfo.getPath().toString()), NutsTextStyle.path()) + NutsTexts.of(session).ofStyled(CoreIOUtils.betterPath(ndiScriptInfo.getPath().toString()), NutsTextStyle.path()) ); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/base/BaseSystemNdi.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/base/BaseSystemNdi.java index b73111f47..e7a29ebe8 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/base/BaseSystemNdi.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/base/BaseSystemNdi.java @@ -5,6 +5,7 @@ import net.thevpc.nuts.runtime.core.shell.ReplaceString; import net.thevpc.nuts.runtime.core.shell.ScriptBuilder; import net.thevpc.nuts.runtime.core.util.CoreIOUtils; +import net.thevpc.nuts.runtime.standalone.util.NutsWorkspaceUtils; import net.thevpc.nuts.runtime.standalone.wscommands.settings.PathInfo; import net.thevpc.nuts.runtime.standalone.wscommands.settings.subcommands.ndi.*; import net.thevpc.nuts.runtime.standalone.wscommands.settings.subcommands.ndi.script.*; @@ -156,7 +157,7 @@ public Path getBinScriptFile(String name, NdiScriptOptions options) { @Override public PathInfo[] createArtifactScript(NdiScriptOptions options) { - NutsId nid = session.id().parser().parse(options.getId()); + NutsId nid = NutsId.of(options.getId(),session); List r = new ArrayList<>(); if (isNutsBootId(nid)) { r.addAll(Arrays.asList( @@ -214,9 +215,9 @@ public PathInfo[] createArtifactScript(NdiScriptOptions options) { public void removeNutsScript(String id, String switchWorkspaceLocation, NutsSession session) { NdiScriptOptions options = new NdiScriptOptions().setSession(session); options.getLauncher().setSwitchWorkspaceLocation(switchWorkspaceLocation); - NutsId nid = this.session.id().parser().parse(id); + NutsId nid = NutsId.of(id,session); Path f = getBinScriptFile(nid.getArtifactId(), options); - NutsTextManager factory = this.session.text(); + NutsTexts factory = NutsTexts.of(this.session); if (Files.isRegularFile(f)) { if (session.getTerminal().ask() .resetLine() @@ -262,10 +263,8 @@ public boolean isNutsBootId(NutsId nid) { public PathInfo[] addScript(NdiScriptOptions options, String[] all) { List idsToInstall = Arrays.asList(all); NutsSession session = options.getSession(); - if (session == null) { - throw new IllegalArgumentException("missing session"); - } - Path workspaceLocation = Paths.get(session.locations().getWorkspaceLocation()); + NutsWorkspaceUtils.checkSession(getSession().getWorkspace(), options.getSession()); + Path workspaceLocation = session.locations().getWorkspaceLocation().toFile(); List result = new ArrayList<>(); Boolean systemWideConfig = options.getLauncher().getSystemWideConfig(); if (!idsToInstall.isEmpty()) { @@ -274,7 +273,7 @@ public PathInfo[] addScript(NdiScriptOptions options, String[] all) { } boolean includeEnv = options.isIncludeEnv(); for (String id : idsToInstall) { - NutsId nid = session.id().parser().parse(id); + NutsId nid = NutsId.of(id,session); if (nid == null) { throw new NutsExecutionException(session, NutsMessage.cstyle("unable to create script for %s : invalid id", id), 100); } @@ -286,12 +285,12 @@ public PathInfo[] addScript(NdiScriptOptions options, String[] all) { // if (includeEnv) { // linkNameCurrent = prepareLinkName(linkNameCurrent); // } - List nutsIds = idsToInstall.stream().filter(x -> isNutsBootId(session.id().parser().parse(x))).collect(Collectors.toList()); - List nonNutsIds = idsToInstall.stream().filter(x -> !isNutsBootId(session.id().parser().parse(x))).collect(Collectors.toList()); + List nutsIds = idsToInstall.stream().filter(x -> isNutsBootId(NutsId.of(x,session))).collect(Collectors.toList()); + List nonNutsIds = idsToInstall.stream().filter(x -> !isNutsBootId(NutsId.of(x,session))).collect(Collectors.toList()); boolean bootAlreadyProcessed = false; for (String id : nutsIds) { try { - NutsId nid = session.id().parser().parse(id); + NutsId nid = NutsId.of(id,session); bootAlreadyProcessed = true; if (!nid.getVersion().isBlank()) { String verString = nid.getVersion().toString(); @@ -320,7 +319,7 @@ public PathInfo[] addScript(NdiScriptOptions options, String[] all) { } for (String id : nonNutsIds) { try { - NutsId nid = session.id().parser().parse(id); + NutsId nid = NutsId.of(id,session); if (nid == null) { throw new NutsExecutionException(session, NutsMessage.cstyle("unable to create script for %s : invalid id", id), 100); } @@ -666,8 +665,8 @@ protected int compareIconExtensions(String a, String b) { } protected int compareIconPaths(String a, String b) { - String n1 = session.io().path(a).getLastExtension(); - String n2 = session.io().path(b).getLastExtension(); + String n1 = NutsPath.of(a,session).getLastExtension(); + String n2 = NutsPath.of(b,session).getLastExtension(); return compareIconExtensions(n1, n2); } @@ -676,7 +675,7 @@ protected String resolveBestIcon(String... iconPaths) { List all = Arrays.stream(iconPaths).map(x -> (x == null) ? "" : x.trim()) .filter(x -> !x.isEmpty()) .filter(x -> - resolveIconExtensionPriority(session.io().path(x).getLastExtension()) >= 0 + resolveIconExtensionPriority(NutsPath.of(x,session).getLastExtension()) >= 0 ) .sorted(this::compareIconPaths).collect(Collectors.toList()); if (all.size() > 0) { @@ -716,7 +715,7 @@ public String getPreferredIconPath(NutsId appId) { String iconPath = null; if (descAppIcon != null) { String descAppIcon0 = descAppIcon; - String descAppIconDigest = session.io().hash().md5().setSource(new ByteArrayInputStream(descAppIcon0.getBytes())).computeString(); + String descAppIconDigest = NutsHash.of(session).md5().setSource(new ByteArrayInputStream(descAppIcon0.getBytes())).computeString(); NutsPath p0 = NutsPath.of(descAppIcon, session); if (descAppIcon.startsWith("classpath://")) { descAppIcon = "nuts-resource://" + appDef.getId().getLongName() + "" + descAppIcon.substring("classpath://".length() - 1); @@ -728,9 +727,9 @@ public String getPreferredIconPath(NutsId appId) { if (Files.isRegularFile(localIconPath)) { iconPath = localIconPath.toString(); } else { - NutsPath p = session.io().path(descAppIcon); + NutsPath p = NutsPath.of(descAppIcon,session); if (p.exists()) { - session.io().copy() + NutsCp.of(session) .from(p) .to(localIconPath) .run(); @@ -767,7 +766,8 @@ public PathInfo[] createShortcut(NutsDesktopIntegrationItem nutsDesktopIntegrati .setDistinct(true) .getResultDefinitions().singleton(); - NutsId appId = options.getSession().id().parser().parse(options.getId()); + NutsSession session = options.getSession(); + NutsId appId = NutsId.of(options.getId(),session); NutsDefinition appDef = loadIdDefinition(appId); List cmd = new ArrayList<>(); @@ -798,9 +798,9 @@ public PathInfo[] createShortcut(NutsDesktopIntegrationItem nutsDesktopIntegrati shortcutName = "%N"; } shortcutName += "%s%v%s%h"; - shortcutName = NameBuilder.label(appDef.getId(), shortcutName, null, appDef.getDescriptor(), session).buildName(); + shortcutName = NameBuilder.label(appDef.getId(), shortcutName, null, appDef.getDescriptor(), this.session).buildName(); - String execCmd = session.commandLine().create(cmd.toArray(new String[0])).toString(); + String execCmd = NutsCommandLine.of(cmd, this.session).toString(); FreeDesktopEntry.Group sl = FreeDesktopEntry.Group.desktopEntry(shortcutName, execCmd, cwd); sl.setStartNotify(true); sl.setIcon(iconPath); @@ -862,7 +862,7 @@ public PathInfo[] createLaunchTermShortcut(NutsDesktopIntegrationItem nutsDeskto name = NameBuilder.label(options.resolveNutsApiId(), "Nuts Terminal%s%v%s%h", null, options.resolveNutsApiDef().getDescriptor(), session) .buildName(); } - String execCmd = session.commandLine().create(cmd).toString(); + String execCmd = NutsCommandLine.of(new String[]{cmd},session).toString(); return createShortcut(nutsDesktopIntegrationItem, options.resolveNutsApiId(), fileName, diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/script/FromTemplateScriptBuilder.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/script/FromTemplateScriptBuilder.java index 0a42574bb..fef3134bc 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/script/FromTemplateScriptBuilder.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/script/FromTemplateScriptBuilder.java @@ -152,7 +152,7 @@ public String apply(String s) { case "NUTS_VERSION": return getSession().getWorkspace().getApiVersion().toString(); case "NUTS_WORKSPACE": - return getSession().locations().getWorkspaceLocation(); + return getSession().locations().getWorkspaceLocation().toString(); case "NUTS_WORKSPACE_APPS": return getSession().locations().getStoreLocation(NutsStoreLocation.APPS); case "NUTS_WORKSPACE_CONFIG": diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/unix/AnyNixNdi.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/unix/AnyNixNdi.java index 82b2f526c..2d5349195 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/unix/AnyNixNdi.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/unix/AnyNixNdi.java @@ -47,7 +47,7 @@ public String createNutsScriptContent(NutsId fnutsId, NdiScriptOptions options, } public void onPostGlobal(NdiScriptOptions options, PathInfo[] updatedPaths) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (Arrays.stream(updatedPaths).anyMatch(x -> x.getStatus() != PathInfo.Status.DISCARDED) && session.isTrace()) { if (session.isPlainTrace()) { session.out().resetLine().printf("%s %s to point to workspace %s%n", @@ -58,7 +58,7 @@ public void onPostGlobal(NdiScriptOptions options, PathInfo[] updatedPaths) { factory.builder().appendJoined(", ", Arrays.stream(updatedPaths).map(x -> factory.ofStyled(x.getPath().getFileName().toString(), NutsTextStyle.path())).collect(Collectors.toList())), - factory.ofStyled(session.locations().getWorkspaceLocation(), NutsTextStyle.path()) + session.locations().getWorkspaceLocation() ); } final String sysRcName = NutsShellHelper.of(session.env().getShellFamily()).getSysRcName(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/win/WindowFreeDesktopEntryWriter.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/win/WindowFreeDesktopEntryWriter.java index 1f254fbdf..fb5e6a4c7 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/win/WindowFreeDesktopEntryWriter.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/ndi/win/WindowFreeDesktopEntryWriter.java @@ -1,5 +1,6 @@ package net.thevpc.nuts.runtime.standalone.wscommands.settings.subcommands.ndi.win; +import net.thevpc.nuts.NutsCommandLine; import net.thevpc.nuts.NutsId; import net.thevpc.nuts.NutsPrintStream; import net.thevpc.nuts.NutsSession; @@ -66,7 +67,7 @@ public PathInfo[] writeMenu(FreeDesktopEntry descriptor, String fileName, boolea if (wd == null) { wd = System.getProperty("user.home"); } - String[] cmd = session.commandLine().parse(root.getExec()).toStringArray(); + String[] cmd = NutsCommandLine.parse(root.getExec(),session).toStringArray(); List categories = new ArrayList<>(root.getCategories()); if (categories.isEmpty()) { categories.add("/"); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/repo/NutsSettingsRepositorySubCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/repo/NutsSettingsRepositorySubCommand.java index 9fb755b39..b94d2031a 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/repo/NutsSettingsRepositorySubCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/repo/NutsSettingsRepositorySubCommand.java @@ -25,7 +25,6 @@ public static RepoInfo repoInfo(NutsRepository x, boolean tree, NutsSession sess @Override public boolean exec(NutsCommandLine cmdLine, Boolean autoSave, NutsSession session) { - NutsCommandLineManager commandLineFormat = session.commandLine(); // NutsWorkspace ws = session.getWorkspace(); // if (cmdLine.next("add repo", "cr") != null) { // String repositoryName = null; @@ -241,11 +240,11 @@ public boolean exec(NutsCommandLine cmdLine, Boolean autoSave, NutsSession sessi enableRepo(cmdLine, autoSave, session, true); return true; } else if (cmdLine.next("edit repo", "er") != null) { - String repoId = cmdLine.required().nextNonOption(commandLineFormat.createName("RepositoryName")).getString(); + String repoId = cmdLine.required().nextNonOption(NutsArgumentName.of("RepositoryName",session)).getString(); if (cmdLine.next("add repo", "ar") != null) { - String repositoryName = cmdLine.required().nextNonOption(commandLineFormat.createName("NewRepositoryName")).getString(); - String location = cmdLine.required().nextNonOption(commandLineFormat.createName("folder")).getString(); - String repoType = cmdLine.nextNonOption(commandLineFormat.createName("repository-type")).getString(); + String repositoryName = cmdLine.required().nextNonOption(NutsArgumentName.of("NewRepositoryName",session)).getString(); + String location = cmdLine.required().nextNonOption(NutsArgumentName.of("folder",session)).getString(); + String repoType = cmdLine.nextNonOption(NutsArgumentName.of("repository-type",session)).getString(); NutsRepository editedRepo = session.repos().getRepository(repoId); NutsRepository repo = editedRepo.config().addMirror( @@ -258,7 +257,7 @@ public boolean exec(NutsCommandLine cmdLine, Boolean autoSave, NutsSession sessi session.config().save(); } else if (cmdLine.next("remove repo", "rr") != null) { - String location = cmdLine.required().nextNonOption(commandLineFormat.createName("RepositoryName")).getString(); + String location = cmdLine.required().nextNonOption(NutsArgumentName.of("RepositoryName",session)).getString(); NutsRepository editedRepo = session.repos().getRepository(repoId); editedRepo.config().removeMirror(location); session.config().save(); @@ -290,11 +289,11 @@ public boolean exec(NutsCommandLine cmdLine, Boolean autoSave, NutsSession sessi } for (NutsRepository repository : linkRepositories) { m.addRow( - session.text().ofStyled(repository.getName(), NutsTextStyle.primary4()), + NutsTexts.of(session).ofStyled(repository.getName(), NutsTextStyle.primary4()), repository.config().isEnabled() - ? repository.isEnabled() ? session.text().ofStyled("ENABLED", NutsTextStyle.success()) - : session.text().ofStyled("", NutsTextStyle.error()) - : session.text().ofStyled("", NutsTextStyle.error()), + ? repository.isEnabled() ? NutsTexts.of(session).ofStyled("ENABLED", NutsTextStyle.success()) + : NutsTexts.of(session).ofStyled("", NutsTextStyle.error()) + : NutsTexts.of(session).ofStyled("", NutsTextStyle.error()), repository.getRepositoryType(), repository.config().getLocation(false) ); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/user/NutsSettingsUserSubCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/user/NutsSettingsUserSubCommand.java index 6239da34b..52ddcef40 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/user/NutsSettingsUserSubCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/subcommands/user/NutsSettingsUserSubCommand.java @@ -22,31 +22,29 @@ public boolean exec(NutsCommandLine cmdLine, Boolean autoSave, NutsSession sessi } public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, Boolean autoSave, NutsSession session) { -// NutsWorkspace ws = session.getWorkspace(); - NutsCommandLineManager commandLineFormat = session.commandLine(); if (cmdLine.next("add user", "au") != null) { NutsRepository repository = null; if (editedRepo != null) { repository = editedRepo; } else { if (cmdLine.next("--repo", "-r") != null) { - repository = session.repos().getRepository(cmdLine.required().nextNonOption(commandLineFormat.createName("RepositoryId")).getString()); + repository = session.repos().getRepository(cmdLine.required().nextNonOption(NutsArgumentName.of("RepositoryId",session)).getString()); } } if (repository == null) { - String user = cmdLine.required().nextNonOption(commandLineFormat.createName("Username")).getString(); - char[] password = cmdLine.nextNonOption(commandLineFormat.createName("Password")).getString().toCharArray(); + String user = cmdLine.required().nextNonOption(NutsArgumentName.of("Username",session)).getString(); + char[] password = cmdLine.nextNonOption(NutsArgumentName.of("Password",session)).getString().toCharArray(); if (cmdLine.isExecMode()) { session.security().addUser(user).setCredentials(password).run(); } } else { - String user = cmdLine.required().nextNonOption(commandLineFormat.createName("Username")).getString(); - char[] password = cmdLine.nextNonOption(commandLineFormat.createName("Password")).getString().toCharArray(); + String user = cmdLine.required().nextNonOption(NutsArgumentName.of("Username",session)).getString(); + char[] password = cmdLine.nextNonOption(NutsArgumentName.of("Password",session)).getString().toCharArray(); String mappedUser=null; char[] remotePassword=null; if(!cmdLine.isEmpty()) { - mappedUser = cmdLine.nextNonOption(commandLineFormat.createName("RemoteId")).getString(); - remotePassword = cmdLine.nextNonOption(commandLineFormat.createName("RemotePassword")).getString().toCharArray(); + mappedUser = cmdLine.nextNonOption(NutsArgumentName.of("RemoteId",session)).getString(); + remotePassword = cmdLine.nextNonOption(NutsArgumentName.of("RemotePassword",session)).getString().toCharArray(); } if (cmdLine.isExecMode()) { repository.security().addUser(user).setCredentials(password).setRemoteIdentity(mappedUser).setRemoteCredentials(remotePassword).run(); @@ -64,7 +62,7 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B repository = editedRepo; } else { if (cmdLine.next("--repo", "-r") != null) { - repository = session.repos().getRepository(cmdLine.required().nextNonOption(commandLineFormat.createName("repository")).getString()); + repository = session.repos().getRepository(cmdLine.required().nextNonOption(NutsArgumentName.of("repository",session)).getString()); } } if (cmdLine.isExecMode()) { @@ -92,7 +90,7 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B repository = editedRepo; } else { if (cmdLine.next("--repo", "-r") != null) { - repository = session.repos().getRepository(cmdLine.required().nextNonOption(commandLineFormat.createName("RepositoryId")).getString()); + repository = session.repos().getRepository(cmdLine.required().nextNonOption(NutsArgumentName.of("RepositoryId",session)).getString()); } } @@ -101,11 +99,11 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B char[] oldPassword = null; do { if (cmdLine.next("--user") != null) { - user = cmdLine.required().nextNonOption(commandLineFormat.createName("Username")).getString(); + user = cmdLine.required().nextNonOption(NutsArgumentName.of("Username",session)).getString(); } else if (cmdLine.next("--password") != null) { - password = cmdLine.required().nextNonOption(commandLineFormat.createName("Password")).getString().toCharArray(); + password = cmdLine.required().nextNonOption(NutsArgumentName.of("Password",session)).getString().toCharArray(); } else if (cmdLine.next("--old-password") != null) { - oldPassword = cmdLine.required().nextNonOption(commandLineFormat.createName("OldPassword")).getString().toCharArray(); + oldPassword = cmdLine.required().nextNonOption(NutsArgumentName.of("OldPassword",session)).getString().toCharArray(); } else { cmdLine.setCommandName("config password").unexpectedArgument(); } @@ -140,11 +138,11 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B repository = editedRepo; } else { if (cmdLine.next("--repo", "-r") != null) { - repository = session.repos().getRepository(cmdLine.required().nextNonOption(commandLineFormat.createName("RepositoryId")).getString()); + repository = session.repos().getRepository(cmdLine.required().nextNonOption(NutsArgumentName.of("RepositoryId",session)).getString()); } } - String user = cmdLine.required().nextNonOption(commandLineFormat.createName("Username")).getString(); + String user = cmdLine.required().nextNonOption(NutsArgumentName.of("Username",session)).getString(); if (cmdLine.isExecMode()) { NutsUser u = null; if (repository == null) { @@ -184,7 +182,7 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B } else { switch (lastOption) { case "--add-group": { - String a = cmdLine.required().nextNonOption(commandLineFormat.createName("Group")).getString(); + String a = cmdLine.required().nextNonOption(NutsArgumentName.of("Group",session)).getString(); if (cmdLine.isExecMode()) { if (repository != null) { repository.security().updateUser(user).addGroup(a).run(); @@ -195,7 +193,7 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B break; } case "--remove-group": { - String a = cmdLine.required().nextNonOption(commandLineFormat.createName("Group")).getString(); + String a = cmdLine.required().nextNonOption(NutsArgumentName.of("Group",session)).getString(); if (cmdLine.isExecMode()) { if (repository != null) { repository.security().updateUser(user).removeGroup(a).run(); @@ -206,7 +204,7 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B break; } case "--add-right": { - String a = cmdLine.required().nextNonOption(commandLineFormat.createName("Right")).getString(); + String a = cmdLine.required().nextNonOption(NutsArgumentName.of("Right",session)).getString(); if (cmdLine.isExecMode()) { if (repository != null) { repository.security().updateUser(user).addPermission(a).run(); @@ -217,7 +215,7 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B break; } case "--remove-right": { - String a = cmdLine.required().nextNonOption(commandLineFormat.createName("Right")).getString(); + String a = cmdLine.required().nextNonOption(NutsArgumentName.of("Right",session)).getString(); if (cmdLine.isExecMode()) { if (repository != null) { repository.security().updateUser(user).removePermission(a).run(); @@ -228,7 +226,7 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B break; } case "--mapped-user": { - String a = cmdLine.required().nextNonOption(commandLineFormat.createName("RemoteIdentity")).getString(); + String a = cmdLine.required().nextNonOption(NutsArgumentName.of("RemoteIdentity",session)).getString(); if (cmdLine.isExecMode()) { if (repository != null) { repository.security().updateUser(user).setRemoteIdentity(a).run(); @@ -239,8 +237,8 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B break; } case "--password": - char[] pwd = (cmdLine.required().nextNonOption(commandLineFormat.createName("password", "Password")).getString()).toCharArray(); - char[] old = (cmdLine.required().nextNonOption(commandLineFormat.createName("password", "OldPassword")).getString()).toCharArray(); + char[] pwd = (cmdLine.required().nextNonOption(NutsArgumentName.of("password", "Password",session)).getString()).toCharArray(); + char[] old = (cmdLine.required().nextNonOption(NutsArgumentName.of("password", "OldPassword",session)).getString()).toCharArray(); if (cmdLine.isExecMode()) { if (repository != null) { repository.security().updateUser(user).setCredentials(pwd).setOldCredentials(old).run(); @@ -268,7 +266,7 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B repository = editedRepo; } else { if (cmdLine.next("--repo", "-r") != null) { - repository = session.repos().getRepository(cmdLine.required().nextNonOption(commandLineFormat.createName("RepositoryId")).getString()); + repository = session.repos().getRepository(cmdLine.required().nextNonOption(NutsArgumentName.of("RepositoryId",session)).getString()); } } //unsecure-box @@ -298,7 +296,7 @@ public static boolean exec(NutsRepository editedRepo, NutsCommandLine cmdLine, B repository = editedRepo; } else { if (cmdLine.next("--repo", "-r") != null) { - repository = session.repos().getRepository(cmdLine.required().nextNonOption(commandLineFormat.createName("RepositoryId")).getString()); + repository = session.repos().getRepository(cmdLine.required().nextNonOption(NutsArgumentName.of("RepositoryId",session)).getString()); } } //secure-box diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/util/SettingsRepoUtils.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/util/SettingsRepoUtils.java index 1527f995d..64d5f1fea 100644 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/util/SettingsRepoUtils.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/settings/util/SettingsRepoUtils.java @@ -8,7 +8,7 @@ public static void showRepo(NutsApplicationContext context, NutsRepository repos String disabledString = enabled ? "" : " "; NutsPrintStream out = context.getSession().out(); out.print(prefix); - NutsTextManager factory = context.getSession().text(); + NutsTexts factory = NutsTexts.of(context.getSession()); if (enabled) { out.print(factory.ofStyled(repository.getName() + disabledString, NutsTextStyle.primary2())); } else { diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/undeploy/AbstractNutsUndeployCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/undeploy/AbstractNutsUndeployCommand.java index 2454abe35..13e89e246 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/undeploy/AbstractNutsUndeployCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/undeploy/AbstractNutsUndeployCommand.java @@ -35,7 +35,7 @@ public NutsUndeployCommand addId(NutsId id) { public NutsUndeployCommand addId(String id) { checkSession(); NutsSession ws = getSession(); - return addId(NutsBlankable.isBlank(id) ? null : ws.id().parser().setLenient(false).parse(id)); + return addId(NutsBlankable.isBlank(id) ? null : NutsId.of(id,ws)); } @Override @@ -45,7 +45,7 @@ public NutsUndeployCommand addIds(String... values) { if (values != null) { for (String s : values) { if (!NutsBlankable.isBlank(s)) { - ids.add(ws.id().parser().setLenient(false).parse(s)); + ids.add(NutsId.of(s,ws)); } } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/undeploy/DefaultNutsUndeployCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/undeploy/DefaultNutsUndeployCommand.java index 5ecce8be1..00c2c6118 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/undeploy/DefaultNutsUndeployCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/undeploy/DefaultNutsUndeployCommand.java @@ -29,7 +29,7 @@ public NutsUndeployCommand run() { .setFetchStrategy(isOffline() ? NutsFetchStrategy.OFFLINE : NutsFetchStrategy.ONLINE) ) .addIds(id) - .addRepositoryFilter(session.filters().repository().byName(getRepository())) + .addRepositoryFilter(NutsRepositoryFilters.of(session).byName(getRepository())) //skip 'installed' repository .setRepositoryFilter( session.repos().filter().byName(DefaultNutsInstalledRepository.INSTALLED_REPO_UUID).neg() diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/uninstall/AbstractNutsUninstallCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/uninstall/AbstractNutsUninstallCommand.java index 18cf028c5..dafb2a388 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/uninstall/AbstractNutsUninstallCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/uninstall/AbstractNutsUninstallCommand.java @@ -30,7 +30,7 @@ public AbstractNutsUninstallCommand(NutsWorkspace ws) { public NutsUninstallCommand addId(String id) { checkSession(); NutsSession ws = getSession(); - return addId(id == null ? null : ws.id().parser().parse(id)); + return addId(id == null ? null : NutsId.of(id,ws)); } @Override @@ -72,7 +72,7 @@ public NutsUninstallCommand removeId(NutsId id) { public NutsUninstallCommand removeId(String id) { checkSession(); NutsSession ws = getSession(); - return removeId(ws.id().parser().parse(id)); + return removeId(NutsId.of(id,ws)); } @Override diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/uninstall/DefaultNutsUninstallCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/uninstall/DefaultNutsUninstallCommand.java index 6f3c82426..fabca4cd9 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/uninstall/DefaultNutsUninstallCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/uninstall/DefaultNutsUninstallCommand.java @@ -46,7 +46,7 @@ public NutsUninstallCommand run() { } for (NutsId id : nutsIds) { List resultDefinitions = session.search().addId(id) - .setInstallStatus(session.filters().installStatus().byInstalled(true)) + .setInstallStatus(NutsInstallStatusFilters.of(session).byInstalled(true)) .setSession(session.copy().setTransitive(false)) .setOptional(false).setEffective(true) .setContent(true)//include content so that we can remove it by calling executor @@ -58,7 +58,7 @@ public NutsUninstallCommand run() { defs.addAll(resultDefinitions); } - NutsMemoryPrintStream mout = session.io().createMemoryPrintStream(); + NutsMemoryPrintStream mout = NutsMemoryPrintStream.of(session); mout.println("should we proceed?"); NutsMessage cancelMessage = NutsMessage.cstyle("removal cancelled : %s", defs.stream() .map(NutsDefinition::getId) @@ -113,7 +113,7 @@ public NutsUninstallCommand run() { wcfg.getModel().fireConfigurationChanged("extensions", session, ConfigEventType.BOOT); } if (getSession().isPlainTrace()) { - out.printf("%s uninstalled %s%n", id, session.text().ofStyled( + out.printf("%s uninstalled %s%n", id, NutsTexts.of(session).ofStyled( "successfully", NutsTextStyle.success() )); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/update/AbstractNutsUpdateCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/update/AbstractNutsUpdateCommand.java index 5949516fc..3a6198666 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/update/AbstractNutsUpdateCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/update/AbstractNutsUpdateCommand.java @@ -47,7 +47,7 @@ public NutsId[] getIds() { public NutsUpdateCommand addId(String id) { checkSession(); NutsSession ws = getSession(); - return addId(id == null ? null : ws.id().parser().parse(id)); + return addId(id == null ? null : NutsId.of(id,ws)); } @Override @@ -89,7 +89,7 @@ public NutsUpdateCommand removeId(NutsId id) { public NutsUpdateCommand removeId(String id) { checkSession(); NutsSession ws = getSession(); - return removeId(ws.id().parser().parse(id)); + return removeId(NutsId.of(id,ws)); } @Override @@ -368,7 +368,7 @@ public NutsUpdateCommand addLockedId(String id) { checkSession(); NutsSession ws = getSession(); if (!NutsBlankable.isBlank(id)) { - lockedIds.add(ws.id().parser().setLenient(false).parse(id)); + lockedIds.add(NutsId.of(id,ws)); } return this; } @@ -477,7 +477,7 @@ public boolean configureFirst(NutsCommandLine cmdLine) { case "--to-version": { String val = cmdLine.nextString().getValue().getString(); if (enabled) { - this.setApiVersion(getSession().version().parse(val)); + this.setApiVersion(NutsVersion.of(val,getSession())); } return true; } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/update/DefaultNutsUpdateCommand.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/update/DefaultNutsUpdateCommand.java index 1e69991a4..f60622c58 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/update/DefaultNutsUpdateCommand.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/update/DefaultNutsUpdateCommand.java @@ -112,7 +112,7 @@ public NutsUpdateCommand checkUpdates() { bootVersion = this.getApiVersion(); } if (this.isApi() || !(this.getApiVersion() == null || this.getApiVersion().isBlank())) { - apiUpdate = checkCoreUpdate(ws.id().parser().parse(NutsConstants.Ids.NUTS_API), this.getApiVersion(), session, Type.API, now); + apiUpdate = checkCoreUpdate(NutsId.of(NutsConstants.Ids.NUTS_API,ws), this.getApiVersion(), session, Type.API, now); if (apiUpdate.isUpdateAvailable()) { bootVersion = apiUpdate.getAvailable().getId().getVersion(); allUpdates.put(NutsConstants.Ids.NUTS_API, apiUpdate); @@ -124,7 +124,7 @@ public NutsUpdateCommand checkUpdates() { NutsUpdateResult runtimeUpdate = null; if (this.isRuntime()) { if (dws.requiresRuntimeExtension(session)) { - runtimeUpdate = checkCoreUpdate(ws.id().parser().parse(ws.getWorkspace().getRuntimeId().getShortName()), + runtimeUpdate = checkCoreUpdate(NutsId.of(ws.getWorkspace().getRuntimeId().getShortName(),ws), apiUpdate != null && apiUpdate.getAvailable().getId() != null ? apiUpdate.getAvailable().getId().getVersion() : bootVersion, session, Type.RUNTIME, now); if (runtimeUpdate.isUpdateAvailable()) { @@ -161,7 +161,7 @@ public NutsUpdateCommand checkUpdates() { NutsId[] lockedIds = this.getLockedIds(); if (lockedIds.length > 0) { for (NutsId d : new HashSet<>(Arrays.asList(lockedIds))) { - NutsDependency dd = ws.dependency().parser().parseDependency(d.toString()); + NutsDependency dd = NutsDependencyParser.of(ws).parse(d.toString()); if (regularUpdates.containsKey(dd.getSimpleName())) { NutsUpdateResult updated = regularUpdates.get(dd.getSimpleName()); //FIX ME @@ -225,7 +225,7 @@ private Set getRegularIds() { HashSet baseRegulars = new HashSet<>(ids); if (isInstalled()) { baseRegulars.addAll(getSession().search().setSession(getSession()) - .setInstallStatus(getSession().filters().installStatus().byInstalled(true)) + .setInstallStatus(NutsInstallStatusFilters.of(getSession()).byInstalled(true)) .getResultIds().stream().map(NutsId::getShortId).collect(Collectors.toList())); // This bloc is to handle packages that were installed by their jar/content but was removed for any reason! NutsWorkspaceExt dws = NutsWorkspaceExt.of(ws); @@ -263,7 +263,7 @@ public NutsUpdateCommand checkFixes() { @Override public FixAction apply(NutsInstallInformation nutsInstallInformation) { NutsId id = getSession().search().setInstallStatus( - getSession().filters().installStatus().byInstalled(true) + NutsInstallStatusFilters.of(session).byInstalled(true) ).addId(nutsInstallInformation.getId()).getResultIds().first(); if (id == null) { return new FixAction(nutsInstallInformation.getId(), "MissingInstallation") { @@ -296,10 +296,10 @@ protected void traceUpdates(NutsWorkspaceUpdateResult result) { NutsUpdateResult[] updates = result.getAllUpdates(); if (updates.length == 0) { out.resetLine().printf("all packages are %s. You are running latest version%s.%n", - session.text().ofStyled("up-to-date", NutsTextStyle.success()), + NutsTexts.of(session).ofStyled("up-to-date", NutsTextStyle.success()), result.getAllResults().length > 1 ? "s" : ""); } else { - out.resetLine().printf("workspace has %s package%s to update.%n", session.text().ofStyled("" + updates.length, NutsTextStyle.primary1()), + out.resetLine().printf("workspace has %s package%s to update.%n", NutsTexts.of(session).ofStyled("" + updates.length, NutsTextStyle.primary1()), (updates.length > 1 ? "s" : "")); int widthCol1 = 2; int widthCol2 = 2; @@ -307,7 +307,7 @@ protected void traceUpdates(NutsWorkspaceUpdateResult result) { widthCol1 = Math.max(widthCol1, update.getAvailable().getId().getShortName().length()); widthCol2 = Math.max(widthCol2, update.getLocal().getId().getVersion().toString().length()); } - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); for (NutsUpdateResult update : updates) { if (update.isUpdateVersionAvailable()) { out.printf("%s : %s => %s%n", @@ -362,7 +362,7 @@ protected NutsUpdateResult checkRegularUpdate(NutsId id, Type type, NutsVersion r.setId(id.getShortId()); boolean shouldUpdateDefault = false; NutsDefinition d0 = session.search().addId(id).setSession(session) - .setInstallStatus(session.filters().installStatus().byDeployed(true)) + .setInstallStatus(NutsInstallStatusFilters.of(session).byDeployed(true)) .setOptional(false).setFailFast(false)//.setDefaultVersions(true) .sort(DEFAULT_THEN_LATEST_VERSION_FIRST) .getResultDefinitions().first(); @@ -395,7 +395,7 @@ protected NutsUpdateResult checkRegularUpdate(NutsId id, Type type, NutsVersion .setFailFast(false) .setLatest(true) .addLockedIds(getLockedIds()) - .addRepositoryFilter(session.filters().repository().installedRepo().neg()) + .addRepositoryFilter(NutsRepositoryFilters.of(session).installedRepo().neg()) .setDependencies(true) .setOptional(isOptional() ? null : false); if (type == Type.EXTENSION) { @@ -467,7 +467,7 @@ private void applyResult(NutsWorkspaceUpdateResult result) { boolean requireSave = false; NutsSession validWorkspaceSession = getSession(); final NutsPrintStream out = validWorkspaceSession.out(); - boolean accept = getSession().term().getTerminal().ask() + boolean accept = getSession().config().getDefaultTerminal().ask() .resetLine() .forBoolean("would you like to apply updates?").setDefaultValue(true) .setSession(validWorkspaceSession).getValue(); @@ -540,7 +540,7 @@ private void traceSingleUpdate(NutsUpdateResult r) { // final String simpleName = d0 != null ? d0.getId().getShortName() : d1 != null ? d1.getId().getShortName() : id.getShortName(); final NutsId simpleId = d0 != null ? d0.getId().getShortId() : d1 != null ? d1.getId().getShortId() : id.getShortId(); final NutsPrintStream out = getSession().out(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (r.isUpdateApplied()) { if (r.isUpdateForced()) { if (d0 == null) { @@ -596,7 +596,7 @@ public NutsUpdateResult checkCoreUpdate(NutsId id, NutsVersion bootApiVersion, N } NutsVersion v = bootApiVersion; if (v == null || v.isBlank()) { - v = getSession().version().parse(NutsConstants.Versions.LATEST); + v = NutsVersion.of(NutsConstants.Versions.LATEST,getSession()); } try { oldFile = fetch0().setId(oldId).setSession(session.copy().setFetchStrategy(NutsFetchStrategy.ONLINE)).getResultDefinition(); diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/version/DefaultNutsVersionInternalExecutable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/version/DefaultNutsVersionInternalExecutable.java index 8717e38d4..e64eae749 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/version/DefaultNutsVersionInternalExecutable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/version/DefaultNutsVersionInternalExecutable.java @@ -30,7 +30,7 @@ public void execute() { // } NutsWorkspace ws = getSession().getWorkspace(); NutsPrintStream out = getSession().out(); - getSession().version().formatter().configure(false, args).println(out); + NutsVersionFormat.of(getSession()).configure(false, args).println(out); } } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/welcome/DefaultNutsWelcomeInternalExecutable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/welcome/DefaultNutsWelcomeInternalExecutable.java index 681bc0492..6cec02a01 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/welcome/DefaultNutsWelcomeInternalExecutable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/welcome/DefaultNutsWelcomeInternalExecutable.java @@ -29,7 +29,7 @@ public void execute() { return; } NutsSession session = getSession(); - NutsCommandLine commandLine = session.commandLine().create(args); + NutsCommandLine commandLine = NutsCommandLine.of(args,session); while (commandLine.hasNext()) { NutsArgument a = commandLine.peek(); if (a.isOption()) { @@ -53,17 +53,17 @@ public void execute() { } else { Map welcome = new LinkedHashMap<>(); welcome.put("message", "Welcome to nuts. Yeah, it is working..."); - welcome.put("name", session.text().ofStyled("nuts", NutsTextStyle.primary(1))); + welcome.put("name", NutsTexts.of(session).ofStyled("nuts", NutsTextStyle.primary(1))); welcome.put("long-name", "Network Updatable Things Services"); welcome.put("description", "The Free and Open Source Package Manager for Java (TM) and other Things ..."); - welcome.put("url", session.io().path("http://github.com/thevpc/nuts")); + welcome.put("url", NutsPath.of("http://github.com/thevpc/nuts",session)); welcome.put("author", "thevpc"); welcome.put("api-id", session.getWorkspace().getApiId().builder().setVersion("").build()); welcome.put("api-version", session.getWorkspace().getApiVersion()); welcome.put("runtime-id", session.getWorkspace().getRuntimeId().builder().setVersion("").build()); welcome.put("runtime-version", session.getWorkspace().getRuntimeId().getVersion()); - welcome.put("workspace", session.io().path(session.locations().getWorkspaceLocation())); - welcome.put("hash-name", session.io().path(session.getWorkspace().getHashName())); + welcome.put("workspace", session.locations().getWorkspaceLocation()); + welcome.put("hash-name", NutsPath.of(session.getWorkspace().getHashName(),session)); if (session.isPlainOut()) { session = session.copy().setOutputFormat(NutsContentType.PROPS); } diff --git a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/which/DefaultNutsWhichInternalExecutable.java b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/which/DefaultNutsWhichInternalExecutable.java index ba6fd5c5d..214dfeeef 100755 --- a/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/which/DefaultNutsWhichInternalExecutable.java +++ b/core/nuts-runtime/src/main/java/net/thevpc/nuts/runtime/standalone/wscommands/which/DefaultNutsWhichInternalExecutable.java @@ -33,7 +33,7 @@ public void execute() { } List commands = new ArrayList(); // NutsWorkspace ws = getSession().getWorkspace(); - NutsCommandLine commandLine = getSession().commandLine().create(args); + NutsCommandLine commandLine = NutsCommandLine.of(args,getSession()); while (commandLine.hasNext()) { NutsArgument a = commandLine.peek(); if (a.isOption()) { @@ -57,13 +57,13 @@ public void execute() { if (commands.isEmpty()) { throw new NutsIllegalArgumentException(getSession(), NutsMessage.cstyle("which: missing commands")); } - NutsTextManager factory = getSession().text(); + NutsTexts factory = NutsTexts.of(getSession()); for (String arg : this.args) { NutsPrintStream out = getSession().out(); + NutsElements elem = NutsElements.of(getSession()); try { NutsExecutableInformation p = execCommand.copy().setSession(getSession()).clearCommand().configure(false, arg).which(); - NutsElementFormat e = getSession().elem(); -// boolean showDesc = false; + // boolean showDesc = false; switch (p.getType()) { case SYSTEM: { if (getSession().isPlainOut()) { @@ -74,7 +74,7 @@ public void execute() { } else { getSession().out().printlnf( - e.forObject() + elem.forObject() .set("name", arg) .set("type", "system-command") .set("description", p.getDescription()) @@ -89,11 +89,11 @@ public void execute() { factory.ofStyled(arg, NutsTextStyle.primary4()), factory.ofStyled("nuts alias", NutsTextStyle.primary6()), p.getId(), - getSession().commandLine().create(getSession().commands().findCommand(p.getName()).getCommand()) + NutsCommandLine.of(getSession().commands().findCommand(p.getName()).getCommand(),getSession()) ); } else { getSession().out().printlnf( - e.forObject() + elem.forObject() .set("name", arg) .set("type", "alias") .set("description", p.getDescription()) @@ -105,7 +105,7 @@ public void execute() { } case ARTIFACT: { if (p.getId() == null) { - NutsId nid = getSession().id().parser().setLenient(true).parse(arg); + NutsId nid = NutsId.of(arg,getSession()); if (nid != null) { throw new NutsNotFoundException(getSession(), nid); } else { @@ -120,7 +120,7 @@ public void execute() { ); } else { getSession().out().printlnf( - e.forObject() + elem.forObject() .set("name", arg) .set("type", "artifact") .set("id", p.getId().toString()) @@ -138,7 +138,7 @@ public void execute() { ); } else { getSession().out().printlnf( - e.forObject() + elem.forObject() .set("name", arg) .set("type", "internal-command") .set("description", p.getDescription()) @@ -155,7 +155,7 @@ public void execute() { ); } else { getSession().out().printlnf( - e.forObject() + elem.forObject() .set("name", arg) .set("type", "unknown-command") .build() @@ -171,7 +171,7 @@ public void execute() { if (getSession().isPlainOut()) { out.printf("%s : %s%n", factory.ofStyled(arg, NutsTextStyle.primary4()), factory.ofStyled("not found", NutsTextStyle.error())); } else { - NutsElementFormat e = getSession().elem(); + NutsElements e = elem; getSession().eout().add( e.forObject() .set("name", arg) diff --git a/core/nuts-runtime/src/main/resources/META-INF/services/net.thevpc.nuts.spi.NutsComponent b/core/nuts-runtime/src/main/resources/META-INF/services/net.thevpc.nuts.spi.NutsComponent index 7db5cb347..7413d6003 100755 --- a/core/nuts-runtime/src/main/resources/META-INF/services/net.thevpc.nuts.spi.NutsComponent +++ b/core/nuts-runtime/src/main/resources/META-INF/services/net.thevpc.nuts.spi.NutsComponent @@ -27,6 +27,75 @@ net.thevpc.nuts.runtime.standalone.executors.ProcessExecutorComponent net.thevpc.nuts.runtime.standalone.bridges.maven.MavenRepositoryFactoryComponent net.thevpc.nuts.runtime.standalone.config.DefaultNutsIndexStoreFactory net.thevpc.nuts.runtime.standalone.security.DefaultNutsAuthenticationAgent +net.thevpc.nuts.runtime.core.log.DefaultNutsLogManager + +##################### Utilities + +net.thevpc.nuts.runtime.core.eval.DefaultNutsExpr +net.thevpc.nuts.runtime.standalone.DefaultNutsStreams +net.thevpc.nuts.runtime.standalone.DefaultNutsVals +net.thevpc.nuts.runtime.standalone.DefaultNutsGlob +net.thevpc.nuts.runtime.standalone.io.DefaultNutsPaths +net.thevpc.nuts.runtime.standalone.io.DefaultNutsInputStreams +net.thevpc.nuts.runtime.standalone.io.DefaultNutsPrintStreams +net.thevpc.nuts.runtime.core.app.NutsCommandHistoryImpl +net.thevpc.nuts.runtime.core.app.DefaultNutsCommandLines +net.thevpc.nuts.runtime.core.app.DefaultDefaultNutsApplicationContexts + +net.thevpc.nuts.runtime.core.app.DefaultNutsCommandLineFormat +net.thevpc.nuts.runtime.core.format.DefaultNutsExecCommandFormat +net.thevpc.nuts.runtime.core.format.DefaultNutsObjectFormat +net.thevpc.nuts.runtime.core.format.DefaultNutsInfoFormat +net.thevpc.nuts.runtime.core.format.DefaultNutsVersionFormat +net.thevpc.nuts.runtime.core.format.props.DefaultNutsPropertiesFormat +net.thevpc.nuts.runtime.core.format.table.DefaultTableFormat +net.thevpc.nuts.runtime.core.format.tree.DefaultNutsTreeFormat + + +net.thevpc.nuts.runtime.standalone.io.DefaultNutsExecutionEntries +net.thevpc.nuts.runtime.standalone.io.DefaultNutsHash +net.thevpc.nuts.runtime.standalone.io.DefaultNutsInputStreamMonitor +net.thevpc.nuts.runtime.standalone.io.DefaultNutsLocks +net.thevpc.nuts.runtime.standalone.io.DefaultNutsTerminals +net.thevpc.nuts.runtime.standalone.io.DefaultNutsTmp +net.thevpc.nuts.runtime.standalone.io.DefaultNutsRm +net.thevpc.nuts.runtime.standalone.io.DefaultNutsCp +net.thevpc.nuts.runtime.standalone.io.DefaultNutsPs +net.thevpc.nuts.runtime.standalone.io.DefaultNutsCompress +net.thevpc.nuts.runtime.standalone.io.DefaultNutsUncompress +net.thevpc.nuts.runtime.standalone.manager.DefaultNutsIdResolver + +net.thevpc.nuts.runtime.core.parser.DefaultNutsIdParser +net.thevpc.nuts.runtime.core.parser.DefaultNutsDescriptorParser +net.thevpc.nuts.runtime.core.parser.DefaultNutsDependencyParser +net.thevpc.nuts.runtime.core.parser.DefaultNutsVersionParser + +net.thevpc.nuts.runtime.core.model.DefaultNutsIdBuilder +net.thevpc.nuts.runtime.core.model.DefaultNutsDescriptorBuilder +net.thevpc.nuts.runtime.core.model.DefaultNutsEnvConditionBuilder +net.thevpc.nuts.runtime.core.model.DefaultNutsDescriptorPropertyBuilder +net.thevpc.nuts.runtime.core.model.DefaultNutsDependencyBuilder +net.thevpc.nuts.runtime.core.model.DefaultNutsArtifactCallBuilder + +net.thevpc.nuts.runtime.core.format.DefaultNutsIdFormat +net.thevpc.nuts.runtime.core.format.DefaultNutsDescriptorFormat +net.thevpc.nuts.runtime.core.format.DefaultNutsVersionFormat +net.thevpc.nuts.runtime.core.format.DefaultNutsDependencyFormat + +net.thevpc.nuts.runtime.core.filters.id.InternalNutsIdFilters +net.thevpc.nuts.runtime.core.filters.version.InternalNutsVersionFilters +net.thevpc.nuts.runtime.core.filters.dependency.InternalNutsDependencyFilters +net.thevpc.nuts.runtime.core.filters.descriptor.InternalNutsDescriptorFilters +net.thevpc.nuts.runtime.core.filters.installstatus.InternalNutsInstallStatusFilters +net.thevpc.nuts.runtime.core.filters.repository.InternalNutsRepositoryFilters + + +net.thevpc.nuts.runtime.core.filters.DefaultNutsFilters + +net.thevpc.nuts.runtime.core.format.elem.DefaultNutsElements +net.thevpc.nuts.runtime.core.format.text.DefaultNutsTexts + +net.thevpc.nuts.runtime.standalone.solvers.DefaultNutsDependencySolvers ##################### Settings Subcommands! diff --git a/core/nuts-runtime/src/main/resources/net/thevpc/nuts/runtime/highlighter-mappings.ini b/core/nuts-runtime/src/main/resources/net/thevpc/nuts/runtime/highlighter-mappings.ini index 1a7d9c1ee..238c9e353 100644 --- a/core/nuts-runtime/src/main/resources/net/thevpc/nuts/runtime/highlighter-mappings.ini +++ b/core/nuts-runtime/src/main/resources/net/thevpc/nuts/runtime/highlighter-mappings.ini @@ -1,17 +1,21 @@ [java] jav, java +text/x-java [c] c, h, c++, cpp +text/x-c, text/x-c++ [hadra] hadra, hadra-lang, hl [xml] xml, xsl +text/xml, text/html [sh] ksh, zsh, csh, bash +text/x-shellscript [fish] fish @@ -19,8 +23,12 @@ fish [cmd] cmd, bat, powsershell +text/x-msdos-batch + [json] json +application/json [text] -text, plain \ No newline at end of file +text, plain +text/plain \ No newline at end of file diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsApplicationContext.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsApplicationContext.java index f9c876960..6211d0139 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsApplicationContext.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsApplicationContext.java @@ -32,16 +32,29 @@ * execution mode, workspace, etc. * * @author thevpc - * @since 0.5.5 * @app.category Application + * @since 0.5.5 */ public interface NutsApplicationContext extends NutsCommandLineConfigurable { - /** * string that prefix each auto complete candidate */ String AUTO_COMPLETE_CANDIDATE_PREFIX = "```error Candidate```: "; + /** + * create a new instance of {@link NutsApplicationContext} + * + * @param session session context session. If null will consider {@code getSession()} that should not be null as well. + * @param args application arguments + * @param startTimeMillis application start time + * @param appClass application class + * @param storeId application store id or null + * @return new instance of {@link NutsApplicationContext} + */ + static NutsApplicationContext of(String[] args, long startTimeMillis, Class appClass, String storeId, NutsSession session) { + return NutsApplicationContexts.of(session).create(args, startTimeMillis, appClass, storeId); + } + /** * application execution mode * @@ -70,7 +83,7 @@ public interface NutsApplicationContext extends NutsCommandLineConfigurable { * to help return a more specific return type; * * @param skipUnsupported when true, all unsupported options are skipped - * @param args argument to configure with + * @param args argument to configure with * @return {@code this} instance */ @Override @@ -270,7 +283,7 @@ public interface NutsApplicationContext extends NutsCommandLineConfigurable { * commandLineProcessor.exec(); * } * - * + *

* This as an example of its usage *

      *     applicationContext.processCommandLine(new NutsCommandLineProcessor() {
@@ -335,6 +348,7 @@ public interface NutsApplicationContext extends NutsCommandLineConfigurable {
 
     /**
      * application store folder path for the given {@code location}
+     *
      * @param location location type
      * @return application store folder path for the given {@code location}
      */
@@ -342,6 +356,7 @@ public interface NutsApplicationContext extends NutsCommandLineConfigurable {
 
     /**
      * return true if {@code getAutoComplete()==null }
+     *
      * @return true if {@code getAutoComplete()==null }
      */
     boolean isExecMode();
diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceAppsManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsApplicationContexts.java
similarity index 68%
rename from core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceAppsManager.java
rename to core/nuts/src/main/java/net/thevpc/nuts/NutsApplicationContexts.java
index 13df19f7c..b4e9afc7e 100644
--- a/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceAppsManager.java
+++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsApplicationContexts.java
@@ -26,30 +26,35 @@
  */
 package net.thevpc.nuts;
 
+
+import net.thevpc.nuts.boot.NutsApiUtils;
+import net.thevpc.nuts.spi.NutsComponent;
+import net.thevpc.nuts.spi.NutsComponentScope;
+import net.thevpc.nuts.spi.NutsComponentScopeType;
+
 /**
+ * Application context that store all relevant information about application
+ * execution mode, workspace, etc.
+ *
+ * @author thevpc
  * @app.category Application
+ * @since 0.5.5
  */
-public interface NutsWorkspaceAppsManager {
+@NutsComponentScope(NutsComponentScopeType.WORKSPACE)
+public interface NutsApplicationContexts extends NutsComponent {
+    static NutsApplicationContexts of(NutsSession session) {
+        NutsApiUtils.checkSession(session);
+        return session.extensions().createSupported(NutsApplicationContexts.class, true, null);
+    }
 
     /**
      * create a new instance of {@link NutsApplicationContext}
      *
-     * @param session session context session. If null will consider {@code getSession()} that should not be null as well.
      * @param args            application arguments
      * @param startTimeMillis application start time
      * @param appClass        application class
      * @param storeId         application store id or null
      * @return new instance of {@link NutsApplicationContext}
      */
-    NutsApplicationContext createApplicationContext(NutsSession session, String[] args, long startTimeMillis, Class appClass, String storeId);
-
-    /**
-     * create a new exec entries action
-     * @return exec entries action
-     */
-    NutsExecutionEntryAction execEntries();
-
-    NutsSession getSession();
-
-    NutsWorkspaceAppsManager setSession(NutsSession session);
+    NutsApplicationContext create(String[] args, long startTimeMillis, Class appClass, String storeId);
 }
diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsApplications.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsApplications.java
index 7993b1026..2f7a4b291 100644
--- a/core/nuts/src/main/java/net/thevpc/nuts/NutsApplications.java
+++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsApplications.java
@@ -129,7 +129,7 @@ public static NutsApplicationContext createApplicationContext(NutsApplication ap
         NutsApplicationContext applicationContext = null;
         applicationContext = applicationInstance.createApplicationContext(session, args, startTimeMillis);
         if (applicationContext == null) {
-            applicationContext = session.apps().createApplicationContext(session, args, startTimeMillis, applicationInstance.getClass(), null);
+            applicationContext = NutsApplicationContext.of(args, startTimeMillis, applicationInstance.getClass(), null,session);
         }
 
         //copy inter-process parameters only
@@ -141,7 +141,7 @@ public static NutsApplicationContext createApplicationContext(NutsApplication ap
         ctxSession.setIndexed(session.isIndexed());
         ctxSession.setCached(session.isCached());
         ctxSession.setTransitive(session.isTransitive());
-        ctxSession.setTerminal(ctxSession.term().createTerminal(session.getTerminal()));
+        ctxSession.setTerminal(NutsSessionTerminal.of(session.getTerminal(),ctxSession));
         return applicationContext;
     }
 
@@ -156,11 +156,11 @@ public static void runApplication(NutsApplication applicationInstance, String[]
         NutsApplicationContext applicationContext = createApplicationContext(applicationInstance, args, session);
         session = applicationContext.getSession();
         boolean inherited = session.boot().getBootOptions().isInherited();
-        session.log().of(NutsApplications.class).with().level(Level.FINE).verb(NutsLogVerb.START)
+        NutsLogger.of(NutsApplications.class,session).with().level(Level.FINE).verb(NutsLogVerb.START)
                 .log(
                         NutsMessage.jstyle(
                         "running application {0}: {1} {2}", inherited ? "(inherited)" : "",
-                        applicationInstance.getClass().getName(), session.commandLine().create(args)
+                        applicationInstance.getClass().getName(), NutsCommandLine.of(args,session)
                         )
                 );
         switch (applicationContext.getMode()) {
diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsArgument.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsArgument.java
index 409796477..0e5772cc0 100644
--- a/core/nuts/src/main/java/net/thevpc/nuts/NutsArgument.java
+++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsArgument.java
@@ -46,7 +46,7 @@ public interface NutsArgument {
      */
     static NutsArgument of(String value, NutsSession session) {
         NutsApiUtils.checkSession(session);
-        return session.commandLine().createArgument(value);
+        return NutsCommandLines.of(session).createArgument(value);
     }
 
     /**
diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsArgumentCandidate.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsArgumentCandidate.java
index cecd51238..6e2da7ee7 100644
--- a/core/nuts/src/main/java/net/thevpc/nuts/NutsArgumentCandidate.java
+++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsArgumentCandidate.java
@@ -29,20 +29,32 @@
 import net.thevpc.nuts.boot.NutsApiUtils;
 
 import java.io.Serializable;
+import java.util.Objects;
 
 /**
  * Argument Candidate used in Auto Complete.
- *
+ * 

* Created by vpc on 3/7/17. * - * @since 0.5.5 * @app.category Command Line + * @since 0.5.5 */ -public interface NutsArgumentCandidate extends Serializable { +public class NutsArgumentCandidate implements Serializable { + + private final String value; + private final String display; + + /** + * @param value value + */ + public NutsArgumentCandidate(String value) { + this.value = value; + this.display = value; + } - static NutsArgumentCandidate of(String value, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.commandLine().createCandidate(value).build(); + public NutsArgumentCandidate(String value, String display) { + this.value = value; + this.display = display; } /** @@ -50,12 +62,34 @@ static NutsArgumentCandidate of(String value, NutsSession session) { * * @return argument value */ - String getValue(); + public String getValue() { + return value; + } /** * human display * * @return human display */ - String getDisplay(); + public String getDisplay() { + return display; + } + + @Override + public int hashCode() { + return Objects.hash(value, display); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + NutsArgumentCandidate that = (NutsArgumentCandidate) o; + return Objects.equals(value, that.value) && Objects.equals(display, that.display); + } + + @Override + public String toString() { + return String.valueOf(value); + } } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsArgumentName.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsArgumentName.java index c12d346e7..1894e69dd 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsArgumentName.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsArgumentName.java @@ -37,6 +37,12 @@ */ public interface NutsArgumentName extends Serializable { + static NutsArgumentName of(String type, String label,NutsSession session){ + return NutsCommandLines.of(session).createName(type,label); + } + static NutsArgumentName of(String type,NutsSession session){ + return NutsCommandLines.of(session).createName(type); + } /** * argument name * diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsArrayElementBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsArrayElementBuilder.java index e377b1298..0253a4a4d 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsArrayElementBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsArrayElementBuilder.java @@ -39,7 +39,7 @@ public interface NutsArrayElementBuilder extends NutsElementBuilder { static NutsArrayElementBuilder of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.elem().forArray(); + return NutsElements.of(session).forArray(); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsArtifactCallBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsArtifactCallBuilder.java index 96954fc9a..556ff8fbb 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsArtifactCallBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsArtifactCallBuilder.java @@ -26,6 +26,7 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; import java.io.Serializable; import java.util.Map; @@ -35,13 +36,13 @@ * as NutsDescriptor executor or installer. * To get an instance of NutsArtifactCallBuilder you can use {@code workspace.descriptor().callBuilder()} * - * @since 0.5.4 * @app.category Base + * @since 0.5.4 */ -public interface NutsArtifactCallBuilder extends Serializable { +public interface NutsArtifactCallBuilder extends Serializable, NutsComponent { static NutsArtifactCallBuilder of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.descriptor().callBuilder(); + return session.extensions().createSupported(NutsArtifactCallBuilder.class, true, null); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsBootManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsBootManager.java index 32babf8eb..4a470e929 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsBootManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsBootManager.java @@ -54,4 +54,6 @@ public interface NutsBootManager { long getCreationTimeMillis(); + NutsClassLoaderNode getBootRuntimeClassLoaderNode(); + NutsClassLoaderNode[] getBootExtensionClassLoaderNode(); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsClassLoaderNode.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsClassLoaderNode.java index b63e3f1ce..17445bc2e 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsClassLoaderNode.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsClassLoaderNode.java @@ -2,6 +2,7 @@ import java.net.URL; import java.util.Arrays; +import java.util.Objects; /** * @app.category Internal @@ -9,17 +10,23 @@ public class NutsClassLoaderNode { private final String id; + private final boolean includedInClasspath; private final URL url; private final boolean enabled; private final NutsClassLoaderNode[] dependencies; - public NutsClassLoaderNode(String id, URL url, boolean enabled, NutsClassLoaderNode... dependencies) { + public NutsClassLoaderNode(String id, URL url, boolean enabled, boolean includedInClasspath, NutsClassLoaderNode... dependencies) { this.id = id; this.url = url; this.enabled = enabled; + this.includedInClasspath = includedInClasspath; this.dependencies = Arrays.copyOf(dependencies, dependencies.length); } + public boolean isIncludedInClasspath() { + return includedInClasspath; + } + public boolean isEnabled() { return enabled; } @@ -38,7 +45,27 @@ public NutsClassLoaderNode[] getDependencies() { @Override public String toString() { - return "NutsClassLoaderNode{" + "id=" + id + ", url=" + url + ", enabled=" + enabled + ", dependencies=" + dependencies + '}'; + return "NutsClassLoaderNode{" + + "id='" + id + '\'' + + ", loaded=" + includedInClasspath + + ", url=" + url + + ", enabled=" + enabled + + ", dependencies=" + Arrays.toString(dependencies) + + '}'; } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + NutsClassLoaderNode that = (NutsClassLoaderNode) o; + return includedInClasspath == that.includedInClasspath && enabled == that.enabled && Objects.equals(id, that.id) && Objects.equals(url, that.url) && Arrays.equals(dependencies, that.dependencies); + } + + @Override + public int hashCode() { + int result = Objects.hash(id, includedInClasspath, url, enabled); + result = 31 * result + Arrays.hashCode(dependencies); + return result; + } } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsClassLoaderNodeBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsClassLoaderNodeBuilder.java index 5b0b2271f..e058076bf 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsClassLoaderNodeBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsClassLoaderNodeBuilder.java @@ -35,6 +35,7 @@ public class NutsClassLoaderNodeBuilder { private String id; private URL url; private boolean enabled; + private boolean includedInClasspath; private List dependencies = new ArrayList<>(); public NutsClassLoaderNodeBuilder() { @@ -44,6 +45,7 @@ public NutsClassLoaderNodeBuilder setAll(NutsClassLoaderNode o) { if (o != null) { id = o.getId(); enabled = o.isEnabled(); + includedInClasspath = o.isIncludedInClasspath(); url = o.getURL(); dependencies.clear(); if (o.getDependencies() != null) { @@ -59,6 +61,7 @@ public NutsClassLoaderNodeBuilder setAll(NutsClassLoaderNodeBuilder o) { if (o != null) { id = o.getId(); enabled = o.isEnabled(); + includedInClasspath = o.isIncludedInClasspath(); url = o.getURL(); dependencies.clear(); if (o.getDependencies() != null) { @@ -70,6 +73,10 @@ public NutsClassLoaderNodeBuilder setAll(NutsClassLoaderNodeBuilder o) { return this; } + public boolean isIncludedInClasspath() { + return includedInClasspath; + } + public boolean isEnabled() { return enabled; } @@ -92,6 +99,16 @@ public NutsClassLoaderNodeBuilder setUrl(URL url) { return this; } + public NutsClassLoaderNodeBuilder setEnabled(boolean enabled) { + this.enabled = enabled; + return this; + } + + public NutsClassLoaderNodeBuilder setIncludedInClasspath(boolean includedInClasspath) { + this.includedInClasspath = includedInClasspath; + return this; + } + public List getDependencies() { return dependencies; } @@ -107,7 +124,7 @@ public NutsClassLoaderNodeBuilder addDependency(NutsClassLoaderNode other) { } public NutsClassLoaderNode build() { - return new NutsClassLoaderNode(id, url, true, dependencies.toArray(new NutsClassLoaderNode[0])); + return new NutsClassLoaderNode(id, url, enabled, includedInClasspath, dependencies.toArray(new NutsClassLoaderNode[0])); } } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandHistory.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandHistory.java index bcf8c0246..79991d5f3 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandHistory.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandHistory.java @@ -24,15 +24,25 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + +import java.io.File; import java.io.InputStream; import java.io.OutputStream; +import java.nio.file.Path; import java.time.Instant; import java.util.ListIterator; /** * @app.category Command Line */ -public interface NutsCommandHistory { +public interface NutsCommandHistory extends NutsComponent { + static NutsCommandHistory of(NutsSession session){ + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsCommandHistory.class, true, null); + } + void load(); @@ -42,6 +52,14 @@ public interface NutsCommandHistory { void save(OutputStream out); + NutsCommandHistory setPath(Path path); + + NutsCommandHistory setPath(File path); + + NutsCommandHistory setPath(NutsPath path); + + NutsPath getPath(); + int size(); void purge(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandHistoryBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandHistoryBuilder.java deleted file mode 100644 index 1ee59152a..000000000 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandHistoryBuilder.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *

- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - *
- *

- * Copyright [2020] [thevpc] Licensed under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law - * or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
==================================================================== - */ -package net.thevpc.nuts; - -import java.io.File; -import java.nio.file.Path; - -/** - * - * @author vpc - */ -public interface NutsCommandHistoryBuilder { - - NutsCommandHistoryBuilder setPath(Path path); - - NutsCommandHistoryBuilder setPath(File path); - - NutsCommandHistory build(); -} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLine.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLine.java index 035d59d36..0f82c7734 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLine.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLine.java @@ -27,6 +27,7 @@ import net.thevpc.nuts.boot.NutsApiUtils; +import java.util.Collection; import java.util.List; /** @@ -97,13 +98,19 @@ public interface NutsCommandLine extends Iterable, NutsFormattable { static NutsCommandLine of(String[] args, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.commandLine().create(args); + return NutsCommandLines.of(session).create(args); + } + + static NutsCommandLine of(List args, NutsSession session) { + return NutsCommandLines.of(session).create(args); } static NutsCommandLine parse(String line, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.commandLine().parse(line); + return NutsCommandLines.of(session).parse(line); + } + + static NutsCommandLine parse(String line, NutsShellFamily shellFamily, NutsSession session) { + return NutsCommandLines.of(session).setShellFamily(shellFamily).parse(line); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLineFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLineFormat.java index 88b594922..cef7fb89f 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLineFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLineFormat.java @@ -25,6 +25,8 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; + /** * Simple Command line Format * @@ -34,6 +36,11 @@ */ public interface NutsCommandLineFormat extends NutsFormat { + static NutsCommandLineFormat of(NutsSession session){ + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsCommandLineFormat.class, true, null); + } + /** * return current command line * diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLineManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLines.java similarity index 79% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLineManager.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLines.java index 9cc88f47e..9e03bc23e 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLineManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsCommandLines.java @@ -26,15 +26,19 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + import java.util.List; /** * @app.category Command Line */ -public interface NutsCommandLineManager { - NutsCommandLineFormat formatter(); - - NutsCommandLineFormat formatter(NutsCommandLine nutsCommandLine); +public interface NutsCommandLines extends NutsComponent { + static NutsCommandLines of(NutsSession session){ + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsCommandLines.class, true, session); + } /** * return new Command line instance @@ -84,35 +88,22 @@ default NutsArgumentName createName(String type) { */ NutsArgumentName createName(String type, String label); - /** - * create argument candidate builder - * @param value candidate value - * @return argument candidate - */ - default NutsArgumentCandidateBuilder createCandidate(String value) { - return createCandidate().setValue(value).setDisplay(value); - } - - - NutsArgumentCandidateBuilder createCandidate(); - - NutsCommandHistoryBuilder createHistory(); NutsSession getSession(); - NutsCommandLineManager setSession(NutsSession session); + NutsCommandLines setSession(NutsSession session); /** * return command line family * @since 0.8.1 * @return command line family */ - NutsShellFamily getCommandlineFamily(); + NutsShellFamily getShellFamily(); /** * change command line family * @param family family * @return {@code this} instance */ - NutsCommandLineManager setCommandlineFamily(NutsShellFamily family); + NutsCommandLines setShellFamily(NutsShellFamily family); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOCompressAction.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsCompress.java similarity index 81% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsIOCompressAction.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsCompress.java index da0947a0c..a6e98c6f9 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOCompressAction.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsCompress.java @@ -25,6 +25,9 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + import java.io.File; import java.io.InputStream; import java.io.OutputStream; @@ -41,7 +44,11 @@ * @since 0.5.4 * @app.category Toolkit */ -public interface NutsIOCompressAction { +public interface NutsCompress extends NutsComponent { + static NutsCompress of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsCompress.class, true, null); + } /** * update format option @@ -49,7 +56,7 @@ public interface NutsIOCompressAction { * @param value value * @return {@code this} instance */ - NutsIOCompressAction setFormatOption(String option, Object value); + NutsCompress setFormatOption(String option, Object value); /** * return format option @@ -69,7 +76,7 @@ public interface NutsIOCompressAction { * @param format format * @return {@code this} instance */ - NutsIOCompressAction setFormat(String format); + NutsCompress setFormat(String format); /** * sources to compress @@ -85,7 +92,7 @@ public interface NutsIOCompressAction { * @return {@code this} instance * @throws NutsUnsupportedArgumentException if unsupported type */ - NutsIOCompressAction addSource(String source); + NutsCompress addSource(String source); /** * add source to compress @@ -94,7 +101,7 @@ public interface NutsIOCompressAction { * @return {@code this} instance * @throws NutsUnsupportedArgumentException if unsupported type */ - NutsIOCompressAction addSource(InputStream source); + NutsCompress addSource(InputStream source); /** * add source to compress @@ -103,7 +110,7 @@ public interface NutsIOCompressAction { * @return {@code this} instance * @throws NutsUnsupportedArgumentException if unsupported type */ - NutsIOCompressAction addSource(File source); + NutsCompress addSource(File source); /** * add source to compress @@ -112,7 +119,7 @@ public interface NutsIOCompressAction { * @return {@code this} instance * @throws NutsUnsupportedArgumentException if unsupported type */ - NutsIOCompressAction addSource(Path source); + NutsCompress addSource(Path source); /** * add source to compress @@ -121,7 +128,7 @@ public interface NutsIOCompressAction { * @return {@code this} instance * @throws NutsUnsupportedArgumentException if unsupported type */ - NutsIOCompressAction addSource(URL source); + NutsCompress addSource(URL source); /** * add source to compress @@ -130,7 +137,7 @@ public interface NutsIOCompressAction { * @return {@code this} instance * @throws NutsUnsupportedArgumentException if unsupported type */ - NutsIOCompressAction addSource(NutsPath source); + NutsCompress addSource(NutsPath source); /** * target to compress to @@ -145,7 +152,7 @@ public interface NutsIOCompressAction { * @param target target * @return {@code this} instance */ - NutsIOCompressAction setTarget(OutputStream target); + NutsCompress setTarget(OutputStream target); /** * update target @@ -153,7 +160,7 @@ public interface NutsIOCompressAction { * @param target target * @return {@code this} instance */ - NutsIOCompressAction setTarget(Path target); + NutsCompress setTarget(Path target); /** * update target @@ -161,7 +168,7 @@ public interface NutsIOCompressAction { * @param target target * @return {@code this} instance */ - NutsIOCompressAction setTarget(File target); + NutsCompress setTarget(File target); /** * update target @@ -169,7 +176,7 @@ public interface NutsIOCompressAction { * @param target target * @return {@code this} instance */ - NutsIOCompressAction setTarget(String target); + NutsCompress setTarget(String target); /** * update target @@ -177,7 +184,7 @@ public interface NutsIOCompressAction { * @param target target * @return {@code this} instance */ - NutsIOCompressAction setTarget(NutsPath target); + NutsCompress setTarget(NutsPath target); /** * update target @@ -185,7 +192,7 @@ public interface NutsIOCompressAction { * @param target target * @return {@code this} instance */ - NutsIOCompressAction to(NutsPath target); + NutsCompress to(NutsPath target); /** * update target @@ -193,7 +200,7 @@ public interface NutsIOCompressAction { * @param target target * @return {@code this} instance */ - NutsIOCompressAction to(OutputStream target); + NutsCompress to(OutputStream target); /** * update target @@ -201,7 +208,7 @@ public interface NutsIOCompressAction { * @param target target * @return {@code this} instance */ - NutsIOCompressAction to(String target); + NutsCompress to(String target); /** * update target @@ -209,7 +216,7 @@ public interface NutsIOCompressAction { * @param target target * @return {@code this} instance */ - NutsIOCompressAction to(Path target); + NutsCompress to(Path target); /** * update target @@ -217,7 +224,7 @@ public interface NutsIOCompressAction { * @param target target * @return {@code this} instance */ - NutsIOCompressAction to(File target); + NutsCompress to(File target); /** * return current session @@ -232,14 +239,14 @@ public interface NutsIOCompressAction { * @param session current session * @return {@code this} instance */ - NutsIOCompressAction setSession(NutsSession session); + NutsCompress setSession(NutsSession session); /** * run this Compress action * * @return {@code this} instance */ - NutsIOCompressAction run(); + NutsCompress run(); /** * true if log progress flag is armed @@ -254,7 +261,7 @@ public interface NutsIOCompressAction { * @param value value * @return {@code this} instance */ - NutsIOCompressAction setLogProgress(boolean value); + NutsCompress setLogProgress(boolean value); /** * return progress factory responsible of creating progress monitor @@ -271,7 +278,7 @@ public interface NutsIOCompressAction { * @return {@code this} instance * @since 0.5.8 */ - NutsIOCompressAction setProgressMonitorFactory(NutsProgressFactory value); + NutsCompress setProgressMonitorFactory(NutsProgressFactory value); /** * set progress monitor. Will create a singleton progress monitor factory @@ -280,7 +287,7 @@ public interface NutsIOCompressAction { * @return {@code this} instance * @since 0.5.8 */ - NutsIOCompressAction setProgressMonitor(NutsProgressMonitor value); + NutsCompress setProgressMonitor(NutsProgressMonitor value); /** * return true if safe copy flag is armed @@ -295,7 +302,7 @@ public interface NutsIOCompressAction { * @param value safe value * @return {@code this} instance */ - NutsIOCompressAction setSafe(boolean value); + NutsCompress setSafe(boolean value); /** * return true if skip root flag is armed. @@ -312,5 +319,5 @@ public interface NutsIOCompressAction { * @return {@code this} instance * @since 0.5.8 */ - NutsIOCompressAction setSkipRoot(boolean value); + NutsCompress setSkipRoot(boolean value); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsConcurrentManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsConcurrentManager.java deleted file mode 100644 index efaa72293..000000000 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsConcurrentManager.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages and libraries - * for runtime execution. Nuts is the ultimate companion for maven (and other - * build managers) as it helps installing all package dependencies at runtime. - * Nuts is not tied to java and is a good choice to share shell scripts and - * other 'things' . Its based on an extensible architecture to help supporting a - * large range of sub managers / repositories. - * - *
- *

- * Copyright [2020] [thevpc] Licensed under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law - * or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
==================================================================== - */ -package net.thevpc.nuts; - -import java.util.concurrent.ExecutorService; - -/** - * @app.category Toolkit - */ -public interface NutsConcurrentManager { - - /** - * create new {@link NutsIOLockAction} instance - * - * @return create new {@link NutsIOLockAction} instance - */ - NutsIOLockAction lock(); - - /** - * return non null executor service - * - * @return non null executor service - */ - ExecutorService executorService(); - - NutsSession getSession(); - - NutsConcurrentManager setSession(NutsSession session); -} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOCopyAction.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsCp.java similarity index 81% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsIOCopyAction.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsCp.java index 10784d2b3..33e0a79d6 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOCopyAction.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsCp.java @@ -25,6 +25,9 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + import java.io.File; import java.io.InputStream; import java.io.OutputStream; @@ -52,7 +55,11 @@ * @since 0.5.4 * @app.category Input Output */ -public interface NutsIOCopyAction { +public interface NutsCp extends NutsComponent { + static NutsCp of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsCp.class, true, null); + } /** * source object to copy from. It may be of any of the supported types. @@ -66,42 +73,42 @@ public interface NutsIOCopyAction { * @return {@code this} instance * @throws NutsUnsupportedArgumentException if unsupported type */ - NutsIOCopyAction setSource(NutsPath source); + NutsCp setSource(NutsPath source); /** * update source to copy from * @param source source to copy from * @return {@code this} instance */ - NutsIOCopyAction setSource(InputStream source); + NutsCp setSource(InputStream source); /** * update source to copy from * @param source source to copy from * @return {@code this} instance */ - NutsIOCopyAction setSource(File source); + NutsCp setSource(File source); /** * update source to copy from * @param source source to copy from * @return {@code this} instance */ - NutsIOCopyAction setSource(Path source); + NutsCp setSource(Path source); /** * update source to copy from * @param source source to copy from * @return {@code this} instance */ - NutsIOCopyAction setSource(URL source); + NutsCp setSource(URL source); /** * update source to copy from * @param source source to copy from * @return {@code this} instance */ - NutsIOCopyAction setSource(String source); + NutsCp setSource(String source); /** * update source to copy from @@ -109,49 +116,49 @@ public interface NutsIOCopyAction { * @return {@code this} instance * @throws NutsUnsupportedArgumentException if unsupported type */ -// NutsIOCopyAction from(NutsPath source); +// NutsCp from(NutsPath source); /** * update source to copy from * @param source source to copy from * @return {@code this} instance */ - NutsIOCopyAction from(String source); + NutsCp from(String source); /** * update source to copy from * @param source source to copy from * @return {@code this} instance */ - NutsIOCopyAction from(NutsPath source); + NutsCp from(NutsPath source); /** * update source to copy from * @param source source to copy from * @return {@code this} instance */ - NutsIOCopyAction from(InputStream source); + NutsCp from(InputStream source); /** * update source to copy from * @param source source to copy from * @return {@code this} instance */ - NutsIOCopyAction from(File source); + NutsCp from(File source); /** * update source to copy from * @param source source to copy from * @return {@code this} instance */ - NutsIOCopyAction from(Path source); + NutsCp from(Path source); /** * update source to copy from * @param source source to copy from * @return {@code this} instance */ - NutsIOCopyAction from(URL source); + NutsCp from(URL source); /** * update source to copy from @@ -159,7 +166,7 @@ public interface NutsIOCopyAction { * @return {@code this} instance * @since 0.8.3 */ - NutsIOCopyAction from(byte[] source); + NutsCp from(byte[] source); /** * update source to copy from @@ -167,7 +174,7 @@ public interface NutsIOCopyAction { * @return {@code this} instance * @since 0.8.3 */ - NutsIOCopyAction setSource(byte[] source); + NutsCp setSource(byte[] source); /** * source object to copy to. It may be of any of the supported types. @@ -180,63 +187,63 @@ public interface NutsIOCopyAction { * @param target target to copy to * @return {@code this} instance */ - NutsIOCopyAction setTarget(OutputStream target); + NutsCp setTarget(OutputStream target); /** * update target to copy from * @param target target to copy to * @return {@code this} instance */ - NutsIOCopyAction setTarget(NutsPrintStream target); + NutsCp setTarget(NutsPrintStream target); /** * update target to copy from * @param target target to copy to * @return {@code this} instance */ -// NutsIOCopyAction setTarget(NutsOutput target); +// NutsCp setTarget(NutsOutput target); /** * update target to copy from * @param target target to copy to * @return {@code this} instance */ - NutsIOCopyAction setTarget(NutsPath target); + NutsCp setTarget(NutsPath target); /** * update target to copy from * @param target target to copy to * @return {@code this} instance */ - NutsIOCopyAction setTarget(Path target); + NutsCp setTarget(Path target); /** * update target to copy from * @param target target to copy to * @return {@code this} instance */ - NutsIOCopyAction setTarget(String target); + NutsCp setTarget(String target); /** * update target to copy from * @param target target to copy to * @return {@code this} instance */ - NutsIOCopyAction setTarget(File target); + NutsCp setTarget(File target); /** * update target * @param target target * @return {@code this} instance */ -// NutsIOCopyAction to(NutsPath target); +// NutsCp to(NutsPath target); /** * update target * @param target target * @return {@code this} instance */ - NutsIOCopyAction to(OutputStream target); + NutsCp to(OutputStream target); /** @@ -244,35 +251,35 @@ public interface NutsIOCopyAction { * @param target target * @return {@code this} instance */ - NutsIOCopyAction to(NutsPrintStream target); + NutsCp to(NutsPrintStream target); /** * update target to copy from * @param target target to copy to * @return {@code this} instance */ - NutsIOCopyAction to(String target); + NutsCp to(String target); /** * update target to copy from * @param target target to copy to * @return {@code this} instance */ - NutsIOCopyAction to(Path target); + NutsCp to(Path target); /** * update target to copy from * @param target target to copy to * @return {@code this} instance */ - NutsIOCopyAction to(File target); + NutsCp to(File target); /** * update target to copy from * @param target target to copy to * @return {@code this} instance */ - NutsIOCopyAction to(NutsPath target); + NutsCp to(NutsPath target); /** * return validator @@ -285,15 +292,15 @@ public interface NutsIOCopyAction { * @param validator validator * @return {@code this} instance */ - NutsIOCopyAction setValidator(NutsIOCopyValidator validator); + NutsCp setValidator(NutsIOCopyValidator validator); boolean isRecursive(); - NutsIOCopyAction setRecursive(boolean recursive); + NutsCp setRecursive(boolean recursive); boolean isMkdirs(); - NutsIOCopyAction setMkdirs(boolean mkdirs); + NutsCp setMkdirs(boolean mkdirs); /** * return true if safe copy flag is armed @@ -306,7 +313,7 @@ public interface NutsIOCopyAction { * @param value value * @return {@code this} instance */ - NutsIOCopyAction setSafe(boolean value); + NutsCp setSafe(boolean value); /** * return current session @@ -319,7 +326,7 @@ public interface NutsIOCopyAction { * @param session current session * @return {@code this} instance */ - NutsIOCopyAction setSession(NutsSession session); + NutsCp setSession(NutsSession session); /** * run this copy action with {@link java.io.ByteArrayOutputStream} target and return bytes result @@ -331,7 +338,7 @@ public interface NutsIOCopyAction { * run this copy action * @return {@code this} instance */ - NutsIOCopyAction run(); + NutsCp run(); /** @@ -345,7 +352,7 @@ public interface NutsIOCopyAction { * @param value value * @return {@code this} instance */ - NutsIOCopyAction setLogProgress(boolean value); + NutsCp setLogProgress(boolean value); /** * return progress factory responsible of creating progress monitor @@ -362,7 +369,7 @@ public interface NutsIOCopyAction { * @return {@code this} instance * @since 0.5.8 */ - NutsIOCopyAction setProgressMonitorFactory(NutsProgressFactory value); + NutsCp setProgressMonitorFactory(NutsProgressFactory value); /** * set progress monitor. Will create a singleton progress monitor factory @@ -371,7 +378,7 @@ public interface NutsIOCopyAction { * @return {@code this} instance * @since 0.5.8 */ - NutsIOCopyAction setProgressMonitor(NutsProgressMonitor value); + NutsCp setProgressMonitor(NutsProgressMonitor value); /** * return true if skip root flag is armed. @@ -388,7 +395,7 @@ public interface NutsIOCopyAction { * @return {@code this} instance * @since 0.5.8 */ - NutsIOCopyAction setSkipRoot(boolean value); + NutsCp setSkipRoot(boolean value); /** * return true created stream should be marked as interruptible @@ -401,11 +408,11 @@ public interface NutsIOCopyAction { * @param interruptible new value * @return {@code this} instance */ - NutsIOCopyAction setInterruptible(boolean interruptible); + NutsCp setInterruptible(boolean interruptible); /** * interrupt last created stream. An exception is throws when the stream is read. * @return {@code this} instance */ - NutsIOCopyAction interrupt(); + NutsCp interrupt(); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependency.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDependency.java index faa56ada3..71a881c26 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependency.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsDependency.java @@ -40,7 +40,10 @@ public interface NutsDependency extends Serializable, NutsFormattable,NutsBlanka static NutsDependency of(String value, NutsSession session) { NutsApiUtils.checkSession(session); - return session.dependency().parser().parseDependency(value); + return + NutsApiUtils + .createSessionCachedType(NutsDependencyParser.class, session,()->NutsDependencyParser.of(session)) + .parse(value); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyBuilder.java index 7eca249e9..63d79c59b 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyBuilder.java @@ -26,6 +26,7 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; import java.util.Map; @@ -38,11 +39,11 @@ * @app.category Descriptor * @since 0.5.4 */ -public interface NutsDependencyBuilder { +public interface NutsDependencyBuilder extends NutsComponent { static NutsDependencyBuilder of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.dependency().builder(); + return session.extensions().createSupported(NutsDependencyBuilder.class,true,null); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyFilterManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyFilters.java similarity index 84% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyFilterManager.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyFilters.java index 1daf60f7e..e9659a214 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyFilterManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyFilters.java @@ -25,21 +25,23 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import java.util.Collection; /** * @app.category Base */ -public interface NutsDependencyFilterManager extends NutsTypedFilters { +@NutsComponentScope(NutsComponentScopeType.SESSION) +public interface NutsDependencyFilters extends NutsTypedFilters { - static NutsDependencyFilterManager of(NutsSession session) { + static NutsDependencyFilters of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.dependency().filter(); + return session.extensions().createSupported(NutsDependencyFilters.class,true,null); } - NutsDependencyFilterManager setSession(NutsSession session); - NutsDependencyFilter byScope(NutsDependencyScopePattern scope); NutsDependencyFilter byScope(NutsDependencyScope scope); @@ -50,8 +52,6 @@ static NutsDependencyFilterManager of(NutsSession session) { NutsDependencyFilter byOptional(Boolean optional); - NutsDependencyFilter byExpression(String expression); - NutsDependencyFilter byExclude(NutsDependencyFilter filter, String[] exclusions); NutsDependencyFilter byArch(Collection arch); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyFormat.java index a39581693..4bf12089c 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyFormat.java @@ -27,6 +27,7 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; /** * Dependency Format Helper @@ -34,11 +35,11 @@ * @since 0.5.6 * @app.category Format */ -public interface NutsDependencyFormat extends NutsFormat { +public interface NutsDependencyFormat extends NutsFormat, NutsComponent { static NutsDependencyFormat of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.dependency().formatter(); + return session.extensions().createSupported(NutsDependencyFormat.class,true,null); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyManager.java deleted file mode 100644 index a5ec669e1..000000000 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyManager.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
- *

- * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== - */ -package net.thevpc.nuts; - -import net.thevpc.nuts.spi.NutsDependencySolver; - -import java.util.Set; - -/** - * @app.category Base - */ -public interface NutsDependencyManager { - - /** - * return mutable id builder instance initialized with {@code this} instance. - * - * @return mutable id builder instance initialized with {@code this} instance - */ - NutsDependencyBuilder builder(); - - NutsDependencyParser parser(); - - - /** - * create dependency format instance - * - * @return dependency format - * @since 0.5.5 - */ - NutsDependencyFormat formatter(); - - /** - * create dependency format instance - * - * @param dependency dependency - * @return dependency format - * @since 0.5.5 - */ - NutsDependencyFormat formatter(NutsDependency dependency); - - NutsDependencyFilterManager filter(); - - Set toScopeSet(NutsDependencyScopePattern other); - - NutsSession getSession(); - - NutsDependencyManager setSession(NutsSession session); - - NutsDependencySolver createSolver(); - - NutsDependencySolver createSolver(String solverName); - - String[] getSolverNames(); -} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyParser.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyParser.java index d51de9e89..d80909e2c 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyParser.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsDependencyParser.java @@ -27,15 +27,16 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; /** * @app.category Base */ -public interface NutsDependencyParser { +public interface NutsDependencyParser extends NutsComponent { static NutsDependencyParser of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.dependency().parser(); + return session.extensions().createSupported(NutsDependencyParser.class,true,null); } boolean isLenient(); @@ -49,8 +50,6 @@ static NutsDependencyParser of(NutsSession session) { * @param dependency dependency * @return new instance of parsed dependency */ - NutsDependency parseDependency(String dependency); + NutsDependency parse(String dependency); - - boolean parseOptional(String optional); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptor.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptor.java index 280efc62f..2c917f29d 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptor.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptor.java @@ -189,4 +189,5 @@ public interface NutsDescriptor extends Serializable, NutsBlankable { */ NutsDescriptorBuilder builder(); + NutsDescriptorFormat formatter(); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorBuilder.java index 19b25be4f..2515312e7 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorBuilder.java @@ -26,6 +26,7 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; import java.io.Serializable; import java.util.List; @@ -42,11 +43,11 @@ * @app.category Descriptor * @since 0.5.4 */ -public interface NutsDescriptorBuilder extends Serializable { +public interface NutsDescriptorBuilder extends Serializable, NutsComponent { static NutsDescriptorBuilder of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.descriptor().descriptorBuilder(); + return session.extensions().createSupported(NutsDescriptorBuilder.class, true,null); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorFilterManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorFilters.java similarity index 83% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorFilterManager.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorFilters.java index c2813acd9..c48331b93 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorFilterManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorFilters.java @@ -27,20 +27,20 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; /** * @app.category Base */ -public interface NutsDescriptorFilterManager extends NutsTypedFilters { - static NutsDescriptorFilterManager of(NutsSession session) { +@NutsComponentScope(NutsComponentScopeType.SESSION) +public interface NutsDescriptorFilters extends NutsTypedFilters{ + static NutsDescriptorFilters of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.descriptor().filter(); + return session.extensions().createSupported(NutsDescriptorFilters.class, true,null); } - NutsDescriptorFilterManager setSession(NutsSession session); - - NutsDescriptorFilter byExpression(String expression); - NutsDescriptorFilter byPackaging(String... values); NutsDescriptorFilter byArch(String... values); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorFormat.java index 305486513..8f0aeabbe 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorFormat.java @@ -26,22 +26,25 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; /** * Descriptor Format class that help building, formatting and parsing Descriptors. + * * @author thevpc - * @since 0.5.4 * @app.category Format + * @since 0.5.4 */ -public interface NutsDescriptorFormat extends NutsFormat { +public interface NutsDescriptorFormat extends NutsFormat, NutsComponent { static NutsDescriptorFormat of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.descriptor().formatter(); + return session.extensions().createSupported(NutsDescriptorFormat.class, true, null); } /** * true if compact flag is armed. * When true, formatted Descriptor will compact JSON result. + * * @return true if compact flag is armed */ boolean isCompact(); @@ -49,6 +52,7 @@ static NutsDescriptorFormat of(NutsSession session) { /** * value compact flag. * When true, formatted Descriptor will compact JSON result. + * * @param compact compact value * @return {@code this} instance */ @@ -57,6 +61,7 @@ static NutsDescriptorFormat of(NutsSession session) { /** * value compact flag. * When true, formatted Descriptor will compact JSON result. + * * @param compact compact value * @return {@code this} instance */ @@ -65,6 +70,7 @@ static NutsDescriptorFormat of(NutsSession session) { /** * value compact flag to true. * When true, formatted Descriptor will compact JSON result. + * * @return {@code this} instance */ NutsDescriptorFormat compact(); @@ -84,11 +90,13 @@ static NutsDescriptorFormat of(NutsSession session) { * to help return a more specific return type; * * @param skipUnsupported when true, all unsupported options are skipped - * @param args argument to configure with + * @param args argument to configure with * @return {@code this} instance */ @Override NutsDescriptorFormat configure(boolean skipUnsupported, String... args); NutsDescriptorFormat setNtf(boolean ntf); + + NutsDescriptorFormat setSession(NutsSession session); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorManager.java deleted file mode 100644 index e2a0d42e9..000000000 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorManager.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
- *

- * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
- * ==================================================================== - */ -package net.thevpc.nuts; - -/** - * @app.category Base - */ -public interface NutsDescriptorManager { - NutsDescriptorParser parser(); - - /** - * create descriptor builder. - * - * @return new instance of NutsDescriptorBuilder - */ - NutsDescriptorBuilder descriptorBuilder(); - - NutsEnvConditionBuilder envConditionBuilder(); - - /** - * create classifier mappings builder. - * - * @return new instance of NutsClassifierMappingBuilder - */ - NutsDescriptorPropertyBuilder propertyBuilder(); - - /** - * create descriptor builder. - * - * @return new instance of NutsIdLocationBuilder - */ - NutsIdLocationBuilder locationBuilder(); - - /** - * create executor builder. - * - * @return new instance of NutsExecutorDescriptorBuilder - */ - NutsArtifactCallBuilder callBuilder(); - - NutsDescriptorFormat formatter(); - - NutsDescriptorFormat formatter(NutsDescriptor value); - - NutsDescriptorFilterManager filter(); - - NutsSession getSession(); - - NutsDescriptorManager setSession(NutsSession session); -} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorParser.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorParser.java index 174c692d3..6fe10b9e3 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorParser.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorParser.java @@ -27,6 +27,7 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; import java.io.File; import java.io.InputStream; @@ -36,11 +37,11 @@ /** * @app.category Base */ -public interface NutsDescriptorParser { +public interface NutsDescriptorParser extends NutsComponent { static NutsDescriptorParser of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.descriptor().parser(); + return session.extensions().createSupported(NutsDescriptorParser.class, true,null); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorPropertyBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorPropertyBuilder.java index d913a5aee..6229da383 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorPropertyBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsDescriptorPropertyBuilder.java @@ -1,11 +1,13 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + +public interface NutsDescriptorPropertyBuilder extends NutsComponent { -public interface NutsDescriptorPropertyBuilder { static NutsDescriptorPropertyBuilder of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.descriptor().propertyBuilder(); + return session.extensions().createSupported(NutsDescriptorPropertyBuilder.class,true,null); } String getName(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsElementFactoryContext.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsElementFactoryContext.java index 23ff0cf32..b8a890816 100755 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsElementFactoryContext.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsElementFactoryContext.java @@ -39,7 +39,7 @@ public interface NutsElementFactoryContext { NutsWorkspace getWorkspace(); - NutsElementFormat elem(); + NutsElements elem(); Map getProperties(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsElementFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsElements.java similarity index 88% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsElementFormat.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsElements.java index eebaec34d..cf9afa9f1 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsElementFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsElements.java @@ -25,6 +25,7 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; import java.io.File; import java.io.InputStream; @@ -44,11 +45,26 @@ * @since 0.5.5 * @app.category Format */ -public interface NutsElementFormat extends NutsObjectFormat { - - static NutsElementFormat of(NutsSession session) { +public interface NutsElements extends NutsObjectFormat, NutsComponent { + Predicate DEFAULT_FORMAT_DESTRUCTOR=new Predicate() { + @Override + public boolean test(Type x) { + if (x instanceof Class) { + Class c = (Class) x; + return !( + NutsString.class.isAssignableFrom(c) + || NutsElement.class.isAssignableFrom(c) + || NutsFormattable.class.isAssignableFrom(c) + || NutsMessage.class.isAssignableFrom(c) + ); + } + return false; + } + }; + + static NutsElements of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.elem(); + return session.extensions().createSupported(NutsElements.class, true, null); } /** @@ -59,6 +75,8 @@ static NutsElementFormat of(NutsSession session) { */ NutsContentType getContentType(); + NutsElements json(); + /** * set the parse content type. defaults to JSON. Non structured content * types are not allowed. @@ -67,7 +85,7 @@ static NutsElementFormat of(NutsSession session) { * @return {@code this} instance * @since 0.8.1 */ - NutsElementFormat setContentType(NutsContentType contentType); + NutsElements setContentType(NutsContentType contentType); /** * return current value to format. @@ -86,7 +104,7 @@ static NutsElementFormat of(NutsSession session) { * @since 0.5.6 */ @Override - NutsElementFormat setValue(Object value); + NutsElements setValue(Object value); /** * set current session. @@ -95,7 +113,7 @@ static NutsElementFormat of(NutsSession session) { * @return {@code this} instance */ @Override - NutsElementFormat setSession(NutsSession session); + NutsElements setSession(NutsSession session); /** * configure the current command with the given arguments. This is an @@ -108,10 +126,10 @@ static NutsElementFormat of(NutsSession session) { * @return {@code this} instance */ @Override - NutsElementFormat configure(boolean skipUnsupported, String... args); + NutsElements configure(boolean skipUnsupported, String... args); @Override - NutsElementFormat setNtf(boolean ntf); + NutsElements setNtf(boolean ntf); /** * compile pathExpression into a valid NutsElementPath that helps filtering @@ -139,7 +157,7 @@ static NutsElementFormat of(NutsSession session) { * @param compact true to enable compact mode * @return {@code this} instance */ - NutsElementFormat setCompact(boolean compact); + NutsElements setCompact(boolean compact); /** * parse url as a valid object of the given type @@ -359,7 +377,7 @@ static NutsElementFormat of(NutsSession session) { Predicate getDestructTypeFilter(); - NutsElementFormat setDestructTypeFilter(Predicate destructTypeFilter); + NutsElements setDestructTypeFilter(Predicate destructTypeFilter); NutsIterableFormat iter(NutsPrintStream out); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsEnvConditionBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsEnvConditionBuilder.java index baa3c99e3..7dc310b97 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsEnvConditionBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsEnvConditionBuilder.java @@ -26,6 +26,7 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; import java.io.Serializable; import java.util.Map; @@ -36,11 +37,11 @@ * @app.category Descriptor * @since 0.8.3 */ -public interface NutsEnvConditionBuilder extends Serializable { +public interface NutsEnvConditionBuilder extends Serializable, NutsComponent { static NutsEnvConditionBuilder of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.descriptor().envConditionBuilder(); + return session.extensions().createSupported(NutsEnvConditionBuilder.class,true,null); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsException.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsException.java index 88473485a..3692f3ebd 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsException.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsException.java @@ -107,7 +107,7 @@ static NutsMessage validateFormattedMessage(NutsMessage message) { static NutsString messageToFormattedString(NutsMessage message, NutsSession session) { NutsApiUtils.checkSession(session); - return session.text().toText(validateFormattedMessage(message)); + return NutsTexts.of(session).toText(validateFormattedMessage(message)); } static String messageToString(NutsMessage message, NutsSession session) { diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsExecCommandFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsExecCommandFormat.java index e356a47c4..adbf2b408 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsExecCommandFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsExecCommandFormat.java @@ -25,6 +25,8 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; + import java.util.function.Function; import java.util.function.Predicate; @@ -37,6 +39,11 @@ * @app.category Format */ public interface NutsExecCommandFormat extends NutsFormat { + static NutsExecCommandFormat of(NutsSession session){ + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsExecCommandFormat.class, true, null); + } + /** * true if input redirection is displayed * @return true if input redirection is displayed diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsExecutionEntryAction.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsExecutionEntries.java similarity index 84% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsExecutionEntryAction.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsExecutionEntries.java index 3c2d8435e..2fca86b9d 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsExecutionEntryAction.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsExecutionEntries.java @@ -26,6 +26,9 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + import java.io.File; import java.io.InputStream; import java.nio.file.Path; @@ -33,7 +36,11 @@ /** * @app.category Base */ -public interface NutsExecutionEntryAction { +public interface NutsExecutionEntries extends NutsComponent { + static NutsExecutionEntries of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsExecutionEntries.class, true, null); + } /** * parse Execution Entries @@ -65,5 +72,5 @@ public interface NutsExecutionEntryAction { NutsSession getSession(); - NutsExecutionEntryAction setSession(NutsSession session); + NutsExecutionEntries setSession(NutsSession session); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsExpr.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsExpr.java new file mode 100644 index 000000000..9cc18837c --- /dev/null +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsExpr.java @@ -0,0 +1,217 @@ +package net.thevpc.nuts; + +import net.thevpc.nuts.spi.NutsComponent; + +public interface NutsExpr extends NutsComponent { + static NutsExpr of(NutsSession session){ + return session.extensions().createSupported(NutsExpr.class, true, null); + } + + Node parse(String expression); + + NutsSession getSession(); + + Var getVar(String varName); + + + + void setFunction(String name, Fct fct); + + void unsetFunction(String name); + + Fct getFunction(String fctName); + + String[] getFunctionNames(); + + Object evalFunction(String fctName, Object... args); + + void setOperator(String name, OpType type, int precedence, boolean rightAssociative, Fct fct); + + Op getOperator(String fctName, OpType type); + + void unsetOperator(String name, OpType type); + + String[] getOperatorNames(OpType type); + + void setVar(String name, Var fct); + + Object evalVar(String fctName); + + NutsExpr newChild(); + + Object evalNode(Node node); + + + enum NodeType implements NutsEnum { + FUNCTION, + OPERATOR, + VARIABLE, + LITERAL; + private final String id; + + NodeType() { + this.id = name().toLowerCase().replace('_', '-'); + } + + public static NodeType parse(String value, NutsSession session) { + return parse(value, null, session); + } + + public static NodeType parse(String value, NodeType emptyValue, NutsSession session) { + NodeType v = parseLenient(value, emptyValue, null); + if (v == null) { + if (!NutsBlankable.isBlank(value)) { + throw new NutsParseEnumException(session, value, NodeType.class); + } + } + return v; + } + + public static NodeType parseLenient(String value) { + return parseLenient(value, null); + } + + public static NodeType parseLenient(String value, NodeType emptyOrErrorValue) { + return parseLenient(value, emptyOrErrorValue, emptyOrErrorValue); + } + + public static NodeType parseLenient(String value, NodeType emptyValue, NodeType errorValue) { + if (value == null) { + value = ""; + } else { + value = value.toUpperCase().trim().replace('-', '_'); + } + if (value.isEmpty()) { + return emptyValue; + } + switch (value) { + case "VAR": + case "VARIABLE": + return VARIABLE; + case "FCT": + case "FUN": + case "FUNCTION": + return FUNCTION; + case "OP": + case "OPERATOR": + return OPERATOR; + case "LIT": + case "LITERAL": + return LITERAL; + } + try { + return NodeType.valueOf(value.toUpperCase()); + } catch (Exception notFound) { + return errorValue; + } + } + + @Override + public String id() { + return id; + } + } + + enum OpType implements NutsEnum { + INFIX, + PREFIX, + POSTFIX; + private final String id; + + OpType() { + this.id = name().toLowerCase().replace('_', '-'); + } + + public static OpType parse(String value, NutsSession session) { + return parse(value, null, session); + } + + public static OpType parse(String value, OpType emptyValue, NutsSession session) { + OpType v = parseLenient(value, emptyValue, null); + if (v == null) { + if (!NutsBlankable.isBlank(value)) { + throw new NutsParseEnumException(session, value, OpType.class); + } + } + return v; + } + + public static OpType parseLenient(String value) { + return parseLenient(value, null); + } + + public static OpType parseLenient(String value, OpType emptyOrErrorValue) { + return parseLenient(value, emptyOrErrorValue, emptyOrErrorValue); + } + + public static OpType parseLenient(String value, OpType emptyValue, OpType errorValue) { + if (value == null) { + value = ""; + } else { + value = value.toUpperCase().trim().replace('-', '_'); + } + if (value.isEmpty()) { + return emptyValue; + } + switch (value) { + case "INFIX": + return INFIX; + case "POSTFIX_OPERATOR": + case "POSTFIX_OP": + case "POSTFIX": + return POSTFIX; + case "PREFIX_OPERATOR": + case "PREFIX_OP": + case "PREFIX": + return PREFIX; + } + try { + return OpType.valueOf(value.toUpperCase()); + } catch (Exception notFound) { + return errorValue; + } + } + + @Override + public String id() { + return id; + } + } + + interface Node { + Object eval(NutsExpr context); + + NodeType getType(); + + Node[] getChildren(); + + String getName(); + + + } + + interface Fct { + Object eval(String name, Node[] args, NutsExpr context); + } + + interface Op { + boolean isLeftAssociative(); + + boolean isRightAssociative(); + + String getName(); + + OpType getType(); + + int getPrecedence(); + + Fct getFct(); + } + + interface Var { + Object get(String name, NutsExpr context); + + void set(String name, Object value, NutsExpr context); + } + +} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsExtensionNotFoundException.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsExtensionNotFoundException.java index ede94f83e..b567b8a08 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsExtensionNotFoundException.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsExtensionNotFoundException.java @@ -42,23 +42,27 @@ public class NutsExtensionNotFoundException extends NutsExtensionException { /** * extension name */ - private final String extensionName; + private final Object criteria; /** * Constructs a new NutsExtensionNotFoundException exception * * @param session workspace * @param missingType missing type - * @param extensionName extension name + * @param criteria extension support criteria object */ - public NutsExtensionNotFoundException(NutsSession session, Class missingType, String extensionName) { + public NutsExtensionNotFoundException(NutsSession session, Class missingType, Object criteria) { super(session, null, + criteria==null? + NutsMessage.cstyle( + "extension %s could not found: type %s could not be wired", missingType.getSimpleName() + ): NutsMessage.cstyle( - "extension %s could not found: type %s could not be wired", extensionName, missingType.getName() + "extension %s could not found: type %s could not be wired with: %s", missingType.getSimpleName(), criteria ) , null); this.missingType = missingType; - this.extensionName = extensionName; + this.criteria = criteria; } /** @@ -76,7 +80,7 @@ public Class getMissingType() { * * @return extension name */ - public String getExtensionName() { - return extensionName; + public Object getCriteria() { + return criteria; } } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsFilterManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsFilters.java similarity index 86% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsFilterManager.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsFilters.java index f93e968b6..33aec70f5 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsFilterManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsFilters.java @@ -23,6 +23,11 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; + /** * Filters helper * @@ -30,7 +35,13 @@ * @app.category Config * @since 0.8.0 */ -public interface NutsFilterManager { +@NutsComponentScope(NutsComponentScopeType.SESSION) +public interface NutsFilters extends NutsComponent { + static NutsFilters of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsFilters.class,true,null); + } + T nonnull(Class type, NutsFilter filter); @@ -77,21 +88,4 @@ public interface NutsFilterManager { T as(Class toFilterInterface, NutsFilter filter); Class detectType(NutsFilter nutsFilter); - - NutsIdFilterManager id(); - - NutsDependencyFilterManager dependency(); - - NutsRepositoryFilterManager repository(); - - NutsVersionFilterManager version(); - - NutsDescriptorFilterManager descriptor(); - - NutsInstallStatusFilterManager installStatus(); - - NutsSession getSession(); - - NutsFilterManager setSession(NutsSession session); - } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsFormat.java index b69cf65bf..7138c9075 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsFormat.java @@ -26,6 +26,8 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.spi.NutsComponent; + import java.io.File; import java.io.OutputStream; import java.io.Writer; @@ -37,7 +39,7 @@ * @since 0.5.5 * @app.category Format */ -public interface NutsFormat extends NutsCommandLineConfigurable { +public interface NutsFormat extends NutsCommandLineConfigurable, NutsComponent { /** * equivalent to {@link #format() } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsFormatManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsFormatManager.java index 5c098ecbe..6e00ec968 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsFormatManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsFormatManager.java @@ -29,14 +29,6 @@ */ public interface NutsFormatManager { - /** - * create element format instance - * - * @return element format - * @since 0.5.5 - */ - NutsElementFormat element(); - /** * create tree format instance * @@ -53,8 +45,6 @@ public interface NutsFormatManager { */ NutsTableFormat table(); - NutsElementFormat element(Object value); - NutsTableFormat table(Object value); NutsTreeFormat tree(Object value); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsGlob.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsGlob.java new file mode 100644 index 000000000..6a8261487 --- /dev/null +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsGlob.java @@ -0,0 +1,19 @@ +package net.thevpc.nuts; + +import net.thevpc.nuts.spi.NutsComponent; + +import java.util.regex.Pattern; + +public interface NutsGlob extends NutsComponent { + static NutsGlob of(NutsSession session) { + return session.extensions().createSupported(NutsGlob.class, true, session); + } + + char getSeparator(); + + NutsGlob setSeparator(char c); + + boolean isGlob(String pattern); + + Pattern toPattern(String pattern); +} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOHashAction.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsHash.java similarity index 75% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsIOHashAction.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsHash.java index 37dd0dc8d..abae82908 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOHashAction.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsHash.java @@ -25,6 +25,9 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + import java.io.File; import java.io.InputStream; import java.io.OutputStream; @@ -33,117 +36,135 @@ /** * I/O command to hash contents. + * * @author thevpc - * @since 0.5.5 * @app.category Input Output + * @since 0.5.5 */ -public interface NutsIOHashAction { +public interface NutsHash extends NutsComponent { + static NutsHash of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsHash.class, true, null); + } /** * source stream to hash + * * @param input source stream to hash * @return {@code this} instance */ - NutsIOHashAction setSource(InputStream input); + NutsHash setSource(InputStream input); /** * file to hash + * * @param file source file to hash * @return {@code this} instance */ - NutsIOHashAction setSource(File file); + NutsHash setSource(File file); /** * file to hash + * * @param path source path to hash * @return {@code this} instance */ - NutsIOHashAction setSource(Path path); + NutsHash setSource(Path path); /** * file to hash + * * @param path source path to hash * @return {@code this} instance */ - NutsIOHashAction setSource(NutsPath path); + NutsHash setSource(NutsPath path); /** * file to hash + * * @param path source path to hash * @return {@code this} instance * @since 0.8.3 */ - NutsIOHashAction setSource(byte[] path); + NutsHash setSource(byte[] path); /** * source stream to hash + * * @param descriptor source descriptor to hash * @return {@code this} instance */ - NutsIOHashAction setSource(NutsDescriptor descriptor); + NutsHash setSource(NutsDescriptor descriptor); /** * compute hash digest and return it as hexadecimal string + * * @return hash digest */ String computeString(); /** * compute hash digest and return it as byte array + * * @return hash digest */ byte[] computeBytes(); /** * compute hash and writes it to the output stream + * * @param out output stream * @return {@code this} instance */ - NutsIOHashAction writeHash(OutputStream out); + NutsHash writeHash(OutputStream out); /** * select MD5 hash algorithm + * * @return {@code this} instance */ - NutsIOHashAction md5(); + NutsHash md5(); NutsSession getSession(); - NutsIOHashAction setSession(NutsSession session); + NutsHash setSession(NutsSession session); /** * select SHA1 hash algorithm + * * @return {@code this} instance */ - NutsIOHashAction sha1(); + NutsHash sha1(); /** * select SHA256 hash algorithm + * * @return {@code this} instance */ - NutsIOHashAction sha256(); + NutsHash sha256(); /** * select hash algorithm. + * * @param algorithm hash algorithm. may be any algorithm supported by - * {@link MessageDigest#getInstance(String)} - * including 'MD5' and 'SHA1' + * {@link MessageDigest#getInstance(String)} + * including 'MD5' and 'SHA1' * @return {@code this} instance */ - NutsIOHashAction algorithm(String algorithm); + NutsHash algorithm(String algorithm); /** - * * @return selected algorithm. default is 'SHA1' */ String getAlgorithm(); /** * select hash algorithm. + * * @param algorithm hash algorithm. may be any algorithm supported by - * {@link MessageDigest#getInstance(String)} - * including 'MD5' and 'SHA1' + * {@link MessageDigest#getInstance(String)} + * including 'MD5' and 'SHA1' * @return {@code this} instance */ - NutsIOHashAction setAlgorithm(String algorithm); + NutsHash setAlgorithm(String algorithm); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsIOManager.java deleted file mode 100644 index 30430f757..000000000 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOManager.java +++ /dev/null @@ -1,169 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
- * is a new Open Source Package Manager to help install packages and libraries - * for runtime execution. Nuts is the ultimate companion for maven (and other - * build managers) as it helps installing all package dependencies at runtime. - * Nuts is not tied to java and is a good choice to share shell scripts and - * other 'things' . Its based on an extensible architecture to help supporting a - * large range of sub managers / repositories. - *
- *

- * Copyright [2020] [thevpc] Licensed under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law - * or agreed to in writing, software distributed under the License is - * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
==================================================================== - */ -package net.thevpc.nuts; - -import net.thevpc.nuts.spi.NutsComponent; -import net.thevpc.nuts.spi.NutsPathFactory; - -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Writer; -import java.net.URL; -import java.nio.file.Path; - -/** - * I/O Manager supports a set of operations to manipulate terminals and files in - * a handy manner that is monitorable and Workspace aware. - * - * @author thevpc - * @app.category Input Output - * @since 0.5.4 - */ -public interface NutsIOManager extends NutsComponent { - - /** - * expand path to Workspace Location - * - * @param path path to expand - * @return expanded path - */ - NutsPath path(String path); - - NutsPath path(File path); - - NutsPath path(Path path); - - NutsPath path(URL path); - - NutsPath path(String path, ClassLoader classLoader); - - /** - * create a null input stream instance - * - * @return null input stream instance - */ - InputStream createNullInputStream(); - - /** - * create a null print stream instance - * - * @return null print stream instance - */ - NutsPrintStream createNullPrintStream(); - - /** - * create print stream that supports the given {@code mode}. If the given - * {@code out} is a PrintStream that supports {@code mode}, it should be - * returned without modification. - * - * @param out stream to wrap - * @param mode mode to support - * @return {@code mode} supporting PrintStream - */ - NutsPrintStream createPrintStream(OutputStream out, NutsTerminalMode mode); - - NutsPrintStream createPrintStream(OutputStream out); - - NutsPrintStream createPrintStream(Writer out); - - NutsMemoryPrintStream createMemoryPrintStream(); - - NutsTempAction tmp(); - - /** - * create new {@link NutsIOCopyAction} instance - * - * @return create new {@link NutsIOCopyAction} instance - */ - NutsIOCopyAction copy(); - - /** - * create new {@link NutsIOProcessAction} instance - * - * @return create new {@link NutsIOProcessAction} instance - */ - NutsIOProcessAction ps(); - - /** - * create new {@link NutsIOCompressAction} instance - * - * @return create new {@link NutsIOCompressAction} instance - */ - NutsIOCompressAction compress(); - - /** - * create new {@link NutsIOUncompressAction} instance - * - * @return create new {@link NutsIOUncompressAction} instance - */ - NutsIOUncompressAction uncompress(); - - /** - * create new {@link NutsIODeleteAction} instance - * - * @return create new {@link NutsIODeleteAction} instance - */ - NutsIODeleteAction delete(); - - /** - * create new {@link NutsMonitorAction} instance that helps monitoring - * streams. - * - * @return create new {@link NutsIOLockAction} instance - */ - NutsMonitorAction monitor(); - - /** - * create new {@link NutsIOHashAction} instance that helps hashing streams - * and files. - * - * @return create new {@link NutsIOHashAction} instance - */ - NutsIOHashAction hash(); - -// NutsInputAction input(); -// -// NutsOutputAction output(); - - NutsSession getSession(); - - NutsIOManager setSession(NutsSession session); - - NutsPrintStream stdout(); - - NutsPrintStream stderr(); - - InputStream stdin(); - - boolean isStandardOutputStream(NutsPrintStream out); - - boolean isStandardErrorStream(NutsPrintStream out); - - boolean isStandardInputStream(InputStream in); - - NutsIOManager addPathFactory(NutsPathFactory pathFactory); - - NutsIOManager removePathFactory(NutsPathFactory pathFactory); -} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsId.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsId.java index d569c10ad..eacc2d710 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsId.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsId.java @@ -31,19 +31,21 @@ /** * Immutable Artifact id information. + * * @author thevpc - * @since 0.1.0 * @app.category Descriptor + * @since 0.1.0 */ -public interface NutsId extends /*NutsTokenFilter, Serializable,*/ Comparable, NutsFormattable, NutsBlankable { +public interface NutsId extends Comparable, NutsFormattable, NutsBlankable { static NutsId of(String value, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.id().parser().parse(value); + return NutsApiUtils.createSessionCachedType(NutsIdParser.class, session,()->NutsIdParser.of(session)) + .parse(value); } /** * true if other has exact short name than {@code this} + * * @param other other id * @return true if other has exact short name than {@code this} */ @@ -51,6 +53,7 @@ static NutsId of(String value, NutsSession session) { /** * true if other has exact long name than {@code this} + * * @param other other id * @return true if other has exact long name than {@code this} */ @@ -58,6 +61,7 @@ static NutsId of(String value, NutsSession session) { /** * true if this id is a long name + * * @return true if this id is a long name */ boolean isLongId(); @@ -104,36 +108,42 @@ static NutsId of(String value, NutsSession session) { * id face define is a release file type selector of the id. * It helps discriminating content (jar) from descriptor, from other (hash,...) * files released for the very same artifact. + * * @return id face selector */ String getFace(); /** * os supported by the artifact + * * @return os supported by the artifact */ NutsEnvCondition getCondition(); /** * properties in the url query form + * * @return properties in the url query form. */ String getPropertiesQuery(); /** * properties as map. + * * @return properties as map. */ Map getProperties(); /** * artifact repository (usually repository name or id) + * * @return artifact repository (usually repository name or id) */ String getRepository(); /** * artifact group which identifies uniquely projects and group of projects. + * * @return artifact group which identifies uniquely projects and group of projects. */ String getGroupId(); @@ -191,24 +201,28 @@ static NutsId of(String value, NutsSession session) { /** * tag used to distinguish between different artifacts that were built from the same source code + * * @return tag used to distinguish between different artifacts that were built from the same source code */ String getClassifier(); /** * package packaging type + * * @return packaging */ String getPackaging(); /** * artifact version (never null) + * * @return artifact version (never null) */ NutsVersion getVersion(); /** * create a builder (mutable id) based on this id + * * @return a new instance of builder (mutable id) based on this id */ NutsIdBuilder builder(); @@ -237,7 +251,7 @@ static NutsId of(String value, NutsSession session) { * @return when the current version is a single value version X , returns [X,[ version that guarantees forward compatibility in all other cases returns the current version * @since 0.8.3 */ - NutsId compatOlder() ; + NutsId compatOlder(); boolean isNull(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdBuilder.java index 7a1061edc..28f5eb33e 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdBuilder.java @@ -26,6 +26,7 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; import java.io.Serializable; import java.util.Map; @@ -37,10 +38,10 @@ * @since 0.5.4 * @app.category Descriptor */ -public interface NutsIdBuilder extends Serializable { +public interface NutsIdBuilder extends NutsComponent, Serializable { static NutsIdBuilder of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.id().builder(); + return session.extensions().createSupported(NutsIdBuilder.class,true,null); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdFilterManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdFilters.java similarity index 79% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsIdFilterManager.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsIdFilters.java index b881335a3..5dbe60267 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdFilterManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdFilters.java @@ -27,20 +27,20 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; /** * @app.category Base */ -public interface NutsIdFilterManager extends NutsTypedFilters { - static NutsIdFilterManager of(NutsSession session) { +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) +public interface NutsIdFilters extends NutsTypedFilters{ + static NutsIdFilters of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.id().filter(); + return session.extensions().createSupported(NutsIdFilters.class, true, null); } - NutsIdFilterManager setSession(NutsSession session); - - NutsIdFilter byExpression(String expression); - NutsIdFilter byDefaultVersion(Boolean defaultVersion); NutsIdFilter byInstallStatus(NutsInstallStatusFilter installStatus); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdFormat.java index bbf00fdc5..cb5a6259e 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdFormat.java @@ -25,6 +25,9 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + /** * Class responsible of manipulating {@link NutsId} instances: *
    @@ -35,7 +38,11 @@ * @since 0.5.4 * @app.category Format */ -public interface NutsIdFormat extends NutsFormat { +public interface NutsIdFormat extends NutsFormat, NutsComponent { + static NutsIdFormat of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsIdFormat.class,true,null); + } /** * return true when the repository should not be included in formatted instance diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdLocation.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdLocation.java index 49ffa625f..c5b0815d9 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdLocation.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdLocation.java @@ -26,30 +26,83 @@ */ package net.thevpc.nuts; +import java.util.Objects; + /** * This class is used in {@link NutsDescriptor} to describe * locations/mirrors to download artifact content instead of the * regular location. * @app.category Descriptor */ -public interface NutsIdLocation extends NutsBlankable{ +public class NutsIdLocation implements NutsBlankable{ + private String url; + private String region; + private String classifier; + + public NutsIdLocation(String url, String region, String classifier) { + this.url = url; + this.region = region; + this.classifier = classifier; + } /** * location url of the artifact content * @return location url of the artifact content */ - String getUrl(); + public String getUrl() { + return url; + } /** * location (geographic) region that may be used to select * the most effective mirror * @return location (geographic) region that may be used to select the most effective mirror */ - String getRegion(); + public String getRegion() { + return region; + } /** * classifier for the artifact * @return classifier for the artifact */ - String getClassifier(); + public String getClassifier() { + return classifier; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + NutsIdLocation that = (NutsIdLocation) o; + return Objects.equals(url, that.url) && Objects.equals(region, that.region) && Objects.equals(classifier, that.classifier); + } + + @Override + public int hashCode() { + return Objects.hash(url, region, classifier); + } + + @Override + public String toString() { + return "NutsIdLocation{" + + "url='" + url + '\'' + + ", region='" + region + '\'' + + ", classifier='" + classifier + '\'' + + '}'; + } + + @Override + public boolean isBlank() { + if(!NutsBlankable.isBlank(url)){ + return false; + } + if(!NutsBlankable.isBlank(classifier)){ + return false; + } + if(!NutsBlankable.isBlank(region)){ + return false; + } + return true; + } } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdLocationBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdLocationBuilder.java deleted file mode 100644 index ffba5c619..000000000 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdLocationBuilder.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
    - * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - *
    - *

    - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
    - * ==================================================================== - */ -package net.thevpc.nuts; - -import net.thevpc.nuts.boot.NutsApiUtils; - -/** - * Mutable IdLocation class that helps creating instance of immutable {@link NutsIdLocation}. - * Instances of {@link NutsIdLocation} are used in {@link NutsDescriptor} (see {@link NutsDescriptor#getLocations()}) - * - * @app.category Base - */ -public interface NutsIdLocationBuilder { - static NutsIdLocationBuilder of(NutsSession session) { - NutsApiUtils.checkSession(session); - return session.descriptor().locationBuilder(); - } - - /** - * return location url - * @return location url - */ - String getUrl(); - - /** - * update location url - * @param value location url - * @return {@code this} instance - */ - NutsIdLocationBuilder setUrl(String value); - - /** - * return location classifier - * @return location classifier - */ - String getClassifier(); - - /** - * update location classifier - * @param value location classifier - * @return {@code this} instance - */ - NutsIdLocationBuilder setClassifier(String value); - - /** - * return location region - * @return location region - */ - String getRegion(); - - /** - * update location region - * @param value location region - * @return {@code this} instance - */ - NutsIdLocationBuilder setRegion(String value); - - /** - * update all attributes, copy from {@code value} instance - * @param value instance to copy from - * @return {@code this} instance - */ - NutsIdLocationBuilder set(NutsIdLocationBuilder value); - - /** - * update all attributes, copy from {@code value} instance - * @param value instance to copy from - * @return {@code this} instance - */ - NutsIdLocationBuilder set(NutsIdLocation value); - - /** - * clear this instance (set null/default all properties) - * - * @return {@code this instance} - */ - NutsIdLocationBuilder clear(); - - - /** - * create new instance of {@link NutsIdLocation} initialized with this builder values. - * @return new instance of {@link NutsIdLocation} initialized with this builder values. - */ - NutsIdLocation build(); -} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdParser.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdParser.java index 0c9099034..ec13196f4 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdParser.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdParser.java @@ -27,15 +27,16 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; /** * @app.category Base */ -public interface NutsIdParser { +public interface NutsIdParser extends NutsComponent { static NutsIdParser of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.id().parser(); + return session.extensions().createSupported(NutsIdParser.class,true,null); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdResolver.java similarity index 54% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsIdManager.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsIdResolver.java index 88b98ec4b..0d694bc2c 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIdManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsIdResolver.java @@ -3,13 +3,12 @@ * Nuts : Network Updatable Things Service * (universal package manager) *
    - * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * + * is a new Open Source Package Manager to help install packages and libraries + * for runtime execution. Nuts is the ultimate companion for maven (and other + * build managers) as it helps installing all package dependencies at runtime. + * Nuts is not tied to java and is a good choice to share shell scripts and + * other 'things' . Its based on an extensible architecture to help supporting a + * large range of sub managers / repositories. *
    *

    * Copyright [2020] [thevpc] @@ -26,34 +25,22 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + /** - * @app.category Base + * Id Resolver from classpath + * + * @author thevpc + * @app.category Descriptor + * @since 0.8.3 */ -public interface NutsIdManager { - /** - * parse the id to null if blank, a valid instance if parse succeeds or throws an error - * @param id id to parse - * @return parsed id to a valid instance or throws an error - */ - NutsId parse(String id); - - /** - * return new parser that accepts blank values but throws errors when the id is invalid - * @return new parser that accepts blank values but throws errors when the id is invalid - */ - NutsIdParser parser(); +public interface NutsIdResolver extends NutsComponent { - NutsIdFormat formatter(); - - NutsIdFormat formatter(NutsId id); - - NutsIdFilterManager filter(); - - /** - * create new instance of id builder - * @return new instance of id builder - */ - NutsIdBuilder builder(); + static NutsIdResolver of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsIdResolver.class,true,null); + } /** * detect nuts id from resources containing the given class @@ -69,9 +56,4 @@ public interface NutsIdManager { * @return all nuts ids detected from resources containing the given class */ NutsId[] resolveIds(Class clazz); - - - NutsSession getSession(); - - NutsIdManager setSession(NutsSession session); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsInfoFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsInfoFormat.java index d318824e2..1d8d7fa5e 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsInfoFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsInfoFormat.java @@ -25,6 +25,8 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; + import java.util.Map; /** @@ -36,6 +38,11 @@ */ public interface NutsInfoFormat extends NutsFormat { + static NutsInfoFormat of(NutsSession session){ + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsInfoFormat.class, true, null); + } + /** * update session * diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsMonitorAction.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsInputStreamMonitor.java similarity index 77% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsMonitorAction.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsInputStreamMonitor.java index 21eca72a7..1de3a47a3 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsMonitorAction.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsInputStreamMonitor.java @@ -25,6 +25,9 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + import java.io.File; import java.io.InputStream; import java.nio.file.Path; @@ -35,7 +38,11 @@ * @author thevpc * @app.category Toolkit */ -public interface NutsMonitorAction { +public interface NutsInputStreamMonitor extends NutsComponent { + static NutsInputStreamMonitor of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsInputStreamMonitor.class, true, null); + } /** * return current session @@ -50,7 +57,7 @@ public interface NutsMonitorAction { * @param session session * @return {@code this} instance */ - NutsMonitorAction setSession(NutsSession session); + NutsInputStreamMonitor setSession(NutsSession session); /** * return action name @@ -65,7 +72,7 @@ public interface NutsMonitorAction { * @param name action name * @return {@code this} instance */ - NutsMonitorAction setName(NutsString name); + NutsInputStreamMonitor setName(NutsString name); /** * return source origin @@ -80,7 +87,7 @@ public interface NutsMonitorAction { * @param origin source origin * @return {@code this} instance */ - NutsMonitorAction setOrigin(Object origin); + NutsInputStreamMonitor setOrigin(Object origin); /** * return operation length @@ -95,7 +102,7 @@ public interface NutsMonitorAction { * @param len operation length * @return {@code this} instance */ - NutsMonitorAction setLength(long len); + NutsInputStreamMonitor setLength(long len); /** * update operation source @@ -103,11 +110,11 @@ public interface NutsMonitorAction { * @param path operation source * @return {@code this} instance */ - NutsMonitorAction setSource(String path); + NutsInputStreamMonitor setSource(String path); -// NutsMonitorAction setSource(NutsPath inputSource); +// NutsInputStreamMonitor setSource(NutsPath inputSource); - NutsMonitorAction setSource(NutsPath inputSource); + NutsInputStreamMonitor setSource(NutsPath inputSource); /** * update operation source @@ -115,7 +122,7 @@ public interface NutsMonitorAction { * @param path operation source * @return {@code this} instance */ - NutsMonitorAction setSource(Path path); + NutsInputStreamMonitor setSource(Path path); /** * update operation source @@ -123,7 +130,7 @@ public interface NutsMonitorAction { * @param path operation source * @return {@code this} instance */ - NutsMonitorAction setSource(File path); + NutsInputStreamMonitor setSource(File path); /** * update operation source @@ -131,7 +138,7 @@ public interface NutsMonitorAction { * @param path operation source * @return {@code this} instance */ - NutsMonitorAction setSource(InputStream path); + NutsInputStreamMonitor setSource(InputStream path); /** * Create monitored input stream @@ -142,11 +149,12 @@ public interface NutsMonitorAction { String getSourceTypeName(); - NutsMonitorAction setSourceTypeName(String sourceType); + NutsInputStreamMonitor setSourceTypeName(String sourceType); /** * return true if log progress on terminal + * * @return true if log progress on terminal */ boolean isLogProgress(); @@ -158,7 +166,7 @@ public interface NutsMonitorAction { * @return {@code this} instance * @since 0.5.8 */ - NutsMonitorAction setLogProgress(boolean value); + NutsInputStreamMonitor setLogProgress(boolean value); /** @@ -176,7 +184,7 @@ public interface NutsMonitorAction { * @return {@code this} instance * @since 0.5.8 */ - NutsMonitorAction setProgressFactory(NutsProgressFactory value); + NutsInputStreamMonitor setProgressFactory(NutsProgressFactory value); /** * set progress monitor. Will create a singleton progress monitor factory @@ -185,5 +193,5 @@ public interface NutsMonitorAction { * @return {@code this} instance * @since 0.5.8 */ - NutsMonitorAction setProgressMonitor(NutsProgressMonitor value); + NutsInputStreamMonitor setProgressMonitor(NutsProgressMonitor value); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsInputStreams.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsInputStreams.java new file mode 100644 index 000000000..283b871a0 --- /dev/null +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsInputStreams.java @@ -0,0 +1,23 @@ +package net.thevpc.nuts; + +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + +import java.io.InputStream; + +public interface NutsInputStreams extends NutsComponent { + static NutsInputStreams of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsInputStreams.class, true, session); + } + + static InputStream ofNull(NutsSession session) { + return of(session).ofNull(); + } + + InputStream ofNull(); + + boolean isStdin(InputStream in); + + InputStream stdin(); +} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsInstallStatusFilterManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsInstallStatusFilters.java similarity index 75% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsInstallStatusFilterManager.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsInstallStatusFilters.java index 72812747e..ccaec7675 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsInstallStatusFilterManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsInstallStatusFilters.java @@ -24,12 +24,20 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; + /** * @app.category Base */ -public interface NutsInstallStatusFilterManager extends NutsTypedFilters { - - NutsInstallStatusFilterManager setSession(NutsSession session); +@NutsComponentScope(NutsComponentScopeType.SESSION) +public interface NutsInstallStatusFilters extends NutsTypedFilters { + static NutsInstallStatusFilters of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsInstallStatusFilters.class,true,null); + } NutsInstallStatusFilter byInstalled(boolean value); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOLockAction.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsLocks.java similarity index 86% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsIOLockAction.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsLocks.java index 665249de3..e75124cb9 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOLockAction.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsLocks.java @@ -25,6 +25,9 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + import java.io.File; import java.nio.file.Path; import java.util.concurrent.Callable; @@ -37,7 +40,11 @@ * @since 0.5.8 * @app.category Input Output */ -public interface NutsIOLockAction { +public interface NutsLocks extends NutsComponent { + static NutsLocks of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsLocks.class, true, null); + } /** * lock source represents a user defined @@ -51,7 +58,7 @@ public interface NutsIOLockAction { * @param source source * @return {@code this} instance */ - NutsIOLockAction setSource(Object source); + NutsLocks setSource(Object source); /** * lock resource represents the lock it self. @@ -65,21 +72,21 @@ public interface NutsIOLockAction { * @param source resource * @return {@code this} instance */ - NutsIOLockAction setResource(File source); + NutsLocks setResource(File source); /** * update resource * @param source resource * @return {@code this} instance */ - NutsIOLockAction setResource(Path source); + NutsLocks setResource(Path source); /** * update resource * @param source resource * @return {@code this} instance */ - NutsIOLockAction setResource(Object source); + NutsLocks setResource(Object source); /** * return session @@ -92,7 +99,7 @@ public interface NutsIOLockAction { * @param session session * @return {@code this} instance */ - NutsIOLockAction setSession(NutsSession session); + NutsLocks setSession(NutsSession session); /** * create lock object for the given source and resource diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsLogger.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsLogger.java index c2f4061e4..2840da8e3 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsLogger.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsLogger.java @@ -26,49 +26,154 @@ */ package net.thevpc.nuts; -import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsLogManager; import java.util.function.Supplier; +import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; /** * Workspace aware Logger + * * @app.category Logging */ public interface NutsLogger { + /** + * create an instance of {@link NutsLogger} + * + * @param clazz logger clazz + * @return new instance of {@link NutsLogger} + */ static NutsLogger of(Class clazz, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.log().of(clazz); + return NutsLogManager.of(session).createLogger(clazz, session); + } + + /** + * create an instance of {@link NutsLogger} + * + * @param name logger name + * @return new instance of {@link NutsLogger} + */ + static NutsLogger of(String name, NutsSession session) { + return NutsLogManager.of(session).createLogger(name, session); + } + + /** + * Log handler + * + * @return Log handler + */ + static Handler[] getHandlers(NutsSession session) { + return NutsLogManager.of(session).getHandlers(session); + } + + /** + * remove the given handler + * + * @param handler handler to remove + */ + static void removeHandler(Handler handler, NutsSession session) { + NutsLogManager.of(session).removeHandler(handler, session); + } + + /** + * add the given handler + * + * @param handler handler to add + * @return this + */ + static void addHandler(Handler handler, NutsSession session) { + NutsLogManager.of(session).addHandler(handler, session); + } + + /** + * terminal handler + * + * @return terminal handler + */ + static Handler getTermHandler(NutsSession session) { + return NutsLogManager.of(session).getTermHandler(session); + } + + /** + * file handler + * + * @return file handler + */ + static Handler getFileHandler(NutsSession session) { + return NutsLogManager.of(session).getFileHandler(session); + } + + + /** + * return terminal logger level + * + * @return terminal logger level + */ + static Level getTermLevel(NutsSession session) { + return NutsLogManager.of(session).getTermLevel(session); + } + + /** + * set terminal logger level + * + * @param level new level + * @return this + */ + static void setTermLevel(Level level, NutsSession session) { + NutsLogManager.of(session).setTermLevel(level, session); } + /** + * return file logger level + * + * @return file logger level + */ + static Level getFileLevel(NutsSession session) { + return NutsLogManager.of(session).getFileLevel(session); + } + + /** + * set file logger level + * + * @param level new level + * @return this + */ + static void setFileLevel(Level level, NutsSession session) { + NutsLogManager.of(session).setFileLevel(level, session); + } + + /** * Check if a message of the given level would actually be logged * by this logger. This check is based on the Loggers effective level, * which may be inherited from its parent. * - * @param level a message logging level + * @param level a message logging level * @return true if the given message level is currently being logged. */ boolean isLoggable(Level level); /** * log message using the given verb and level + * * @param session session - * @param level message level - * @param verb message verb / category - * @param msg message - * @param thrown thrown exception + * @param level message level + * @param verb message verb / category + * @param msg message + * @param thrown thrown exception */ - void log(NutsSession session, Level level, NutsLogVerb verb, NutsMessage msg,Throwable thrown); + void log(NutsSession session, Level level, NutsLogVerb verb, NutsMessage msg, Throwable thrown); /** * log message using the given verb and level - * @param session session - * @param level message level - * @param verb message verb / category - * @param msgSupplier message supplier + * + * @param session session + * @param level message level + * @param verb message verb / category + * @param msgSupplier message supplier * @param errorSupplier message error */ void log(NutsSession session, Level level, NutsLogVerb verb, Supplier msgSupplier, Supplier errorSupplier); @@ -76,6 +181,7 @@ static NutsLogger of(Class clazz, NutsSession session) { /** * create a logger op. * A Logger Op handles all information to log in a custom manner. + * * @return new instance of {@link NutsLoggerOp} */ NutsLoggerOp with(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsLoggerOp.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsLoggerOp.java index 320bac44b..6dd25a461 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsLoggerOp.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsLoggerOp.java @@ -38,8 +38,10 @@ */ public interface NutsLoggerOp { static NutsLoggerOp of(Class clazz, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.log().of(clazz).with(); + return NutsLogger.of(clazz,session).with(); + } + static NutsLoggerOp of(String name, NutsSession session) { + return NutsLogger.of(name,session).with(); } NutsLoggerOp session(NutsSession session); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsMemoryPrintStream.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsMemoryPrintStream.java index fb6797b6a..18ce08f85 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsMemoryPrintStream.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsMemoryPrintStream.java @@ -1,5 +1,9 @@ package net.thevpc.nuts; public interface NutsMemoryPrintStream extends NutsPrintStream { + static NutsMemoryPrintStream of(NutsSession session) { + return NutsPrintStreams.of(session).createInMemory(); + } + byte[] getBytes(); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsMessage.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsMessage.java index d2c8c5598..b18b5e105 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsMessage.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsMessage.java @@ -52,7 +52,7 @@ public Object[] getParams() { } public NutsString toNutsString(NutsSession session) { - return session.text().toText(this); + return NutsTexts.of(session).toText(this); } @Override diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsMissingSessionException.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsMissingSessionException.java new file mode 100644 index 000000000..00f39c117 --- /dev/null +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsMissingSessionException.java @@ -0,0 +1,89 @@ +/** + * ==================================================================== + * Nuts : Network Updatable Things Service + * (universal package manager) + *
    + * is a new Open Source Package Manager to help install packages + * and libraries for runtime execution. Nuts is the ultimate companion for + * maven (and other build managers) as it helps installing all package + * dependencies at runtime. Nuts is not tied to java and is a good choice + * to share shell scripts and other 'things' . Its based on an extensible + * architecture to help supporting a large range of sub managers / repositories. + * + *
    + *

    + * Copyright [2020] [thevpc] + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a + * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + *
    + * ==================================================================== + */ +package net.thevpc.nuts; + +import java.util.HashSet; +import java.util.Set; +import java.util.Stack; + +/** + * Base Boot Nuts Exception. Thrown when the Workspace could is booting + * and is not yet available. + * + * @author thevpc + * @app.category Exceptions + * @since 0.5.4 + */ +public class NutsMissingSessionException extends RuntimeException { + + private final NutsMessage message; + + /** + * Constructs a 'missing session' exception + * + */ + public NutsMissingSessionException() { + this(NutsMessage.plain("missing session")); + } + + /** + * Constructs a new runtime exception with the specified detail message. + * The cause is not initialized, and may subsequently be initialized by a + * call to {@link #initCause}. + * + * @param message the detail message. The detail message is saved for + * later retrieval by the {@link #getMessage()} method. + */ + public NutsMissingSessionException(NutsMessage message) { + super(message.toString()); + this.message = message; + } + + /** + * Constructs a new runtime exception with the specified detail message and + * cause. + *
    + * Note that the detail message associated with + * {@code cause} is not automatically incorporated in + * this runtime exception's detail message. + * + * @param message the detail message (which is saved for later retrieval + * by the {@link #getMessage()} method). + * @param cause the cause (which is saved for later retrieval by the + * {@link #getCause()} method). (A {@code null} value is + * permitted, and indicates that the cause is nonexistent or + * unknown.) + */ + public NutsMissingSessionException(NutsMessage message, Throwable cause) { + super(message.toString(), cause); + this.message = message; + } + + public NutsMessage getFormattedMessage() { + return message; + } +} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsObjectElementBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsObjectElementBuilder.java index ac2ce40f0..a16df1219 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsObjectElementBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsObjectElementBuilder.java @@ -39,7 +39,7 @@ public interface NutsObjectElementBuilder extends NutsElementBuilder { static NutsObjectElementBuilder of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.elem().forObject(); + return NutsElements.of(session).forObject(); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsObjectFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsObjectFormat.java index 27a6299b1..3bba69675 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsObjectFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsObjectFormat.java @@ -26,6 +26,8 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; + /** * Object format is responsible of formatting to terminal * a given object. Multiple implementation should be available @@ -35,6 +37,11 @@ */ public interface NutsObjectFormat extends NutsFormat { + static NutsObjectFormat of(NutsSession session){ + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsObjectFormat.class, true, null); + } + /** * return value to format * @return value to format diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsPath.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsPath.java index e83ac7fb6..95b2723f2 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsPath.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsPath.java @@ -27,6 +27,8 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsPathFactory; +import net.thevpc.nuts.spi.NutsPaths; import java.io.File; import java.io.InputStream; @@ -39,34 +41,50 @@ import java.util.stream.Stream; /** - * this interface describes any local or remote file path. It includes simple file path (ex. '/home/here' and 'c:\\here') + * this interface describes any local or remote resource path. It includes simple file path (ex. '/home/here' and 'c:\\here') * as well as urls and uri ('ssh://here'), etc. + * * @app.category Input Output */ public interface NutsPath extends NutsFormattable { static NutsPath of(URL path, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.io().path(path); + return NutsApiUtils + .createSessionCachedType(NutsPaths.class, session,()->NutsPaths.of(session)) + .createPath(path,session); } static NutsPath of(String path, ClassLoader classLoader, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.io().path(path, classLoader); + return NutsPaths.of(session).createPath(path, classLoader,session); } static NutsPath of(File path, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.io().path(path); + return NutsApiUtils + .createSessionCachedType(NutsPaths.class, session,()->NutsPaths.of(session)) + .createPath(path,session); } static NutsPath of(Path path, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.io().path(path); + return NutsApiUtils + .createSessionCachedType(NutsPaths.class, session,()->NutsPaths.of(session)) + .createPath(path,session); } static NutsPath of(String path, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.io().path(path); + return NutsApiUtils + .createSessionCachedType(NutsPaths.class, session,()->NutsPaths.of(session)) + .createPath(path,session); + } + + static void addPathFactory(NutsPathFactory pathFactory,NutsSession session){ + NutsApiUtils + .createSessionCachedType(NutsPaths.class, session,()->NutsPaths.of(session)) + .addPathFactory(pathFactory, session); + } + + static void removePathFactory(NutsPathFactory pathFactory,NutsSession session){ + NutsApiUtils + .createSessionCachedType(NutsPaths.class, session,()->NutsPaths.of(session)) + .removePathFactory(pathFactory, session); } /** @@ -104,6 +122,7 @@ static NutsPath of(String path, NutsSession session) { /** * path protocol or null if undefined. This is some how similar to url protocol * Particularly file system paths have an empty (aka "") protocol + * * @return path protocol or null if undefined */ String getProtocol(); @@ -114,12 +133,14 @@ static NutsPath of(String path, NutsSession session) { /** * return true if the path is or can be converted to a valid url + * * @return true if the path is or can be converted to a valid url */ boolean isURL(); /** * return true if the path is or can be converted to a valid local file + * * @return true if the path is or can be converted to a valid local file */ boolean isFile(); @@ -131,12 +152,14 @@ static NutsPath of(String path, NutsSession session) { /** * return a valid url or null + * * @return a valid url or null */ URL asURL(); /** * return a valid local file + * * @return return a valid local file */ Path asFilePath(); @@ -160,6 +183,7 @@ static NutsPath of(String path, NutsSession session) { boolean isOther(); boolean isSymbolicLink(); + boolean isDirectory(); boolean isRegularFile(); @@ -185,6 +209,7 @@ static NutsPath of(String path, NutsSession session) { NutsPath getParent(); String getUserKind(); + NutsPath setUserKind(String userKind); boolean isAbsolute(); @@ -204,7 +229,9 @@ static NutsPath of(String path, NutsSession session) { Set getPermissions(); NutsPath setPermissions(NutsPathPermission... permissions); + NutsPath addPermissions(NutsPathPermission... permissions); + NutsPath removePermissions(NutsPathPermission... permissions); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsPathBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsPathBuilder.java index 96bdbc97f..42867774f 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsPathBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsPathBuilder.java @@ -37,23 +37,19 @@ */ public interface NutsPathBuilder extends NutsFormattable { static NutsPathBuilder of(URL path, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.io().path(path).builder(); + return NutsPath.of(path,session).builder(); } static NutsPathBuilder of(String path, ClassLoader classLoader, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.io().path(path, classLoader).builder(); + return NutsPath.of(path,classLoader,session).builder(); } static NutsPathBuilder of(File path, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.io().path(path).builder(); + return NutsPath.of(path,session).builder(); } static NutsPathBuilder of(String path, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.io().path(path).builder(); + return NutsPath.of(path,session).builder(); } Function getVarResolver(); @@ -64,9 +60,9 @@ static NutsPathBuilder of(String path, NutsSession session) { NutsPathBuilder withAppBaseDir(); - String getBaseDir(); + NutsPath getBaseDir(); - NutsPathBuilder setBaseDir(String baseDir); + NutsPathBuilder setBaseDir(NutsPath baseDir); /** * expand path to {@code baseFolder}. Expansion mechanism supports '~' diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsPrintStream.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsPrintStream.java index fce8047be..520881ad3 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsPrintStream.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsPrintStream.java @@ -7,23 +7,39 @@ public interface NutsPrintStream { static NutsPrintStream ofNull(NutsSession session) { - return session.io().createNullPrintStream(); + return NutsPrintStreams.of(session).createNull(); } - static NutsPrintStream ofMemory(NutsSession session) { - return session.io().createMemoryPrintStream(); + /** + * return new in-memory NutsPrintStream implementation. + * this is equivalent to {@code NutsMemoryPrintStream.of(session)} + * @param session session + * @return new in-memory NutsPrintStream implementation + */ + static NutsMemoryPrintStream ofInMemory(NutsSession session) { + return NutsPrintStreams.of(session).createInMemory(); } static NutsPrintStream of(OutputStream out, NutsSession session) { - return session.io().createPrintStream(out); + return NutsPrintStreams.of(session).create(out); } + /** + * create print stream that supports the given {@code mode}. If the given + * {@code out} is a PrintStream that supports {@code mode}, it should be + * returned without modification. + * + * @param out stream to wrap + * @param mode mode to support + * @param session session + * @return {@code mode} supporting PrintStream + */ static NutsPrintStream of(OutputStream out, NutsTerminalMode mode, NutsSession session) { - return session.io().createPrintStream(out, mode); + return NutsPrintStreams.of(session).create(out, mode); } static NutsPrintStream of(Writer out, NutsSession session) { - return session.io().createPrintStream(out); + return NutsPrintStreams.of(session).create(out); } NutsSession getSession(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsPrintStreams.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsPrintStreams.java new file mode 100644 index 000000000..409a530a0 --- /dev/null +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsPrintStreams.java @@ -0,0 +1,45 @@ +package net.thevpc.nuts; + +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + +import java.io.OutputStream; +import java.io.Writer; + +public interface NutsPrintStreams extends NutsComponent { + static NutsPrintStreams of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsPrintStreams.class, true, session); + } + + + NutsPrintStream createNull() ; + + NutsMemoryPrintStream createInMemory() ; + + /** + * create print stream that supports the given {@code mode}. If the given + * {@code out} is a PrintStream that supports {@code mode}, it should be + * returned without modification. + * + * @param out stream to wrap + * @param mode mode to support + * @return {@code mode} supporting PrintStream + */ + NutsPrintStream create(OutputStream out, NutsTerminalMode mode) ; + + NutsPrintStream create(OutputStream out) ; + + NutsPrintStream create(Writer out, NutsTerminalMode mode); + + NutsPrintStream create(Writer out) ; + + boolean isStdout(NutsPrintStream out); + + boolean isStderr(NutsPrintStream out); + + NutsPrintStream stdout(); + + NutsPrintStream stderr(); + +} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsPropertiesFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsPropertiesFormat.java index c7a16e0bf..bb9fbc79d 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsPropertiesFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsPropertiesFormat.java @@ -26,6 +26,8 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; + import java.util.Map; /** @@ -33,6 +35,10 @@ * @app.category Format */ public interface NutsPropertiesFormat extends NutsObjectFormat { + static NutsPropertiesFormat of(NutsSession session){ + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsPropertiesFormat.class, true, null); + } /** * return model to format diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOProcessAction.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsPs.java similarity index 84% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsIOProcessAction.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsPs.java index b662db31e..06afcffb3 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOProcessAction.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsPs.java @@ -25,6 +25,9 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + /** * I/O Action that help monitoring processes * @@ -32,7 +35,12 @@ * @since 0.5.8 * @app.category Toolkit */ -public interface NutsIOProcessAction { +public interface NutsPs extends NutsComponent { + static NutsPs of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsPs.class, true, null); + } + /** * process type to consider. Supported 'java' * @@ -47,7 +55,7 @@ public interface NutsIOProcessAction { * @param processType new type * @return return {@code this} instance */ - NutsIOProcessAction setType(String processType); + NutsPs setType(String processType); /** * set process type to consider. @@ -56,7 +64,7 @@ public interface NutsIOProcessAction { * @param processType new type * @return return {@code this} instance */ - NutsIOProcessAction type(String processType); + NutsPs type(String processType); /** * list all processes of type {@link #getType()} @@ -78,7 +86,7 @@ public interface NutsIOProcessAction { * @param session session * @return {@code this} instance */ - NutsIOProcessAction setSession(NutsSession session); + NutsPs setSession(NutsSession session); /** * return true if fail fast. @@ -95,7 +103,7 @@ public interface NutsIOProcessAction { * @param failFast value * @return {@code this} instance */ - NutsIOProcessAction setFailFast(boolean failFast); + NutsPs setFailFast(boolean failFast); boolean isSupportedKillProcess(); @@ -107,12 +115,12 @@ public interface NutsIOProcessAction { * @param failFast value * @return {@code this} instance */ - NutsIOProcessAction failFast(boolean failFast); + NutsPs failFast(boolean failFast); /** * set fail fast flag * * @return {@code this} instance */ - NutsIOProcessAction failFast(); + NutsPs failFast(); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsReadOnlyException.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsReadOnlyException.java index 9e3563c81..9175add1e 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsReadOnlyException.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsReadOnlyException.java @@ -39,7 +39,7 @@ public class NutsReadOnlyException extends NutsException { * @param location location */ public NutsReadOnlyException(NutsSession session, String location) { - super(session, NutsMessage.cstyle("cannot update readonly workspace %s", session.text().ofStyled(location, NutsTextStyle.path()))); + super(session, NutsMessage.cstyle("cannot update readonly workspace %s", NutsTexts.of(session).ofStyled(location, NutsTextStyle.path()))); } /** @@ -47,6 +47,6 @@ public NutsReadOnlyException(NutsSession session, String location) { * @param session workspace */ public NutsReadOnlyException(NutsSession session) { - this(session, session == null ? null : session.locations().getWorkspaceLocation()); + this(session, session == null ? null : String.valueOf(session.locations().getWorkspaceLocation())); } } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsRepositoryFilterManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsRepositoryFilters.java similarity index 73% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsRepositoryFilterManager.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsRepositoryFilters.java index 45495ae41..a35214cd1 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsRepositoryFilterManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsRepositoryFilters.java @@ -26,11 +26,20 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; + /** * @app.category Base */ -public interface NutsRepositoryFilterManager extends NutsTypedFilters { - NutsRepositoryFilterManager setSession(NutsSession session); +@NutsComponentScope(NutsComponentScopeType.SESSION) +public interface NutsRepositoryFilters extends NutsTypedFilters{ + static NutsRepositoryFilters of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsRepositoryFilters.class,true,null); + } NutsRepositoryFilter byName(String... names); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsRepositoryManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsRepositoryManager.java index 63b0228c5..c35a37708 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsRepositoryManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsRepositoryManager.java @@ -29,7 +29,7 @@ */ public interface NutsRepositoryManager { - NutsRepositoryFilterManager filter(); + NutsRepositoryFilters filter(); NutsRepository addRepository(NutsAddRepositoryOptions options); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIODeleteAction.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsRm.java similarity index 82% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsIODeleteAction.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsRm.java index 5e51b2d3c..4f11c0777 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIODeleteAction.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsRm.java @@ -25,6 +25,9 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + import java.io.File; import java.nio.file.Path; @@ -35,7 +38,12 @@ * @since 0.5.8 * @app.category Input Output */ -public interface NutsIODeleteAction { +public interface NutsRm extends NutsComponent { + static NutsRm of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsRm.class, true, null); + } + /** * return target to delete * @return return target to delete @@ -47,21 +55,21 @@ public interface NutsIODeleteAction { * @param target target * @return {@code this} instance */ - NutsIODeleteAction setTarget(Object target); + NutsRm setTarget(Object target); /** * update target to delete * @param target target * @return {@code this} instance */ - NutsIODeleteAction setTarget(File target); + NutsRm setTarget(File target); /** * update target to delete * @param target target * @return {@code this} instance */ - NutsIODeleteAction setTarget(Path target); + NutsRm setTarget(Path target); /** * current session @@ -74,13 +82,13 @@ public interface NutsIODeleteAction { * @param session session * @return {@code this} instance */ - NutsIODeleteAction setSession(NutsSession session); + NutsRm setSession(NutsSession session); /** * run delete action and return {@code this} * @return {@code this} instance */ - NutsIODeleteAction run(); + NutsRm run(); /** * return true if fail fast. @@ -95,6 +103,6 @@ public interface NutsIODeleteAction { * @param failFast value * @return {@code this} instance */ - NutsIODeleteAction setFailFast(boolean failFast); + NutsRm setFailFast(boolean failFast); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsSession.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsSession.java index 93c5dd9a3..2e20285bc 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsSession.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsSession.java @@ -124,71 +124,6 @@ public interface NutsSession extends NutsCommandLineConfigurable { NutsSession setBot(Boolean bot); -// /** -// * equivalent to {@code setTrace(false)} -// * -// * @return {@code this} instance -// */ -// NutsSession setSilent(); -// /** -// * true if force flag is armed. some operations may require user -// * confirmation before performing critical operations such as overriding -// * existing values, deleting sensitive information ; in such cases, arming -// * force flag will provide an implicit confirmation. -// * -// * @return true if force flag is armed. -// */ -// boolean isForce(); -// /** -// * change force flag value. some operations may require user confirmation -// * before performing critical operations such as overriding existing values, -// * deleting sensitive information ; in such cases, arming force flag will -// * provide an implicit confirmation. -// * -// * @param enable if true force flag is armed -// * @return {@code this} instance -// */ -// NutsSession setForce(Boolean enable); -// -// /** -// * equivalent to {@code setAsk(true)} -// * -// * @return {@code this} instance -// */ -// NutsSession ask(); -// /** -// * equivalent to {@code setConfirm(enable?ASK:null)} -// * -// * @param enable new value -// * @return {@code this} instance -// */ -// NutsSession setAsk(boolean enable); -// /** -// * change YES flag value. some operations may require user confirmation -// * before performing critical operations such as overriding existing values, -// * deleting sensitive information ; in such cases, arming yes flag will -// * provide an implicit confirmation. -// * -// * @param enable if true yes flag is armed -// * @return {@code this} instance -// */ -// NutsSession setYes(boolean enable); -// -// /** -// * equivalent to {@code setYes(true)} -// * -// * @return {@code this} instance -// */ -// NutsSession yes(); -// -// /** -// * equivalent to {@code setYes(enable)} -// * -// * @param enable new value -// * @return {@code this} instance -// */ -// NutsSession yes(boolean enable); - /** * true if YES is armed. * @@ -197,31 +132,6 @@ public interface NutsSession extends NutsCommandLineConfigurable { */ boolean isYes(); -// /** -// * change no flag value. some operations may require user confirmation -// * before performing critical operations such as overriding existing values, -// * deleting sensitive information ; in such cases, arming no flag will -// * provide an implicit negative confirmation. -// * -// * @param enable if true NO flag is armed -// * @return {@code this} instance -// */ -// NutsSession setNo(boolean enable); -// /** -// * equivalent to {@code setNo(true)} -// * -// * @return {@code this} instance -// */ -// NutsSession no(); -// -// /** -// * equivalent to {@code setNo(enable)} -// * -// * @param enable new value -// * @return {@code this} instance -// */ -// NutsSession no(boolean enable); - /** * true if NO is armed. * @@ -732,13 +642,6 @@ public interface NutsSession extends NutsCommandLineConfigurable { */ NutsUpdateStatisticsCommand updateStatistics(); - /** - * - * @since 0.8.3 - * @return new apps manager instance - */ - NutsWorkspaceAppsManager apps(); - /** * * @since 0.8.3 @@ -767,27 +670,6 @@ public interface NutsSession extends NutsCommandLineConfigurable { */ NutsWorkspaceSecurityManager security(); - /** - * - * @since 0.8.3 - * @return new filter manager instance - */ - NutsFilterManager filters(); - - /** - * - * @since 0.8.3 - * @return new io manager instance - */ - NutsIOManager io(); - - /** - * - * @since 0.8.3 - * @return new log manager instance - */ - NutsLogManager log(); - /** * * @since 0.8.3 @@ -796,29 +678,6 @@ public interface NutsSession extends NutsCommandLineConfigurable { NutsWorkspaceEventManager events(); - /** - * - * @since 0.8.3 - * @return new events commandline instance - */ - NutsCommandLineManager commandLine(); - - /** - * create id format instance - * - * @return id format - * @since 0.8.3 - */ - NutsIdManager id(); - - /** - * create version format instance - * - * @return version format - * @since 0.8.3 - */ - NutsVersionManager version(); - /** * create info format instance * @@ -827,22 +686,6 @@ public interface NutsSession extends NutsCommandLineConfigurable { */ NutsInfoFormat info(); - /** - * create descriptor format instance - * - * @return descriptor format - * @since 0.8.3 - */ - NutsDescriptorManager descriptor(); - - /** - * return dependency manager - * - * @return dependency manager - * @since 0.8.3 - */ - NutsDependencyManager dependency(); - /** * * @since 0.8.3 @@ -850,20 +693,6 @@ public interface NutsSession extends NutsCommandLineConfigurable { */ NutsFormatManager formats(); - /** - * - * @since 0.8.3 - * @return new concurrent manager instance - */ - NutsConcurrentManager concurrent(); - - /** - * - * @since 0.8.3 - * @return new utilities' manager instance - */ - NutsUtilManager util(); - /** * * @since 0.8.3 @@ -899,28 +728,6 @@ public interface NutsSession extends NutsCommandLineConfigurable { */ NutsBootManager boot(); - /** - * - * @since 0.8.3 - * @return new terminal manager instance - */ - NutsTerminalManager term(); - - /** - * - * @since 0.8.3 - * @return new text manager instance - */ - NutsTextManager text(); - - /** - * create element format instance - * - * @return element format - * @since 0.8.3 - */ - NutsElementFormat elem(); - /** * return dependency solver Name * @return dependency solver Name diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsSessionTerminal.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsSessionTerminal.java index e80239971..dc3736c7d 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsSessionTerminal.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsSessionTerminal.java @@ -26,6 +26,8 @@ package net.thevpc.nuts; +import net.thevpc.nuts.spi.NutsTerminals; + import java.io.InputStream; /** @@ -35,6 +37,17 @@ * @since 0.5.4 */ public interface NutsSessionTerminal { + static NutsSessionTerminal of(NutsSession session) { + return NutsTerminals.of(session).createTerminal(session); + } + + static NutsSessionTerminal of(NutsSessionTerminal parent, NutsSession session) { + return NutsTerminals.of(session).createTerminal(parent,session); + } + + static NutsSessionTerminal of(InputStream in, NutsPrintStream out, NutsPrintStream err, NutsSession session) { + return NutsTerminals.of(session).createTerminal(in, out, err,session); + } String readLine(NutsPrintStream out, String prompt, Object... params); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsStream.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsStream.java index d463f96c1..367191bd9 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsStream.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsStream.java @@ -42,6 +42,36 @@ * @since 0.5.4 */ public interface NutsStream extends Iterable { + static NutsStream of(T[] str, String name,NutsSession session){ + return NutsStreams.of(session).create(str,name); + } + + static NutsStream of(Iterable str, String name,NutsSession session){ + return NutsStreams.of(session).create(str,name); + } + + static NutsStream of(Iterator str, String name,NutsSession session){ + return NutsStreams.of(session).create(str,name); + } + + static NutsStream of(Stream str, String name,NutsSession session){ + return NutsStreams.of(session).create(str,name); + } + static NutsStream of(T[] str, NutsSession session){ + return NutsStreams.of(session).create(str,null); + } + + static NutsStream of(Iterable str, NutsSession session){ + return NutsStreams.of(session).create(str,null); + } + + static NutsStream of(Iterator str, NutsSession session){ + return NutsStreams.of(session).create(str,null); + } + + static NutsStream of(Stream str, NutsSession session){ + return NutsStreams.of(session).create(str,null); + } /** * return result as a java.util.List . diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsStreams.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsStreams.java new file mode 100644 index 000000000..c0f7e10a6 --- /dev/null +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsStreams.java @@ -0,0 +1,23 @@ +package net.thevpc.nuts; + +import net.thevpc.nuts.spi.NutsComponent; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; + +import java.util.Iterator; +import java.util.stream.Stream; + +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) +public interface NutsStreams extends NutsComponent { + static NutsStreams of(NutsSession session) { + return session.extensions().createSupported(NutsStreams.class, true, session); + } + + NutsStream create(T[] str, String name); + + NutsStream create(Iterable str, String name); + + NutsStream create(Iterator str, String name); + + NutsStream create(Stream str, String name); +} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsString.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsString.java index 816d55c62..049cad467 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsString.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsString.java @@ -36,17 +36,17 @@ public interface NutsString extends NutsBlankable{ static NutsString of(NutsMessage str, NutsSession session) { - return session.text().toText(str); + return NutsTexts.of(session).toText(str); } static NutsString parse(String str, NutsSession session) { NutsApiUtils.checkSession(session); - return session.text().parse(str); + return NutsTexts.of(session).parse(str); } static NutsString plain(String str, NutsSession session) { NutsApiUtils.checkSession(session); - return session.text().ofPlain(str); + return NutsTexts.of(session).ofPlain(str); } NutsString immutable(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsSupportMode.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsSupportMode.java index 0fd98f37c..7c99bdb07 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsSupportMode.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsSupportMode.java @@ -85,7 +85,7 @@ public static NutsSupportMode parse(String value, NutsSupportMode emptyValue, Nu public boolean acceptCondition(NutsSupportCondition request, NutsSession session) { if (session == null) { - throw new IllegalArgumentException("missing session"); + throw new NutsMissingSessionException(); } if (request == null) { request = NutsSupportCondition.NEVER; diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsSystemTerminal.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsSystemTerminal.java index b807867bd..fc7cd9440 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsSystemTerminal.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsSystemTerminal.java @@ -27,6 +27,7 @@ package net.thevpc.nuts; import net.thevpc.nuts.spi.NutsSystemTerminalBase; +import net.thevpc.nuts.spi.NutsTerminals; import java.io.InputStream; @@ -37,6 +38,9 @@ * @app.category Input Output */ public interface NutsSystemTerminal extends NutsSystemTerminalBase { + static void enableRichTerm(NutsSession session){ + NutsTerminals.of(session).enableRichTerm(session); + } /** * Reads a single line of text from the terminal's input stream. * @@ -91,4 +95,6 @@ public interface NutsSystemTerminal extends NutsSystemTerminalBase { * @return {@code this} instance */ NutsSystemTerminal printProgress(float progress, NutsMessage message, NutsSession session); + + NutsSystemTerminalBase getParent(); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTableFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTableFormat.java index 088dd6ba1..205aedf9e 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTableFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsTableFormat.java @@ -25,6 +25,8 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; + /** * * @author thevpc @@ -32,6 +34,10 @@ * @app.category Format */ public interface NutsTableFormat extends NutsObjectFormat { + static NutsTableFormat of(NutsSession session){ + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsTableFormat.class, true, null); + } boolean isVisibleHeader(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTerminalManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTerminalManager.java deleted file mode 100644 index 46088ccb2..000000000 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTerminalManager.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
    - * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
    - *

    - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
    - * ==================================================================== - */ -package net.thevpc.nuts; - -import net.thevpc.nuts.spi.NutsSystemTerminalBase; -import net.thevpc.nuts.spi.NutsTerminalSpec; - -import java.io.InputStream; - -/** - * @app.category Input Output - */ -public interface NutsTerminalManager { - - - /** - * return workspace system terminal. - * - * @return workspace system terminal - */ - NutsSystemTerminal getSystemTerminal(); - - /** - * update workspace wide system terminal - * - * @param terminal system terminal - * @return {@code this} instance - */ - NutsTerminalManager setSystemTerminal(NutsSystemTerminalBase terminal); - - NutsTerminalManager enableRichTerm(); - - NutsSystemTerminal createSystemTerminal(NutsTerminalSpec spec); - - /** - * return workspace default terminal - * - * @return workspace default terminal - */ - NutsSessionTerminal getTerminal(); - - /** - * update workspace wide terminal - * - * @param terminal terminal - * @return {@code this} instance - */ - NutsTerminalManager setTerminal(NutsSessionTerminal terminal); - - /** - * return new terminal bound to system terminal - * - * @return new terminal - */ - NutsSessionTerminal createTerminal(); - - /** - * return new terminal - * - * @param in in - * @param out out - * @param err err - * @return new terminal - */ - NutsSessionTerminal createTerminal(InputStream in, NutsPrintStream out, NutsPrintStream err); - - NutsSessionTerminal createTerminal(NutsSessionTerminal terminal); - - -// /** -// * return new terminal bound to the given {@code parent} -// * -// * @param parent parent terminal or null -// * @return new terminal -// */ -// NutsSessionTerminal createTerminal(NutsSystemTerminalBase parent); - -// /** -// * prepare PrintStream to handle NutsImmutableString aware format pattern. If the instance -// * already supports Nuts specific pattern it will be returned unmodified. -// * -// * @param out PrintStream to check -// * @return NutsImmutableString pattern format capable PrintStream -// */ -// PrintStream prepare(PrintStream out); -// -// /** -// * prepare PrintWriter to handle %N (escape) format pattern. If the instance -// * already supports Nuts specific pattern it will be returned unmodified. -// * -// * @param out PrintWriter to check -// * @return %N pattern format capable PrintWriter -// */ -// PrintWriter prepare(PrintWriter out); - -// /** -// * true if the stream is not null and could be resolved as Formatted Output -// * Stream. If False is returned this does no mean necessarily that the -// * stream is not formatted. -// * -// * @param out stream to check -// * @return true if formatted -// */ -// boolean isFormatted(OutputStream out); -// -// /** -// * true if the stream is not null and could be resolved as Formatted Output -// * Stream. If False is returned this does no mean necessarily that the -// * stream is not formatted. -// * -// * @param out stream to check -// * @return true if formatted -// */ -// boolean isFormatted(Writer out); - -// NutsTerminalManager sendTerminalCommand(NutsPrintStream out, NutsTerminalCommand command); - - NutsSession getSession(); - - NutsTerminalManager setSession(NutsSession session); - -} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsText.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsText.java index f9dec7361..e00d08431 100755 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsText.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsText.java @@ -35,7 +35,7 @@ public interface NutsText extends NutsString { static NutsString parse(String str, NutsSession session) { NutsApiUtils.checkSession(session); - return session.text().parse(str); + return NutsTexts.of(session).parse(str); } NutsTextType getType(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextBuilder.java index 925d5297c..ce3de0a10 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextBuilder.java @@ -11,7 +11,7 @@ public interface NutsTextBuilder extends NutsString { static NutsTextBuilder of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.text().builder(); + return NutsTexts.of(session).builder(); } NutsTextStyleGenerator getStyleGenerator(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextParser.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextParser.java index 4122e3d59..8fa5a8fc4 100755 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextParser.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextParser.java @@ -12,7 +12,7 @@ public interface NutsTextParser { static NutsTextParser of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.text().parser(); + return NutsTexts.of(session).parser(); } String escapeText(String text); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyle.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyle.java index e5d6566a6..947b12eb1 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyle.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyle.java @@ -1,9 +1,13 @@ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; + +import java.util.Objects; + /** * @app.category Format */ -public class NutsTextStyle { +public class NutsTextStyle implements NutsEnum { private final NutsTextStyleType type; private final int variant; @@ -311,4 +315,75 @@ public String toString() { } return type + "(" + variant + ")"; } + + public static NutsTextStyle parseLenient(String value) { + return parseLenient(value, null, null); + } + + public static NutsTextStyle parseLenient(String value, NutsTextStyle emptyValue) { + return parseLenient(value, emptyValue, emptyValue); + } + + public static NutsTextStyle parseLenient(String value, NutsTextStyle emptyValue, NutsTextStyle errorValue) { + value = value == null ? "" : value.trim(); + int par = value.indexOf('('); + String nbr = ""; + String key = value; + if (par > 0) { + int b = value.indexOf(')', par); + if (b > 0) { + nbr = value.substring(par + 1, b); + key = value.substring(0, par); + } + }else{ + int len = value.length(); + int x= len; + while(x-1>=0 && Character.isDigit(value.charAt(x-1))){ + x--; + } + if(x< len){ + nbr = value.substring(x, len); + key = value.substring(0, x); + } + } + nbr = nbr.trim(); + key = key.trim(); + if (nbr.isEmpty()) { + nbr = "0"; + } + NutsTextStyleType t = NutsTextStyleType.parseLenient(key, null, null); + if (t == null) { + if (NutsBlankable.isBlank(key)) { + return emptyValue; + } + return errorValue; + } + Integer ii = NutsApiUtils.parseInt(nbr, null, null); + if (ii == null) { + if (NutsBlankable.isBlank(key)) { + ii = 0; + } else { + return errorValue; + } + } + return NutsTextStyle.of(t, ii); + } + + @Override + public String id() { + return type.id() + (variant == 0 ? "" : String.valueOf(variant)); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + NutsTextStyle that = (NutsTextStyle) o; + return variant == that.variant && type == that.type; + } + + @Override + public int hashCode() { + return Objects.hash(type, variant); + } } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyleType.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyleType.java index afb502fc7..f0401677b 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyleType.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyleType.java @@ -29,6 +29,7 @@ * @app.category Format */ public enum NutsTextStyleType implements NutsEnum { + PLAIN(true),//f UNDERLINED(true),//_ ITALIC(true),// / STRIKED(true),// - @@ -84,11 +85,140 @@ public static NutsTextStyleType parseLenient(String value, NutsTextStyleType emp if (value == null) { value = ""; } else { - value = value.toUpperCase().trim().replace('-', '_'); + value = value.toUpperCase().trim().replace('-', '_').replace("_",""); } if (value.isEmpty()) { return emptyValue; } + switch (value.toLowerCase()) { + case "f": + case "foreground": + case "foregroundcolor": { + return FORE_COLOR; + } + case "plain": { + return PLAIN; + } + case "foregroundtruecolor": { + return FORE_TRUE_COLOR; + } + case "b": + case "background": + case "back_color": + case "backcolor": + case "backgroundcolor": { + return BACK_COLOR; + } + case "backtruecolor": + case "backgroundtruecolor": { + return BACK_TRUE_COLOR; + + } + + case "p": + case "primary": { + return PRIMARY; + } + case "s": + case "secondary": { + return SECONDARY; + } + case "underlined": { + return UNDERLINED; + } + case "bold": { + return BOLD; + } + case "boolean": + case "bool": + { + return BOOLEAN; + } + case "blink": { + return BLINK; + } + case "comments": { + return COMMENTS; + } + case "config": { + return CONFIG; + } + case "danger": { + return DANGER; + } + case "date": { + return DATE; + } + case "number": { + return NUMBER; + } + case "error": { + return ERROR; + } + case "warning": + case "warn": + { + return WARN; + } + case "version": { + return VERSION; + } + case "var": + case "variable": + { + return VAR; + } + case "input": { + return INPUT; + } + case "title": { + return TITLE; + } + case "success": { + return SUCCESS; + } + case "string": { + return STRING; + } + case "strike": + case "striked": { + return STRIKED; + } + case "separator": { + return SEPARATOR; + } + case "reversed": { + return REVERSED; + } + case "path": { + return PATH; + } + case "option": { + return OPTION; + } + case "pale": { + return PALE; + } + case "operator": { + return OPERATOR; + } + case "kw": + case "keyword": + { + return KEYWORD; + } + case "italic": { + return ITALIC; + } + case "information": + case "info": + { + return INFO; + } + case "fail": { + return FAIL; + } + } try { return NutsTextStyleType.valueOf(value.toUpperCase()); } catch (Exception notFound) { diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyled.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyled.java index e3748c2b9..59fdb282c 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyled.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyled.java @@ -5,27 +5,27 @@ */ public interface NutsTextStyled extends NutsText { static NutsTextStyled of(String str, NutsTextStyle style, NutsSession session) { - return session.text().ofStyled(str, style); + return NutsTexts.of(session).ofStyled(str, style); } static NutsTextStyled of(NutsString str, NutsTextStyle style, NutsSession session) { - return session.text().ofStyled(str, style); + return NutsTexts.of(session).ofStyled(str, style); } static NutsTextStyled of(NutsText str, NutsTextStyle style, NutsSession session) { - return session.text().ofStyled(str, style); + return NutsTexts.of(session).ofStyled(str, style); } static NutsTextStyled of(String str, NutsTextStyles styles, NutsSession session) { - return session.text().ofStyled(str, styles); + return NutsTexts.of(session).ofStyled(str, styles); } static NutsTextStyled of(NutsString str, NutsTextStyles styles, NutsSession session) { - return session.text().ofStyled(str, styles); + return NutsTexts.of(session).ofStyled(str, styles); } static NutsTextStyled of(NutsText str, NutsTextStyles styles, NutsSession session) { - return session.text().ofStyled(str, styles); + return NutsTexts.of(session).ofStyled(str, styles); } NutsText getChild(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyles.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyles.java index 7abe1f270..c4bd39965 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyles.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsTextStyles.java @@ -23,18 +23,15 @@ */ package net.thevpc.nuts; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; +import java.util.*; +import java.util.stream.Collectors; /** - * * @author vpc */ -public final class NutsTextStyles implements Iterable { +public final class NutsTextStyles implements Iterable, NutsEnum { - public static NutsTextStyles NONE = new NutsTextStyles(new NutsTextStyle[0]); + public static NutsTextStyles PLAIN = new NutsTextStyles(new NutsTextStyle[0]); private final NutsTextStyle[] elements; @@ -43,67 +40,70 @@ private NutsTextStyles(NutsTextStyle[] elements) { } public static NutsTextStyles of(NutsTextStyle... others) { - return NONE.append(others); + Map visited=new TreeMap<>(); + if(others!=null) { + for (NutsTextStyle element : others) { + if(element!=null) { + visited.put(element.getType(), element); + } + } + } + visited.remove(NutsTextStyleType.PLAIN); + if(visited.isEmpty()){ + return PLAIN; + } + return new NutsTextStyles(visited.values().toArray(new NutsTextStyle[0])); } public static NutsTextStyles of(NutsTextStyle other) { - if (other == null) { - return NONE; + if (other == null || other.getType()==NutsTextStyleType.PLAIN) { + return PLAIN; } return new NutsTextStyles(new NutsTextStyle[]{other}); } public NutsTextStyles append(NutsTextStyles other) { - if (other == null || other.isNone()) { + if (other == null || other.isPlain()) { return this; } - if (this.isNone()) { + if (this.isPlain()) { return other; } return append(other.elements); } public NutsTextStyles append(NutsTextStyle... others) { - if (others.length == 0) { + if (others==null || others.length == 0) { return this; } List all = new ArrayList(size() + others.length + 1); - for (NutsTextStyle i : elements) { - all.add(i); - } - for (NutsTextStyle i : others) { - if (i != null) { - all.add(i); - } - } - if (all.isEmpty()) { - return NONE; - } - return new NutsTextStyles(all.toArray(new NutsTextStyle[0])); + all.addAll(Arrays.asList(elements)); + all.addAll(Arrays.asList(others)); + return of(all.toArray(new NutsTextStyle[0])); } public NutsTextStyles append(NutsTextStyle other) { - if (other == null) { + if (other == null || other.getType()==NutsTextStyleType.PLAIN) { return this; } NutsTextStyle[] elements2 = new NutsTextStyle[elements.length + 1]; System.arraycopy(elements, 0, elements2, 0, elements.length); elements2[elements.length] = other; - return new NutsTextStyles(elements2); + return of(elements2); } public NutsTextStyles removeLast() { if (elements.length <= 0) { return this; } - return new NutsTextStyles(Arrays.copyOf(elements, elements.length - 1)); + return of(Arrays.copyOf(elements, elements.length - 1)); } public NutsTextStyles removeFirst() { if (elements.length <= 0) { return this; } - return new NutsTextStyles(Arrays.copyOfRange(elements, 1, elements.length)); + return of(Arrays.copyOfRange(elements, 1, elements.length)); } public NutsTextStyle get(int index) { @@ -116,10 +116,23 @@ public int size() { @Override public String toString() { - return Arrays.toString(elements); + return id(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + NutsTextStyles that = (NutsTextStyles) o; + return Arrays.equals(elements, that.elements); + } + + @Override + public int hashCode() { + return Arrays.hashCode(elements); } - public boolean isNone() { + public boolean isPlain() { return elements.length == 0; } @@ -129,4 +142,35 @@ public Iterator iterator() { } + public static NutsTextStyles parseLenient(String value) { + return parseLenient(value,null,null); + } + + public static NutsTextStyles parseLenient(String value, NutsTextStyles emptyValue) { + return parseLenient(value,emptyValue,emptyValue); + } + public static NutsTextStyles parseLenient(String value, NutsTextStyles emptyValue, NutsTextStyles errorValue) { + value = value.trim(); + List all=new ArrayList<>(); + for (String s : value.split(",")) { + s=s.trim(); + if(s.length()>0){ + NutsTextStyle a = NutsTextStyle.parseLenient(s, null, null); + if(a==null){ + return errorValue; + } + all.add(a); + } + } + return of(all.toArray(new NutsTextStyle[0])); + } + + + @Override + public String id() { + if (elements.length == 0) { + return "plain"; + } + return Arrays.stream(elements).map(NutsTextStyle::id).collect(Collectors.joining(",")); + } } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTexts.java similarity index 74% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsTextManager.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsTexts.java index 2ba2386ad..fa9093b4c 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTextManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsTexts.java @@ -1,21 +1,22 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; import java.util.Collection; /** * @app.category Format */ -public interface NutsTextManager { - static NutsTextManager of(NutsSession session) { +public interface NutsTexts extends NutsComponent { + static NutsTexts of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.text(); + return session.extensions().createSupported(NutsTexts.class,true,null); } NutsSession getSession(); - NutsTextManager setSession(NutsSession session); + NutsTexts setSession(NutsSession session); NutsTextBuilder builder(); @@ -55,15 +56,15 @@ static NutsTextManager of(NutsSession session) { NutsTextFormatTheme getTheme(); - NutsTextManager setTheme(NutsTextFormatTheme theme); + NutsTexts setTheme(NutsTextFormatTheme theme); - NutsTextManager setTheme(String themeName); + NutsTexts setTheme(String themeName); NutsCodeHighlighter getCodeHighlighter(String kind); - NutsTextManager addCodeHighlighter(NutsCodeHighlighter format); + NutsTexts addCodeHighlighter(NutsCodeHighlighter format); - NutsTextManager removeCodeHighlighter(String id); + NutsTexts removeCodeHighlighter(String id); NutsCodeHighlighter[] getCodeHighlighters(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTempAction.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTmp.java similarity index 83% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsTempAction.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsTmp.java index 0329367fa..7452f38c3 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTempAction.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsTmp.java @@ -26,18 +26,25 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + /** * @app.category Input Output */ -public interface NutsTempAction { +public interface NutsTmp extends NutsComponent { + static NutsTmp of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsTmp.class, true, null); + } String getRepositoryId(); - NutsTempAction setRepositoryId(String repositoryId); + NutsTmp setRepositoryId(String repositoryId); NutsSession getSession(); - NutsTempAction setSession(NutsSession session); + NutsTmp setSession(NutsSession session); /** * create temp file in the repositoryId's temp folder diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTreeFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTreeFormat.java index 4442f6a11..e78eb1cb8 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTreeFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsTreeFormat.java @@ -24,6 +24,8 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; + /** * Tree Format handles terminal output in Tree format. It is one of the many * formats supported bu nuts such as plain,table, xml, json. To use Tree format, @@ -37,6 +39,10 @@ * @app.category Format */ public interface NutsTreeFormat extends NutsObjectFormat { + static NutsTreeFormat of(NutsSession session){ + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsTreeFormat.class, true, null); + } /** * return node format diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsTypedFilters.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsTypedFilters.java index 30e474b0b..eb62953de 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsTypedFilters.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsTypedFilters.java @@ -25,6 +25,10 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.spi.NutsComponent; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; + /** * Filters helper * @@ -32,11 +36,8 @@ * @app.category Config * @since 0.8.0 */ -public interface NutsTypedFilters { - NutsSession getSession(); - - NutsTypedFilters setSession(NutsSession session); - +@NutsComponentScope(NutsComponentScopeType.SESSION) +public interface NutsTypedFilters extends NutsComponent { T nonnull(NutsFilter filter); T always(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOUncompressAction.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsUncompress.java similarity index 78% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsIOUncompressAction.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsUncompress.java index ca04cd320..8a3cd86e2 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsIOUncompressAction.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsUncompress.java @@ -25,6 +25,9 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + import java.io.File; import java.io.InputStream; import java.net.URL; @@ -36,7 +39,12 @@ * @since 0.5.8 * @app.category Input Output */ -public interface NutsIOUncompressAction { +public interface NutsUncompress extends NutsComponent { + static NutsUncompress of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsUncompress.class, true, null); + } + /** * format * @return format @@ -48,7 +56,7 @@ public interface NutsIOUncompressAction { * @param format format * @return {@code this} instance */ - NutsIOUncompressAction setFormat(String format); + NutsUncompress setFormat(String format); /** * update format option @@ -56,7 +64,7 @@ public interface NutsIOUncompressAction { * @param value value * @return {@code this} instance */ - NutsIOUncompressAction setFormatOption(String option, Object value); + NutsUncompress setFormatOption(String option, Object value); /** * return format option @@ -76,64 +84,64 @@ public interface NutsIOUncompressAction { * @param source source to uncompress from * @return {@code this} instance */ - NutsIOUncompressAction setSource(InputStream source); + NutsUncompress setSource(InputStream source); /** * update source to uncompress from * @param source source to uncompress from * @return {@code this} instance */ - NutsIOUncompressAction setSource(NutsPath source); + NutsUncompress setSource(NutsPath source); /** * update source to uncompress from * @param source source to uncompress from * @return {@code this} instance */ - NutsIOUncompressAction setSource(File source); + NutsUncompress setSource(File source); /** * update source to uncompress from * @param source source to uncompress from * @return {@code this} instance */ - NutsIOUncompressAction setSource(Path source); + NutsUncompress setSource(Path source); /** * update source to uncompress from * @param source source to uncompress from * @return {@code this} instance */ - NutsIOUncompressAction setSource(URL source); + NutsUncompress setSource(URL source); /** * update source to uncompress from * @param source source to uncompress from * @return {@code this} instance */ - NutsIOUncompressAction from(InputStream source); + NutsUncompress from(InputStream source); /** * update source to uncompress from * @param source source to uncompress from * @return {@code this} instance */ - NutsIOUncompressAction from(File source); + NutsUncompress from(File source); /** * update source to uncompress from * @param source source to uncompress from * @return {@code this} instance */ - NutsIOUncompressAction from(Path source); + NutsUncompress from(Path source); /** * update source to uncompress from * @param source source to uncompress from * @return {@code this} instance */ - NutsIOUncompressAction from(URL source); + NutsUncompress from(URL source); - NutsIOUncompressAction to(NutsPath target); + NutsUncompress to(NutsPath target); /** * target to uncompress to @@ -146,58 +154,58 @@ public interface NutsIOUncompressAction { * @param target target * @return {@code this} instance */ - NutsIOUncompressAction setTarget(Path target); + NutsUncompress setTarget(Path target); /** * update target * @param target target * @return {@code this} instance */ - NutsIOUncompressAction setTarget(File target); + NutsUncompress setTarget(File target); /** * update target * @param target target * @return {@code this} instance */ - NutsIOUncompressAction setTarget(String target); + NutsUncompress setTarget(String target); - NutsIOUncompressAction setTarget(NutsPath target); + NutsUncompress setTarget(NutsPath target); /** * update source to uncompress from * @param source source to uncompress from * @return {@code this} instance */ - NutsIOUncompressAction from(String source); + NutsUncompress from(String source); /** * update target * @param target target * @return {@code this} instance */ - NutsIOUncompressAction to(String target); + NutsUncompress to(String target); /** * update target * @param target target * @return {@code this} instance */ - NutsIOUncompressAction to(Path target); + NutsUncompress to(Path target); /** * update target * @param target target * @return {@code this} instance */ - NutsIOUncompressAction to(File target); + NutsUncompress to(File target); /** * update source to uncompress from * @param source source to uncompress from * @return {@code this} instance */ - NutsIOUncompressAction from(NutsPath source); + NutsUncompress from(NutsPath source); /** * return current session @@ -210,15 +218,15 @@ public interface NutsIOUncompressAction { * @param session current session * @return {@code this} instance */ - NutsIOUncompressAction setSession(NutsSession session); + NutsUncompress setSession(NutsSession session); /** * run this uncompress action * @return {@code this} instance */ - NutsIOUncompressAction run(); + NutsUncompress run(); - NutsIOUncompressAction visit(NutsIOUncompressVisitor visitor); + NutsUncompress visit(NutsIOUncompressVisitor visitor); /** * true if log progress flag is armed @@ -231,7 +239,7 @@ public interface NutsIOUncompressAction { * @param value value * @return {@code this} instance */ - NutsIOUncompressAction setLogProgress(boolean value); + NutsUncompress setLogProgress(boolean value); /** * return true if skip root flag is armed. @@ -248,7 +256,7 @@ public interface NutsIOUncompressAction { * @return {@code this} instance * @since 0.5.8 */ - NutsIOUncompressAction setSkipRoot(boolean value); + NutsUncompress setSkipRoot(boolean value); /** * return progress factory responsible of creating progress monitor @@ -265,7 +273,7 @@ public interface NutsIOUncompressAction { * @return {@code this} instance * @since 0.5.8 */ - NutsIOUncompressAction setProgressMonitorFactory(NutsProgressFactory value); + NutsUncompress setProgressMonitorFactory(NutsProgressFactory value); /** * set progress monitor. Will create a singleton progress monitor factory @@ -274,7 +282,7 @@ public interface NutsIOUncompressAction { * @return {@code this} instance * @since 0.5.8 */ - NutsIOUncompressAction setProgressMonitor(NutsProgressMonitor value); + NutsUncompress setProgressMonitor(NutsProgressMonitor value); /** * set progress monitor. Will create a singleton progress monitor factory @@ -283,7 +291,7 @@ public interface NutsIOUncompressAction { * @return {@code this} instance * @since 0.5.8 */ - NutsIOUncompressAction progressMonitor(NutsProgressMonitor value); + NutsUncompress progressMonitor(NutsProgressMonitor value); /** * return true if safe flag is armed @@ -296,5 +304,5 @@ public interface NutsIOUncompressAction { * @param value value * @return {@code this} instance */ - NutsIOUncompressAction setSafe(boolean value); + NutsUncompress setSafe(boolean value); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsUtilManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsUtilManager.java deleted file mode 100644 index 60eacb2cc..000000000 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsUtilManager.java +++ /dev/null @@ -1,28 +0,0 @@ -package net.thevpc.nuts; - -import net.thevpc.nuts.boot.NutsApiUtils; - -import java.util.stream.Stream; - -/** - * @app.category Format - */ -public interface NutsUtilManager { - static NutsUtilManager of(NutsSession session) { - NutsApiUtils.checkSession(session); - return session.util(); - } - - NutsSession getSession(); - - NutsUtilManager setSession(NutsSession session); - - NutsVal valOf(Object str); - - NutsStream streamOf(T[] str, String name); - - NutsStream streamOf(Iterable str, String name); - - NutsStream streamOf(Stream str, String name); - -} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsVal.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsVal.java index 9b75a130c..c0df215c1 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsVal.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsVal.java @@ -32,7 +32,6 @@ * @see net.thevpc.nuts.NutsArgument * @see net.thevpc.nuts.NutsBootManager * @see net.thevpc.nuts.NutsWorkspaceEnvManager - * @see net.thevpc.nuts.NutsUtilManager */ public interface NutsVal extends NutsBlankable { /** @@ -42,7 +41,7 @@ public interface NutsVal extends NutsBlankable { * @return a wrapped instance for the given value */ static NutsVal of(Object value, NutsSession session) { - return session.util().valOf(value); + return NutsVals.of(session).of(value); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsVals.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsVals.java new file mode 100644 index 000000000..c772c9712 --- /dev/null +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsVals.java @@ -0,0 +1,14 @@ +package net.thevpc.nuts; + +import net.thevpc.nuts.spi.NutsComponent; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; + +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) +public interface NutsVals extends NutsComponent { + static NutsVals of(NutsSession session) { + return session.extensions().createSupported(NutsVals.class, true, session); + } + + NutsVal of(Object str); +} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsVersion.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsVersion.java index c3e45abf9..c8cce22a1 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsVersion.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsVersion.java @@ -26,6 +26,7 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsPaths; import java.io.Serializable; import java.math.BigInteger; @@ -53,8 +54,10 @@ public interface NutsVersion extends Serializable, /*NutsTokenFilter, */NutsForm * @return parsed value */ static NutsVersion of(String str, NutsSession session) { - NutsApiUtils.checkSession(session); - return session.version().parse(str); + return + NutsApiUtils + .createSessionCachedType(NutsVersionParser.class, session,()->NutsVersionParser.of(session)) + .parse(str); } /** diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionFilterManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionFilters.java similarity index 74% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsVersionFilterManager.java rename to core/nuts/src/main/java/net/thevpc/nuts/NutsVersionFilters.java index ae95b1fda..0d8167c06 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionFilterManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionFilters.java @@ -24,14 +24,19 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; + /** * @app.category Base */ -public interface NutsVersionFilterManager extends NutsTypedFilters { - - NutsVersionFilterManager setSession(NutsSession session); +@NutsComponentScope(NutsComponentScopeType.SESSION) +public interface NutsVersionFilters extends NutsTypedFilters { + static NutsVersionFilters of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsVersionFilters.class,true,null); + } NutsVersionFilter byValue(String version); - - NutsVersionFilter byExpression(String expression); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionFormat.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionFormat.java index d954bd69c..7d1e77c0f 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionFormat.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionFormat.java @@ -25,6 +25,9 @@ */ package net.thevpc.nuts; +import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; + import java.util.Map; /** @@ -33,7 +36,12 @@ * @since 0.5.4 * @app.category Format */ -public interface NutsVersionFormat extends NutsFormat { +public interface NutsVersionFormat extends NutsFormat, NutsComponent { + + static NutsVersionFormat of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsVersionFormat.class, true,null); + } /** * update session diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionManager.java deleted file mode 100644 index 185a5898b..000000000 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionManager.java +++ /dev/null @@ -1,58 +0,0 @@ -/** - * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) - *
    - * is a new Open Source Package Manager to help install packages - * and libraries for runtime execution. Nuts is the ultimate companion for - * maven (and other build managers) as it helps installing all package - * dependencies at runtime. Nuts is not tied to java and is a good choice - * to share shell scripts and other 'things' . Its based on an extensible - * architecture to help supporting a large range of sub managers / repositories. - * - *
    - *

    - * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a - * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language - * governing permissions and limitations under the License. - *
    - * ==================================================================== - */ -package net.thevpc.nuts; - -/** - * version manager is responsible of parsing and formatting versons - * @app.category Base - */ -public interface NutsVersionManager { - - /** - * parse the version to empty version if blank, a valid instance if parse succeeds or throws an error - * @param version id to parse - * @return parsed version to a valid instance or throws an error - */ - NutsVersion parse(String version); - - - /** - * return new parser that accepts blank values but throws errors when the version is invalid - * @return new parser that accepts blank values but throws errors when the version is invalid - */ - NutsVersionParser parser(); - - NutsVersionFormat formatter(); - - NutsVersionFormat formatter(NutsVersion version); - - NutsVersionFilterManager filter(); - - NutsSession getSession(); - - NutsVersionManager setSession(NutsSession session); -} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionParser.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionParser.java index 2cfee34f0..02eda14f1 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionParser.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsVersionParser.java @@ -27,15 +27,16 @@ package net.thevpc.nuts; import net.thevpc.nuts.boot.NutsApiUtils; +import net.thevpc.nuts.spi.NutsComponent; /** * @app.category Base */ -public interface NutsVersionParser { +public interface NutsVersionParser extends NutsComponent { - static NutsVersionParser parse(NutsSession session) { + static NutsVersionParser of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.version().parser(); + return session.extensions().createSupported(NutsVersionParser.class, true,null); } /** @@ -58,6 +59,7 @@ static NutsVersionParser parse(NutsSession session) { boolean isAcceptIntervals(); NutsVersionParser setAcceptIntervals(boolean acceptIntervals); + /** * return version instance representing the {@code version} string * diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspace.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspace.java index 43d89bb3d..13e013f39 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspace.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspace.java @@ -27,8 +27,6 @@ import net.thevpc.nuts.spi.NutsComponent; -import java.util.Set; - /** * Created by vpc on 1/5/17. * @@ -86,8 +84,6 @@ public interface NutsWorkspace extends NutsComponent { ///////////////////// sub system - NutsWorkspaceAppsManager apps(); - NutsWorkspaceExtensionManager extensions(); NutsWorkspaceConfigManager config(); @@ -96,33 +92,8 @@ public interface NutsWorkspace extends NutsComponent { NutsWorkspaceSecurityManager security(); - NutsFilterManager filters(); - - NutsIOManager io(); - - NutsLogManager log(); - - NutsWorkspaceEventManager events(); - NutsCommandLineManager commandLine(); - - /** - * create id format instance - * - * @return id format - * @since 0.5.5 - */ - NutsIdManager id(); - - /** - * create version format instance - * - * @return version format - * @since 0.5.5 - */ - NutsVersionManager version(); - /** * create info format instance * @@ -131,28 +102,8 @@ public interface NutsWorkspace extends NutsComponent { */ NutsInfoFormat info(); - /** - * create descriptor format instance - * - * @return descriptor format - * @since 0.5.5 - */ - NutsDescriptorManager descriptor(); - - /** - * return dependency manager - * - * @return dependency manager - * @since 0.8.0 - */ - NutsDependencyManager dependency(); - NutsFormatManager formats(); - NutsConcurrentManager concurrent(); - - NutsUtilManager util(); - NutsImportManager imports(); NutsCustomCommandManager commands(); @@ -163,15 +114,4 @@ public interface NutsWorkspace extends NutsComponent { NutsBootManager boot(); - NutsTerminalManager term(); - - NutsTextManager text(); - - /** - * create element format instance - * - * @return element format - * @since 0.5.5 - */ - NutsElementFormat elem(); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceConfigManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceConfigManager.java index 8e766e991..3a963a333 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceConfigManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceConfigManager.java @@ -26,8 +26,10 @@ package net.thevpc.nuts; import net.thevpc.nuts.spi.NutsIndexStoreFactory; +import net.thevpc.nuts.spi.NutsSystemTerminalBase; import java.util.Set; +import java.util.concurrent.ExecutorService; /** * @author thevpc @@ -85,4 +87,35 @@ public interface NutsWorkspaceConfigManager { String getHashName(Object o); String getWorkspaceHashName(String path); + + ExecutorService executorService(); + + /** + * return workspace system terminal. + * + * @return workspace system terminal + */ + NutsSystemTerminal getSystemTerminal(); + + /** + * update workspace wide system terminal + * + * @param terminal system terminal + * @return {@code this} instance + */ + NutsWorkspaceConfigManager setSystemTerminal(NutsSystemTerminalBase terminal); + /** + * return workspace default terminal + * + * @return workspace default terminal + */ + NutsSessionTerminal getDefaultTerminal(); + + /** + * update workspace wide terminal + * + * @param terminal terminal + * @return {@code this} instance + */ + NutsWorkspaceConfigManager setDefaultTerminal(NutsSessionTerminal terminal); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceExtensionManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceExtensionManager.java index 4e09b622f..15f81a68f 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceExtensionManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceExtensionManager.java @@ -54,23 +54,11 @@ public interface NutsWorkspaceExtensionManager { * @param extension type class * @param extension context type * @param type extension type + * @param required * @param supportCriteria context * @return valid instance or null if no extension implementation was found */ - , V> T createSupported(Class type, V supportCriteria); - - /** - * create supported extension implementation or return null. - * - * @param extension type class - * @param extension context type - * @param type extension type - * @param supportCriteria context - * @param constructorParameterTypes constructor Parameter Types - * @param constructorParameters constructor Parameters - * @return valid instance or null if no extension implementation was found - */ - , V> T createSupported(Class type, V supportCriteria, Class[] constructorParameterTypes, Object[] constructorParameters); + , V> T createSupported(Class type, boolean required, V supportCriteria); , V> List createAllSupported(Class type, V supportCriteria); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceLocationManager.java b/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceLocationManager.java index 0d37d1138..cf02de243 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceLocationManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/NutsWorkspaceLocationManager.java @@ -77,7 +77,7 @@ public interface NutsWorkspaceLocationManager { String getHomeLocation(NutsHomeLocation location); - String getWorkspaceLocation(); + NutsPath getWorkspaceLocation(); NutsWorkspaceLocationManager setStoreLocation(NutsStoreLocation folderType, String location); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/boot/NutsApiUtils.java b/core/nuts/src/main/java/net/thevpc/nuts/boot/NutsApiUtils.java index 42a4bd60d..af1896657 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/boot/NutsApiUtils.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/boot/NutsApiUtils.java @@ -5,6 +5,7 @@ import java.io.PrintStream; import java.net.URL; import java.util.Arrays; +import java.util.function.Supplier; import java.util.logging.Level; /** @@ -33,7 +34,7 @@ public static boolean isBlank(char[] string) { public static void checkSession(NutsSession session) { if (session == null) { - throw new IllegalArgumentException("missing session"); + throw new NutsMissingSessionException(); } } @@ -65,25 +66,26 @@ public static String resolveNutsIdDigestOrError() { String d = resolveNutsIdDigest(); if (d == null) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); - URL[] urls = PrivateNutsUtilClassLoader.resolveClasspathURLs(cl,true); + URL[] urls = PrivateNutsUtilClassLoader.resolveClasspathURLs(cl, true); throw new NutsBootException( NutsMessage.plain( "unable to detect nuts digest. Most likely you are missing valid compilation of nuts." + "\n\t 'pom.properties' could not be resolved and hence, we are unable to resolve nuts version." + - "\n\t java="+ System.getProperty("java.home")+ " as "+System.getProperty("java.version")+ - "\n\t class-path="+ System.getProperty("java.class.path")+ - "\n\t urls="+ Arrays.toString(urls)+ - "\n\t class-loader="+ cl.getClass().getName()+" as "+cl + "\n\t java=" + System.getProperty("java.home") + " as " + System.getProperty("java.version") + + "\n\t class-path=" + System.getProperty("java.class.path") + + "\n\t urls=" + Arrays.toString(urls) + + "\n\t class-loader=" + cl.getClass().getName() + " as " + cl ) ); } return d; } + public static String resolveNutsIdDigest() { return resolveNutsIdDigest( new NutsBootId("net.thevpc.nuts", "nuts", NutsBootVersion.parse(Nuts.getVersion())), - PrivateNutsUtilClassLoader.resolveClasspathURLs(Thread.currentThread().getContextClassLoader(),true) + PrivateNutsUtilClassLoader.resolveClasspathURLs(Thread.currentThread().getContextClassLoader(), true) ); } @@ -142,4 +144,24 @@ public static Integer parseInt(String value, Integer emptyValue, Integer errorVa public static Integer parseFileSizeInBytes(String value, Integer defaultMultiplier, Integer emptyValue, Integer errorValue) { return PrivateNutsUtils.parseFileSizeInBytes(value, defaultMultiplier, emptyValue, errorValue); } + + public static T createSessionCachedType(String name, Class t, NutsSession session, Supplier sup) { + checkSession(session); + name = NutsUtilStrings.trim(name); + if (NutsBlankable.isBlank(name)) { + name = "default"; + } + String key = t + "." + name + "." + "." + System.identityHashCode(session); + Object v = session.getProperty(key); + if (v != null && t.isInstance(v)) { + return (T) v; + } + v = sup.get(); + session.setProperty(key, v); + return (T) v; + } + + public static T createSessionCachedType(Class t, NutsSession session, Supplier sup) { + return createSessionCachedType("default", t, session, sup); + } } \ No newline at end of file diff --git a/core/nuts/src/main/java/net/thevpc/nuts/boot/NutsBootWorkspace.java b/core/nuts/src/main/java/net/thevpc/nuts/boot/NutsBootWorkspace.java index 75803babf..0d9e94b33 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/boot/NutsBootWorkspace.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/boot/NutsBootWorkspace.java @@ -27,6 +27,7 @@ import net.thevpc.nuts.spi.NutsBootWorkspaceFactory; import java.io.*; +import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; @@ -759,7 +760,6 @@ public NutsSession openWorkspace() { } boolean recover = options.isRecover() || options.isReset(); -// LinkedHashMap allExtensionFiles = new LinkedHashMap<>(); List deps = new ArrayList<>(); String workspaceBootLibFolder = workspaceInformation.getLib(); @@ -769,51 +769,13 @@ public NutsSession openWorkspace() { .split("[\n;]") ).map(String::trim).filter(x -> x.length() > 0).toArray(String[]::new); - NutsClassLoaderNodeBuilder rt = new NutsClassLoaderNodeBuilder(); - File runtimeJarFile = PrivateNutsUtilMaven.getBootCacheJar(workspaceInformation.getRuntimeId(), repositories, workspaceBootLibFolder, !recover, "runtime", options.getExpireTime(), errorList, workspaceInformation, pathExpansionConverter, LOG); - - if (LOG.isLoggable(Level.CONFIG)) { - String rtHash = ""; - if (workspaceInformation.getRuntimeId() != null) { - rtHash = PrivateNutsUtilDigest.getFileOrDirectoryDigest(runtimeJarFile.toPath()); - if (rtHash == null) { - rtHash = ""; - } - } - LOG.log(Level.CONFIG, NutsLogVerb.INFO, NutsMessage.jstyle("detect nuts-runtime version {0} - digest {1} from {2}", workspaceInformation.getRuntimeId(), rtHash, runtimeJarFile)); - } - - rt.setId(workspaceInformation.getRuntimeId().toString()) - .setUrl(runtimeJarFile - .toURI().toURL()); - for (NutsBootId s : workspaceInformation.getRuntimeBootDescriptor().getDependencies()) { - NutsClassLoaderNodeBuilder x = new NutsClassLoaderNodeBuilder(); - if (PrivateNutsUtilBootId.isAcceptDependency(s, workspaceInformation.getOptions())) { - x.setId(s.toString()) - .setUrl(PrivateNutsUtilMaven.getBootCacheJar(s, repositories, workspaceBootLibFolder, !recover, "runtime dependency", options.getExpireTime(), errorList, workspaceInformation, pathExpansionConverter, LOG) - .toURI().toURL() - ); - rt.addDependency(x.build()); - } - } - workspaceInformation.setRuntimeBootDependencyNode(rt.build()); + workspaceInformation.setRuntimeBootDependencyNode( + createClassLoaderNode(workspaceInformation.getRuntimeBootDescriptor(), + repositories, workspaceBootLibFolder, recover, errorList, true)); for (NutsBootDescriptor nutsBootDescriptor : workspaceInformation.getExtensionBootDescriptors()) { - NutsClassLoaderNodeBuilder rt2 = new NutsClassLoaderNodeBuilder(); - rt2.setId(nutsBootDescriptor.getId().toString()) - .setUrl(PrivateNutsUtilMaven.getBootCacheJar(workspaceInformation.getRuntimeId(), repositories, workspaceBootLibFolder, !recover, "extension " + nutsBootDescriptor.getId(), options.getExpireTime(), errorList, workspaceInformation, pathExpansionConverter, LOG) - .toURI().toURL()); - for (NutsBootId s : nutsBootDescriptor.getDependencies()) { - if (PrivateNutsUtilBootId.isAcceptDependency(s, workspaceInformation.getOptions())) { - NutsClassLoaderNodeBuilder x = new NutsClassLoaderNodeBuilder(); - x.setId(s.toString()) - .setUrl(PrivateNutsUtilMaven.getBootCacheJar(s, repositories, workspaceBootLibFolder, !recover, "extension " + nutsBootDescriptor.getId() + " dependency", options.getExpireTime(), errorList, workspaceInformation, pathExpansionConverter, LOG) - .toURI().toURL() - ); - rt2.addDependency(x.build()); - } - } - deps.add(rt2.build()); + deps.add(createClassLoaderNode(nutsBootDescriptor,repositories, workspaceBootLibFolder, recover, + errorList, false)); } workspaceInformation.setExtensionBootDependencyNodes(deps.toArray(new NutsClassLoaderNode[0])); deps.add(0, workspaceInformation.getRuntimeBootDependencyNode()); @@ -1138,7 +1100,7 @@ public NutsSession runWorkspace() { session.setAppId(workspace.getApiId()); if (LOG2 == null) { - LOG2 = session.log().of(NutsBootWorkspace.class); + LOG2 = NutsLogger.of(NutsBootWorkspace.class,session); LOG2_SESSION = session; } NutsLoggerOp logOp = LOG2.with().session(session).level(Level.CONFIG); @@ -1353,4 +1315,49 @@ public String getRequirementsHelpString(boolean unsatisfiedOnly) { return null; } + private NutsClassLoaderNode createClassLoaderNode(NutsBootDescriptor descr,String[] repositories, + String workspaceBootLibFolder,boolean recover,PrivateNutsErrorInfoList errorList, + boolean runtimeDep + ) throws MalformedURLException { + NutsBootId id=descr.getId(); + NutsBootId[] deps=descr.getDependencies(); + NutsClassLoaderNodeBuilder rt = new NutsClassLoaderNodeBuilder(); + String name=runtimeDep?"runtime":("extension " + id.toString()); + File file=PrivateNutsUtilMaven.getBootCacheJar(workspaceInformation.getRuntimeId(), repositories, workspaceBootLibFolder, + !recover, name, options.getExpireTime(), errorList, + workspaceInformation, pathExpansionConverter, LOG); + rt.setId(id.toString()); + rt.setUrl(file.toURI().toURL()); + rt.setIncludedInClasspath( + PrivateNutsUtilClassLoader.isLoadedClassPath( + rt.getURL(),getContextClassLoader(), LOG)); + + if (LOG.isLoggable(Level.CONFIG)) { + String rtHash = ""; + if (workspaceInformation.getRuntimeId() != null) { + rtHash = PrivateNutsUtilDigest.getFileOrDirectoryDigest(file.toPath()); + if (rtHash == null) { + rtHash = ""; + } + } + LOG.log(Level.CONFIG, NutsLogVerb.INFO, NutsMessage.jstyle("detect "+name+" version {0} - digest {1} from {2}", id.toString(), rtHash, file)); + } + + for (NutsBootId s : deps) { + NutsClassLoaderNodeBuilder x = new NutsClassLoaderNodeBuilder(); + if (PrivateNutsUtilBootId.isAcceptDependency(s, workspaceInformation.getOptions())) { + x.setId(s.toString()) + .setUrl(PrivateNutsUtilMaven.getBootCacheJar(s, repositories, workspaceBootLibFolder, !recover, + name+" dependency", + options.getExpireTime(), errorList, workspaceInformation, pathExpansionConverter, LOG) + .toURI().toURL() + ); + x.setIncludedInClasspath(PrivateNutsUtilClassLoader.isLoadedClassPath( + x.getURL(),getContextClassLoader(), LOG)); + rt.addDependency(x.build()); + } + } + return rt.build(); + } + } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsArgumentImpl.java b/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsArgumentImpl.java index c50cf2c1b..73e2f5e95 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsArgumentImpl.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsArgumentImpl.java @@ -1,7 +1,7 @@ package net.thevpc.nuts.boot; import net.thevpc.nuts.NutsArgument; -import net.thevpc.nuts.NutsCommandLineManager; +import net.thevpc.nuts.NutsCommandLines; import net.thevpc.nuts.NutsUtilStrings; import net.thevpc.nuts.NutsVal; @@ -10,7 +10,7 @@ /** * This is a minimal implementation of NutsArgument and hence should not be * used. Instead an instance of NutsArgument can be retrieved using - * {@link NutsCommandLineManager#createArgument(String)} + * {@link NutsCommandLines#createArgument(String)} * * @author thevpc * @app.category Format diff --git a/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsUtilApplication.java b/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsUtilApplication.java index 98aef46d0..80d51bed8 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsUtilApplication.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsUtilApplication.java @@ -95,14 +95,14 @@ public static int processThrowable(Throwable ex, PrintStream out, boolean showMe if (out == null) { if (session != null) { try { - fout = session.term().getSystemTerminal().getErr(); + fout = session.config().getSystemTerminal().getErr(); if (fm != null) { - fm = session.text().ofStyled(fm, NutsTextStyle.error()); + fm = NutsTexts.of(session).ofStyled(fm, NutsTextStyle.error()); } else { - fm = session.text().ofStyled(m, NutsTextStyle.error()); + fm = NutsTexts.of(session).ofStyled(m, NutsTextStyle.error()); } } catch (Exception ex2) { - session.log().of(NutsApplications.class).with().level(Level.FINE).error(ex2).log( + NutsLoggerOp.of(NutsApplications.class,session).level(Level.FINE).error(ex2).log( NutsMessage.jstyle("unable to get system terminal") ); // @@ -118,7 +118,7 @@ public static int processThrowable(Throwable ex, PrintStream out, boolean showMe } } else { if (session != null) { - fout = session.io().createPrintStream(out, NutsTerminalMode.FORMATTED); + fout = NutsPrintStream.of(out, NutsTerminalMode.FORMATTED,session); } else { fout = null; } @@ -138,14 +138,14 @@ public static int processThrowable(Throwable ex, PrintStream out, boolean showMe fout.flush(); } else { if (fm != null) { - session.eout().add(session.elem().forObject() + session.eout().add(NutsElements.of(session).forObject() .set("app-id", session.getAppId() == null ? "" : session.getAppId().toString()) .set("error", fm.filteredText()) .build() ); if (showTrace) { - session.eout().add(session.elem().forObject().set("error-trace", - session.elem().forArray().addAll(PrivateNutsUtils.stacktraceToArray(ex)).build() + session.eout().add(NutsElements.of(session).forObject().set("errorTrace", + NutsElements.of(session).forArray().addAll(PrivateNutsUtils.stacktraceToArray(ex)).build() ).build()); } NutsArrayElementBuilder e = session.eout(); @@ -155,13 +155,13 @@ public static int processThrowable(Throwable ex, PrintStream out, boolean showMe } fout.flush(); } else { - session.eout().add(session.elem().forObject() + session.eout().add(NutsElements.of(session).forObject() .set("app-id", session.getAppId() == null ? "" : session.getAppId().toString()) .set("error", m) .build()); if (showTrace) { - session.eout().add(session.elem().forObject().set("error-trace", - session.elem().forArray().addAll(PrivateNutsUtils.stacktraceToArray(ex)).build() + session.eout().add(NutsElements.of(session).forObject().set("errorTrace", + NutsElements.of(session).forArray().addAll(PrivateNutsUtils.stacktraceToArray(ex)).build() ).build()); } NutsArrayElementBuilder e = session.eout(); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsUtilClassLoader.java b/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsUtilClassLoader.java index f01a22a18..bd2638289 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsUtilClassLoader.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/boot/PrivateNutsUtilClassLoader.java @@ -16,27 +16,26 @@ import java.util.zip.ZipFile; class PrivateNutsUtilClassLoader { - private static void fillBootDependencyNodes(NutsClassLoaderNode node, Set urls) { - urls.add(node.getURL()); - for (NutsClassLoaderNode dependency : node.getDependencies()) { - fillBootDependencyNodes(dependency, urls); + private static void fillBootDependencyNodes(NutsClassLoaderNode node, Set urls, Set visitedIds,PrivateNutsLog LOG) { + String shortName = NutsBootId.parse(node.getId()).getShortName(); + if(!visitedIds.contains(shortName)){ + visitedIds.add(shortName); + if(!node.isIncludedInClasspath()) { + urls.add(node.getURL()); + }else{ + LOG.log(Level.WARNING, NutsLogVerb.CACHE, NutsMessage.jstyle("url will not be loaded (already in classloader) : {0}", node.getURL())); + } + for (NutsClassLoaderNode dependency : node.getDependencies()) { + fillBootDependencyNodes(dependency, urls,visitedIds,LOG); + } } } static URL[] resolveClassWorldURLs(NutsClassLoaderNode[] nodes, ClassLoader contextClassLoader, PrivateNutsLog LOG) { - LinkedHashSet urls0 = new LinkedHashSet<>(); + LinkedHashSet urls = new LinkedHashSet<>(); + Set visitedIds=new HashSet<>(); for (NutsClassLoaderNode info : nodes) { - fillBootDependencyNodes(info, urls0); - } - List urls = new ArrayList<>(); - for (URL url0 : urls0) { - if (url0 != null) { - if (isLoadedClassPath(url0, contextClassLoader, LOG)) { - LOG.log(Level.WARNING, NutsLogVerb.CACHE, NutsMessage.jstyle("url will not be loaded (already in classloader) : {0}", url0)); - } else { - urls.add(url0); - } - } + fillBootDependencyNodes(info, urls,visitedIds,LOG); } return urls.toArray(new URL[0]); } @@ -107,7 +106,7 @@ public static URL[] resolveClasspathURLs(ClassLoader contextClassLoader, boolean return all.toArray(new URL[0]); } - private static boolean isLoadedClassPath(URL url, ClassLoader contextClassLoader, PrivateNutsLog LOG) { + public static boolean isLoadedClassPath(URL url, ClassLoader contextClassLoader, PrivateNutsLog LOG) { try { if (url != null) { if (contextClassLoader == null) { diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsDefaultArgumentCandidate.java b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsComponentScope.java old mode 100755 new mode 100644 similarity index 64% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsDefaultArgumentCandidate.java rename to core/nuts/src/main/java/net/thevpc/nuts/spi/NutsComponentScope.java index f6d1b976f..da12e098f --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsDefaultArgumentCandidate.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsComponentScope.java @@ -24,39 +24,22 @@ *
    * ==================================================================== */ -package net.thevpc.nuts; +package net.thevpc.nuts.spi; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; /** - * Default (simple) NutsArgumentCandidate implementation. - * @author thevpc - * @since 0.5.5 + * classes that are marked with this annotation will be created once by the + * factory. + * + * @since 0.5.4 + * @app.category SPI Base */ -public class NutsDefaultArgumentCandidate implements NutsArgumentCandidate { - - private final String value; - private final String display; - - /** - * - * @param value value - */ - public NutsDefaultArgumentCandidate(String value) { - this.value = value; - this.display = value; - } - - public NutsDefaultArgumentCandidate(String value, String display) { - this.value = value; - this.display = display; - } - - @Override - public String getValue() { - return value; - } - - @Override - public String getDisplay() { - return display; - } +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.TYPE) +public @interface NutsComponentScope { + NutsComponentScopeType value() default NutsComponentScopeType.PROTOTYPE; } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsComponentScopeType.java b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsComponentScopeType.java new file mode 100644 index 000000000..73e4a7757 --- /dev/null +++ b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsComponentScopeType.java @@ -0,0 +1,129 @@ +/** + * ==================================================================== + * Nuts : Network Updatable Things Service + * (universal package manager) + *
    + * is a new Open Source Package Manager to help install packages + * and libraries for runtime execution. Nuts is the ultimate companion for + * maven (and other build managers) as it helps installing all package + * dependencies at runtime. Nuts is not tied to java and is a good choice + * to share shell scripts and other 'things' . Its based on an extensible + * architecture to help supporting a large range of sub managers / repositories. + * + *
    + *

    + * Copyright [2020] [thevpc] + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a + * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + *
    + * ==================================================================== + */ +package net.thevpc.nuts.spi; + +import net.thevpc.nuts.NutsEnum; +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.boot.NutsApiUtils; + +/** + * Modes Application can run with + * + * @app.category Application + * @since 0.5.5 + */ +public enum NutsComponentScopeType implements NutsEnum { + /** + * a new instance will be created per workspace reference + */ + WORKSPACE, + /** + * a new instance will be created per session reference + */ + SESSION, + /** + * a new instance will be created at each call + */ + PROTOTYPE; + + /** + * lower-cased identifier for the enum entry + */ + private final String id; + + /** + * default constructor + */ + NutsComponentScopeType() { + this.id = name().toLowerCase().replace('_', '-'); + } + + /** + * parse string and return null if parse fails + * + * @param value value to parse + * @return parsed instance or null + */ + public static NutsComponentScopeType parseLenient(String value) { + return parseLenient(value, null); + } + + /** + * parse string and return {@code emptyOrErrorValue} if parse fails + * + * @param emptyOrErrorValue emptyOrErrorValue + * @param value value to parse + * @return parsed instance or {@code emptyOrErrorValue} + */ + public static NutsComponentScopeType parseLenient(String value, NutsComponentScopeType emptyOrErrorValue) { + return parseLenient(value, emptyOrErrorValue, emptyOrErrorValue); + } + + /** + * parse string and return {@code emptyValue} when null or {@code errorValue} if parse fails + * + * @param value value to parse + * @param emptyValue value when the value is null or empty + * @param errorValue value when the value cannot be parsed + * @return parsed value + */ + public static NutsComponentScopeType parseLenient(String value, NutsComponentScopeType emptyValue, NutsComponentScopeType errorValue) { + if (value == null) { + value = ""; + } else { + value = value.toUpperCase().trim().replace('-', '_'); + } + if (value.isEmpty()) { + return emptyValue; + } + try { + return NutsComponentScopeType.valueOf(value.toUpperCase()); + } catch (Exception notFound) { + return errorValue; + } + } + + public static NutsComponentScopeType parse(String value, NutsSession session) { + return parse(value, null, session); + } + + public static NutsComponentScopeType parse(String value, NutsComponentScopeType emptyValue, NutsSession session) { + NutsComponentScopeType v = parseLenient(value, emptyValue, null); + NutsApiUtils.checkNonNullEnum(v,value, NutsComponentScopeType.class,session); + return v; + } + + /** + * lower cased identifier. + * + * @return lower cased identifier + */ + public String id() { + return id; + } + +} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsDependencySolver.java b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsDependencySolver.java index 63d655a5b..fb30dc5b4 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsDependencySolver.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsDependencySolver.java @@ -36,6 +36,18 @@ */ public interface NutsDependencySolver{ + static NutsDependencySolver of(NutsSession session){ + return NutsDependencySolvers.of(session).createSolver(session); + } + + static NutsDependencySolver of(String solverName, NutsSession session){ + return NutsDependencySolvers.of(session).createSolver(solverName,session); + } + + static String[] getSolverNames(NutsSession session){ + return NutsDependencySolvers.of(session).getSolverNames(session); + } + NutsDependencySolver add(NutsDefinition def); diff --git a/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsDependencySolvers.java b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsDependencySolvers.java new file mode 100644 index 000000000..3f45ea291 --- /dev/null +++ b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsDependencySolvers.java @@ -0,0 +1,19 @@ +package net.thevpc.nuts.spi; + +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.boot.NutsApiUtils; + +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) +public interface NutsDependencySolvers extends NutsComponent { + static NutsDependencySolvers of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsDependencySolvers.class,true,null); + } + + NutsDependencySolver createSolver(NutsSession session); + + NutsDependencySolver createSolver(String solverName,NutsSession session); + + String[] getSolverNames(NutsSession session); + +} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsLogManager.java b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsLogManager.java similarity index 69% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsLogManager.java rename to core/nuts/src/main/java/net/thevpc/nuts/spi/NutsLogManager.java index e38512bea..c1e27fd30 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsLogManager.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsLogManager.java @@ -24,7 +24,11 @@ *
    * ==================================================================== */ -package net.thevpc.nuts; +package net.thevpc.nuts.spi; + +import net.thevpc.nuts.NutsLogger; +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.boot.NutsApiUtils; import java.util.logging.Handler; import java.util.logging.Level; @@ -33,81 +37,83 @@ * Nuts Log Manager * @app.category Logging */ -public interface NutsLogManager { +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) +public interface NutsLogManager extends NutsComponent { + static NutsLogManager of(NutsSession session) { + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsLogManager.class,true,null); + } + /** * Log handler * @return Log handler */ - Handler[] getHandlers(); + Handler[] getHandlers(NutsSession session); /** * remove the given handler * @param handler handler to remove * @return this */ - NutsLogManager removeHandler(Handler handler); + NutsLogManager removeHandler(Handler handler,NutsSession session); /** * add the given handler * @param handler handler to add * @return this */ - NutsLogManager addHandler(Handler handler); + NutsLogManager addHandler(Handler handler,NutsSession session); /** * terminal handler * @return terminal handler */ - Handler getTermHandler(); + Handler getTermHandler(NutsSession session); /** * file handler * @return file handler */ - Handler getFileHandler(); + Handler getFileHandler(NutsSession session); /** * create an instance of {@link NutsLogger} * @param name logger name * @return new instance of {@link NutsLogger} */ - NutsLogger of(String name); + NutsLogger createLogger(String name, NutsSession session); /** * create an instance of {@link NutsLogger} * @param clazz logger clazz * @return new instance of {@link NutsLogger} */ - NutsLogger of(Class clazz); + NutsLogger createLogger(Class clazz, NutsSession session); /** * return terminal logger level * @return terminal logger level */ - Level getTermLevel(); + Level getTermLevel(NutsSession session); /** * set terminal logger level * @param level new level * @return this */ - NutsLogManager setTermLevel(Level level); + NutsLogManager setTermLevel(Level level,NutsSession session); /** * return file logger level * @return file logger level */ - Level getFileLevel(); + Level getFileLevel(NutsSession session); /** * set file logger level * @param level new level * @return this */ - NutsLogManager setFileLevel(Level level); - - - NutsSession getSession(); + NutsLogManager setFileLevel(Level level,NutsSession session); - NutsLogManager setSession(NutsSession session); } diff --git a/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsPaths.java b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsPaths.java new file mode 100644 index 000000000..3c280b274 --- /dev/null +++ b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsPaths.java @@ -0,0 +1,38 @@ +package net.thevpc.nuts.spi; + +import net.thevpc.nuts.NutsPath; +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.boot.NutsApiUtils; + +import java.io.File; +import java.net.URL; +import java.nio.file.Path; + +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) +public interface NutsPaths extends NutsComponent { + static NutsPaths of(NutsSession session){ + NutsApiUtils.checkSession(session); + return session.extensions().createSupported(NutsPaths.class, true, session); + } + + /** + * expand path to Workspace Location + * + * @param path path to expand + * @return expanded path + */ + NutsPath createPath(String path, NutsSession session); + + NutsPath createPath(File path, NutsSession session); + + NutsPath createPath(Path path, NutsSession session); + + NutsPath createPath(URL path, NutsSession session); + + NutsPath createPath(String path, ClassLoader classLoader, NutsSession session); + + NutsPaths addPathFactory(NutsPathFactory pathFactory,NutsSession session); + + NutsPaths removePathFactory(NutsPathFactory pathFactory,NutsSession session); + +} diff --git a/core/nuts/src/main/java/net/thevpc/nuts/NutsArgumentCandidateBuilder.java b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsTerminals.java similarity index 58% rename from core/nuts/src/main/java/net/thevpc/nuts/NutsArgumentCandidateBuilder.java rename to core/nuts/src/main/java/net/thevpc/nuts/spi/NutsTerminals.java index ea45540af..1ed7d92f7 100644 --- a/core/nuts/src/main/java/net/thevpc/nuts/NutsArgumentCandidateBuilder.java +++ b/core/nuts/src/main/java/net/thevpc/nuts/spi/NutsTerminals.java @@ -24,61 +24,45 @@ *
    * ==================================================================== */ -package net.thevpc.nuts; +package net.thevpc.nuts.spi; +import net.thevpc.nuts.NutsPrintStream; +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.NutsSessionTerminal; import net.thevpc.nuts.boot.NutsApiUtils; -import java.io.Serializable; +import java.io.InputStream; /** - * @app.category Application + * @app.category Input Output */ -public interface NutsArgumentCandidateBuilder extends Serializable { - - static NutsArgumentCandidateBuilder of(NutsSession session) { +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) +public interface NutsTerminals extends NutsComponent { + static NutsTerminals of(NutsSession session) { NutsApiUtils.checkSession(session); - return session.commandLine().createCandidate(); + return session.extensions().createSupported(NutsTerminals.class, true, null); } - /** - * argument value - * - * @return argument value - */ - String getValue(); - /** - * set value - * @param value value - * @return {@code this} instance - */ - NutsArgumentCandidateBuilder setValue(String value); + NutsTerminals enableRichTerm(NutsSession session); /** - * human display + * return new terminal bound to system terminal * - * @return human display + * @return new terminal */ - String getDisplay(); + NutsSessionTerminal createTerminal(NutsSession session); /** - * set display - * @param value value - * @return {@code this} instance - */ - NutsArgumentCandidateBuilder setDisplay(String value); - - /** - * set all values from the given candidate - * @param value value - * @return {@code this} instance + * return new terminal + * + * @param in in + * @param out out + * @param err err + * @return new terminal */ - NutsArgumentCandidateBuilder setAll(NutsArgumentCandidate value); + NutsSessionTerminal createTerminal(InputStream in, NutsPrintStream out, NutsPrintStream err, NutsSession session); - /** - * build a candidate - * @return candidate - */ - NutsArgumentCandidate build(); + NutsSessionTerminal createTerminal(NutsSessionTerminal terminal, NutsSession session); } diff --git a/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineCommandHistory.java b/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineCommandHistory.java index 6e47d9581..4d05d67b3 100644 --- a/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineCommandHistory.java +++ b/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineCommandHistory.java @@ -30,6 +30,9 @@ import static net.thevpc.nuts.ext.term.NutsJLineHistory.DEFAULT_HISTORY_FILE_SIZE; import static net.thevpc.nuts.ext.term.NutsJLineHistory.DEFAULT_HISTORY_SIZE; + +import net.thevpc.nuts.spi.NutsSupportLevelContext; +import net.thevpc.nuts.spi.NutsSystemTerminalBase; import org.jline.reader.History; import org.jline.reader.History.Entry; import org.jline.reader.LineReader; @@ -49,6 +52,7 @@ public class NutsJLineCommandHistory implements NutsCommandHistory { private LineReader reader; private final LinkedList items = new LinkedList<>(); + private NutsPath path; private int lastLoaded = 0; private int nbEntriesInFile = 0; private int offset = 0; @@ -65,6 +69,7 @@ private void internalClear() { items.clear(); } + public LineReader getReader() { return reader; } @@ -73,7 +78,48 @@ public void setReader(LineReader reader) { this.reader = reader; } - private Path getPath() { + @Override + public NutsCommandHistory setPath(Path path) { + return setPath(path==null?null:NutsPath.of(path,session)); + } + + @Override + public NutsCommandHistory setPath(File path) { + return setPath(path==null?null:NutsPath.of(path,session)); + } + + @Override + public NutsCommandHistory setPath(NutsPath path) { + this.path=path; + if(this.path!=null) { + reader.getVariables().put(LineReader.HISTORY_FILE, path.toFile()); + } + return this; + } + + @Override + public NutsPath getPath() { + return null; + } + + @Override + public int getSupportLevel(NutsSupportLevelContext context) { + NutsSystemTerminal st = context.getSession().config().getSystemTerminal(); + boolean jline=false; + NutsSystemTerminalBase b = st.getParent(); + if(b!=null){ + if (b instanceof NutsJLineTerminal){ + jline=true; + } + } + if(jline) { + return DEFAULT_SUPPORT + 10; + }else{ + return -1; + } + } + + private Path getPathPath() { Object obj = reader != null ? reader.getVariables().get(LineReader.HISTORY_FILE) : null; if (obj instanceof Path) { return (Path) obj; @@ -116,7 +162,7 @@ public void accept(String l) { @Override public void load() { - Path path = getPath(); + Path path = getPathPath(); if (path != null) { try { if (Files.exists(path)) { @@ -139,7 +185,7 @@ public void save(OutputStream out) { // shellHistory.save(); // } else { try { - Path path = getPath(); + Path path = getPathPath(); if (path != null) { // Append new items to the history file try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out))) { @@ -164,7 +210,7 @@ public void save(OutputStream out) { @Override public void save() { try { - Path path = getPath(); + Path path = getPathPath(); if (path != null) { Log.trace("Saving history to: ", path); Files.createDirectories(path.toAbsolutePath().getParent()); @@ -190,7 +236,7 @@ public void purge() { // shellHistory.clear(); // } else { internalClear(); - Path path = getPath(); + Path path = getPathPath(); if (path != null) { try { Log.trace("Purging history from: ", path); diff --git a/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineCompleter.java b/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineCompleter.java index ff778689b..b56108fae 100644 --- a/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineCompleter.java +++ b/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineCompleter.java @@ -23,7 +23,7 @@ public void complete(LineReader reader, final ParsedLine line, List c NutsCommandAutoCompleteResolver autoCompleteResolver = nutsJLineTerminal.getAutoCompleteResolver(); if (autoCompleteResolver != null) { - NutsCommandLine commandline = session.commandLine().create(line.words()); + NutsCommandLine commandline = NutsCommandLine.of(line.words(),session); if (line.words().size() > 0) { commandline.setCommandName(line.words().get(0)); } diff --git a/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineTerminal.java b/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineTerminal.java index 807707162..1bb26adbf 100644 --- a/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineTerminal.java +++ b/ext/next-term/src/main/java/net/thevpc/nuts/ext/term/NutsJLineTerminal.java @@ -31,7 +31,6 @@ import org.jline.terminal.TerminalBuilder; import java.io.*; -import java.nio.file.Paths; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; @@ -43,7 +42,7 @@ /** * Created by vpc on 2/20/17. */ -@NutsPrototype +@NutsComponentScope(NutsComponentScopeType.PROTOTYPE) public class NutsJLineTerminal implements NutsSystemTerminalBase { private static final Logger LOG = Logger.getLogger(NutsJLineTerminal.class.getName()); @@ -121,9 +120,9 @@ public NutsJLineTerminal setCommandAutoCompleteResolver(NutsCommandAutoCompleteR private AttributedString toAttributedString(NutsText n, NutsTextStyles styles, NutsSession session) { switch (n.getType()) { case PLAIN: { - styles=session.text().getTheme().toBasicStyles(styles, session); + styles=NutsTexts.of(session).getTheme().toBasicStyles(styles, session); NutsTextPlain p = (NutsTextPlain) n; - if (styles.isNone()) { + if (styles.isPlain()) { return new AttributedString(p.getText()); } else { AttributedStyle s = AttributedStyle.DEFAULT; @@ -182,11 +181,11 @@ private AttributedString toAttributedString(NutsText n, NutsTextStyles styles, N case CODE: { NutsTextCode p = (NutsTextCode) n; NutsText nn = p.highlight(session); - return toAttributedString(nn, NutsTextStyles.NONE, session); + return toAttributedString(nn, NutsTextStyles.PLAIN, session); } case TITLE: { NutsTextTitle p = (NutsTextTitle) n; - return toAttributedString(p.getChild(), NutsTextStyles.NONE, session); + return toAttributedString(p.getChild(), NutsTextStyles.PLAIN, session); } case LINK: { NutsTextLink p = (NutsTextLink) n; @@ -205,7 +204,7 @@ private AttributedString toAttributedString(NutsText n, NutsTextStyles styles, N } case STYLED: { NutsTextStyled p = (NutsTextStyled) n; - if (styles.isNone()) { + if (styles.isPlain()) { return toAttributedString(p.getChild(), p.getStyles(), session); } else { return toAttributedString( @@ -239,10 +238,10 @@ public void prepare(NutsSession session) { .highlighter(new Highlighter() { @Override public AttributedString highlight(LineReader reader, String buffer) { - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); NutsCommandReadHighlighter h = getCommandReadHighlighter(); NutsText n=(h!=null)?h.highlight(buffer, session):text.ofPlain(buffer); - return toAttributedString(n, NutsTextStyles.NONE, session); + return toAttributedString(n, NutsTextStyles.PLAIN, session); } @Override @@ -261,22 +260,22 @@ public void setErrorIndex(int i) { // .parse(parse) .build(); reader.unsetOpt(LineReader.Option.INSERT_TAB); - reader.setVariable(LineReader.HISTORY_FILE, Paths.get(session.locations().getWorkspaceLocation()).resolve("history").normalize().toFile()); + reader.setVariable(LineReader.HISTORY_FILE, session.locations().getWorkspaceLocation().resolve("history").normalize().toFile()); if (reader instanceof LineReaderImpl) { ((LineReaderImpl) reader).setHistory(new NutsJLineHistory(reader, session, this)); } - this.out = session.io().createPrintStream( + this.out = NutsPrintStream.of( new TransparentPrintStream( new PrintStream(reader.getTerminal().output(), true), System.out ), - NutsTerminalMode.FORMATTED); - this.err = session.io().createPrintStream( + NutsTerminalMode.FORMATTED,session); + this.err = NutsPrintStream.of( new TransparentPrintStream( new PrintStream(reader.getTerminal().output(), true), System.err ), - NutsTerminalMode.FORMATTED);//.setColor(NutsPrintStream.RED); + NutsTerminalMode.FORMATTED,session);//.setColor(NutsPrintStream.RED); this.in = new TransparentInputStream(reader.getTerminal().input(), System.in); } @@ -292,10 +291,11 @@ protected void close(){ @Override public int getSupportLevel(NutsSupportLevelContext criteria) { + NutsSession session = criteria.getSession(); try { - prepare(criteria.getSession()); + prepare(session); }catch (Exception ex){ - criteria.getSession().log().of(NutsJLineTerminal.class) + NutsLogger.of(NutsJLineTerminal.class,session) .with().level(Level.FINEST).verb(NutsLogVerb.FAIL).error(ex) .log(NutsMessage.jstyle("unable to create NutsJLineTerminal. ignored.")); return NO_SUPPORT; @@ -310,11 +310,11 @@ public String readLine(NutsPrintStream out, NutsMessage message,NutsSession sess out = getOut(); } if (out == null) { - out = session.io().stdout(); + out = NutsPrintStreams.of(session).stdout(); } String readLine = null; try { - readLine = reader.readLine(session.text().toText(message).toString()); + readLine = reader.readLine(NutsTexts.of(session).toText(message).toString()); } catch (UserInterruptException e) { throw new NutsJLineInterruptException(); } @@ -330,11 +330,11 @@ public String readLine(NutsPrintStream out, NutsMessage message,NutsSession sess public char[] readPassword(NutsPrintStream out, NutsMessage message,NutsSession session) { prepare(session); if (out == null) { - return reader.readLine(session.text().toText(message).toString(), '*').toCharArray(); + return reader.readLine(NutsTexts.of(session).toText(message).toString(), '*').toCharArray(); }else{ //should I use some out?? } - return reader.readLine(session.text().toText(message).toString(), '*').toCharArray(); + return reader.readLine(NutsTexts.of(session).toText(message).toString(), '*').toCharArray(); } @Override diff --git a/lib/nlib-ssh/src/main/java/net/thevpc/nuts/lib/ssh/SShConnection.java b/lib/nlib-ssh/src/main/java/net/thevpc/nuts/lib/ssh/SShConnection.java index 13e3562c6..f7f91f91d 100644 --- a/lib/nlib-ssh/src/main/java/net/thevpc/nuts/lib/ssh/SShConnection.java +++ b/lib/nlib-ssh/src/main/java/net/thevpc/nuts/lib/ssh/SShConnection.java @@ -3,6 +3,7 @@ import com.jcraft.jsch.*; import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.NutsString; +import net.thevpc.nuts.NutsTexts; import java.io.*; import java.util.ArrayList; @@ -671,7 +672,7 @@ public String getStringBuffer() { public InputStream prepareStream(File file) throws FileNotFoundException { FileInputStream in = new FileInputStream(file); for (SshListener listener : listeners) { - InputStream v = listener.monitorInputStream(in, file.length(), nutsSession.text().toText(file.getPath())); + InputStream v = listener.monitorInputStream(in, file.length(), NutsTexts.of(nutsSession).toText(file.getPath())); if (v != null) { return v; } diff --git a/lib/nlib-ssh/src/main/java/net/thevpc/nuts/lib/ssh/SshNutsPath.java b/lib/nlib-ssh/src/main/java/net/thevpc/nuts/lib/ssh/SshNutsPath.java index 968e7b904..2bc12f41b 100644 --- a/lib/nlib-ssh/src/main/java/net/thevpc/nuts/lib/ssh/SshNutsPath.java +++ b/lib/nlib-ssh/src/main/java/net/thevpc/nuts/lib/ssh/SshNutsPath.java @@ -32,7 +32,7 @@ public NutsPath resolve(String path) { } loc.append(String.join("/", others)); return - getSession().io().path( + NutsPath.of( SshPath.toString( this.path.getHost(), this.path.getPort(), @@ -40,9 +40,9 @@ public NutsPath resolve(String path) { this.path.getUser(), this.path.getPassword(), this.path.getKeyFile() - )); + ),getSession()); } - return getSession().io().path(toString()); + return NutsPath.of(toString(),getSession()); } public static String getURLParentPath(String ppath) { @@ -71,7 +71,7 @@ public NutsPath getParent() { return null; } return - getSession().io().path( + NutsPath.of( SshPath.toString( this.path.getHost(), this.path.getPort(), @@ -79,7 +79,7 @@ public NutsPath getParent() { this.path.getUser(), this.path.getPassword(), this.path.getKeyFile() - )); + ),getSession()); } @Override @@ -112,7 +112,7 @@ public void print(NutsPrintStream out) { NutsTextStyle _path = NutsTextStyle.path(); NutsTextStyle _nbr = NutsTextStyle.number(); // if(true) { - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); NutsTextBuilder sb = text.builder(); String user=path.getUser(); String host=path.getHost(); @@ -272,7 +272,7 @@ public NutsPath[] getChildren() { cc+="/"; } cc+=x; - return getSession().io().path(path.setPath(cc).toString()); + return NutsPath.of(path.setPath(cc).toString(),getSession()); } ).toArray(NutsPath[]::new); }catch (Exception e){ @@ -288,12 +288,12 @@ public Instant getLastModifiedInstant() { @Override public NutsPath toAbsolute(NutsPath basePath) { - return getSession().io().path(toString()); + return NutsPath.of(toString(),getSession()); } @Override public NutsPath normalize() { - return getSession().io().path(toString()); + return NutsPath.of(toString(),getSession()); } @Override diff --git a/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/DefaultProjectTemplate.java b/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/DefaultProjectTemplate.java index aeb15e8ac..57d81b041 100755 --- a/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/DefaultProjectTemplate.java +++ b/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/DefaultProjectTemplate.java @@ -63,7 +63,7 @@ public String ask(String propName, String propertyTitle, StringValidator validat return term.ask() .resetLine() .forString( - getSession().text().builder() + NutsTexts.of(getSession()).builder() .append(propertyTitle, NutsTextStyle.primary4()) .append(" (") .append(propName,NutsTextStyle.pale()) @@ -408,7 +408,7 @@ public File resolvePomFile(File folder) { if (!pomFile.isFile()) { return null; } - session.descriptor().parser().setDescriptorStyle(NutsDescriptorStyle.MAVEN).parse(pomFile); + NutsDescriptorParser.of(session).setDescriptorStyle(NutsDescriptorStyle.MAVEN).parse(pomFile); return pomFile; } catch (Exception ex) { throw new RuntimeException(ex); @@ -431,7 +431,7 @@ public NutsDescriptor askForPom() { if (!getSession().getTerminal().ask() .resetLine() .forBoolean("accept project location %s?", - applicationContext.getSession().text().ofStyled(p.getPath(),NutsTextStyle.path())) + NutsTexts.of(applicationContext.getSession()).ofStyled(p.getPath(),NutsTextStyle.path())) .setDefaultValue(false) .getBooleanValue()) { throw new NutsUserCancelException(getSession()); @@ -439,7 +439,7 @@ public NutsDescriptor askForPom() { } } try { - return session.descriptor().parser().setDescriptorStyle(NutsDescriptorStyle.MAVEN) + return NutsDescriptorParser.of(session).setDescriptorStyle(NutsDescriptorStyle.MAVEN) .parse(new File(getProjectRootFolder(), "pom.xml")); } catch (Exception ex) { throw new RuntimeException(ex); diff --git a/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/IOUtils.java b/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/IOUtils.java index 1bc58e786..31ec59537 100755 --- a/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/IOUtils.java +++ b/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/IOUtils.java @@ -6,6 +6,7 @@ package net.thevpc.nuts.lib.template; import net.thevpc.nuts.NutsTextStyle; +import net.thevpc.nuts.NutsTexts; import java.io.BufferedReader; import java.io.File; @@ -77,10 +78,10 @@ public static void writeString(String str, File file, ProjectTemplate project) t fileWriter.flush(); fileWriter.close(); if (isOverride) { - console.println("[OVERRIDE] %s%n",project.getSession().text().ofStyled(file.getPath(), NutsTextStyle.path())); + console.println("[OVERRIDE] %s%n", NutsTexts.of(project.getSession()).ofStyled(file.getPath(), NutsTextStyle.path())); } else { project.setNewlyCreated(file.getPath()); - console.println("[GENERATE] %s%n" + project.getSession().text().ofStyled(file.getPath(),NutsTextStyle.path())); + console.println("[GENERATE] %s%n" + NutsTexts.of(project.getSession()).ofStyled(file.getPath(),NutsTextStyle.path())); } } diff --git a/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/ValidatorFactory.java b/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/ValidatorFactory.java index 8fcd40682..b7ae8d075 100755 --- a/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/ValidatorFactory.java +++ b/lib/nlib-template/src/main/java/net/thevpc/nuts/lib/template/ValidatorFactory.java @@ -1,5 +1,6 @@ package net.thevpc.nuts.lib.template; +import net.thevpc.nuts.NutsArgument; import net.thevpc.nuts.NutsSession; public class ValidatorFactory { @@ -124,7 +125,7 @@ public String validate(String value) { public final StringValidator BOOLEAN = new StringValidator() { @Override public String validate(String value) { - Boolean b = session.commandLine().createArgument(value).getAll().getBoolean(null); + Boolean b = NutsArgument.of(value,session).getAll().getBoolean(null); if (b == null) { throw new IllegalArgumentException("Invalid boolean"); } diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test01_CreateTest.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test01_CreateTest.java index 3226e9ab3..4fd9913b0 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test01_CreateTest.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test01_CreateTest.java @@ -9,10 +9,15 @@ import net.thevpc.nuts.*; import java.io.File; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; +import java.io.InputStream; +import java.net.MalformedURLException; +import java.util.Set; +import java.util.regex.Pattern; +import net.thevpc.nuts.runtime.core.util.CoreServiceUtils; +import net.thevpc.nuts.spi.NutsComponent; +import net.thevpc.nuts.spi.NutsDependencySolver; +import net.thevpc.nuts.spi.NutsTerminals; import org.junit.jupiter.api.*; /** @@ -20,6 +25,18 @@ */ public class Test01_CreateTest { + @Test + public void tempTest(){ + try { + Set q = CoreServiceUtils.loadZipServiceClassNames(new File("/home/vpc/nuts-runtime-0.8.3.0-err.jar").toURI().toURL(), NutsComponent.class); + System.out.println(q.size()); + for (String s : q) { + System.out.println(s); + } + } catch (MalformedURLException e) { + e.printStackTrace(); + } + } @Test public void minimal1() throws Exception { String wsPath = TestUtils.getTestBaseFolder().getPath(); @@ -30,7 +47,7 @@ public void minimal1() throws Exception { "--verbose", "--skip-companions"); Assertions.assertEquals(new File(wsPath, "cache").getPath(), session.locations().getStoreLocation(NutsStoreLocation.CACHE)); - Assertions.assertEquals(0,session.repos().getRepositories().length); + Assertions.assertEquals(0, session.repos().getRepositories().length); // Assertions.assertEquals(new File(wsPath, "cache/" + NutsConstants.Folders.REPOSITORIES + "/" + // session.repos().getRepositories()[0].getName() + // "/" + session.repos().getRepositories()[0].getUuid()).getPath(), @@ -57,7 +74,7 @@ public void minimal1() throws Exception { "a\n\nb"; System.out.println("-----------------------"); System.out.println(str); - NutsText txt = session.text().parse(str); + NutsText txt = NutsTexts.of(session).parse(str); System.out.println("-----------------------"); System.out.println(txt); } @@ -92,15 +109,14 @@ public void default1() throws Exception { String base = ""; switch (NutsOsFamily.getCurrent()) { case WINDOWS: { - base =new File(System.getProperty("user.home"),"AppData\\Local\\nuts\\cache").getPath(); + base = new File(System.getProperty("user.home"), "AppData\\Local\\nuts\\cache").getPath(); break; } case MACOS: case LINUX: case UNIX: - case UNKNOWN: - { - base =new File(System.getProperty("user.home"),".cache/nuts").getPath(); + case UNKNOWN: { + base = new File(System.getProperty("user.home"), ".cache/nuts").getPath(); break; } } @@ -133,24 +149,241 @@ public void default3() throws Exception { "--skip-companions").getWorkspace(); } - @BeforeAll - public static void setUpClass() throws IOException { - TestUtils.println("####### RUNNING TEST @ " + TestUtils.getCallerClassSimpleName()); - } + @Test + public void createUtilTypes() { + NutsSession s = TestUtils.runNewTestWorkspace("--verbose","-b"); - @AfterAll - public static void tearUpClass() throws IOException { - } + { + NutsPath home = NutsPath.of(new File(System.getProperty("user.home")), s); + Assertions.assertNotNull(home); + } - @BeforeEach - public void startup() throws IOException { -// Assumptions.assumeTrue(NutsOsFamily.getCurrent()== NutsOsFamily.LINUX); - TestUtils.unsetNutsSystemProperties(); - } + { + NutsCommandLine cmd = NutsCommandLine.of(new String[]{"cmd", "--test"}, s); + Assertions.assertNotNull(cmd); + } - @AfterEach - public void cleanup() { - TestUtils.unsetNutsSystemProperties(); - } + { + NutsArgument arg = NutsArgument.of("arg", s); + Assertions.assertNotNull(arg); + } + + { + NutsExpr expr = NutsExpr.of(s); + Assertions.assertNotNull(expr); + } + + { + NutsStream stream = NutsStream.of(new String[]{"a"}, s); + Assertions.assertNotNull(stream); + } + + { + NutsVal v = NutsVal.of("a", s); + Assertions.assertNotNull(v); + } + + { + Pattern g = NutsGlob.of(s).toPattern("a.*"); + Assertions.assertNotNull(g); + } + + { + InputStream stdin = NutsInputStreams.of(s).stdin(); + Assertions.assertNotNull(stdin); + } + + { + NutsPrintStream stdout = NutsPrintStreams.of(s).stdout(); + Assertions.assertNotNull(stdout); + } + { + NutsCommandHistory h = NutsCommandHistory.of(s); + Assertions.assertNotNull(h); + } + + { + NutsApplicationContexts c = NutsApplicationContexts.of(s); + Assertions.assertNotNull(c); + } + + { + NutsExecutionEntries c = NutsExecutionEntries.of(s); + Assertions.assertNotNull(c); + } + + { + NutsHash c = NutsHash.of(s); + Assertions.assertNotNull(c); + } + + { + NutsInputStreamMonitor c = NutsInputStreamMonitor.of(s); + Assertions.assertNotNull(c); + } + { + NutsLocks c = NutsLocks.of(s); + Assertions.assertNotNull(c); + } + { + NutsTerminals c = NutsTerminals.of(s); + Assertions.assertNotNull(c); + } + { + NutsTmp c = NutsTmp.of(s); + Assertions.assertNotNull(c); + } + { + NutsRm c = NutsRm.of(s); + Assertions.assertNotNull(c); + } + { + NutsCp c = NutsCp.of(s); + Assertions.assertNotNull(c); + } + { + NutsPs c = NutsPs.of(s); + Assertions.assertNotNull(c); + } + { + NutsCompress c = NutsCompress.of(s); + Assertions.assertNotNull(c); + } + { + NutsUncompress c = NutsUncompress.of(s); + Assertions.assertNotNull(c); + } + { + NutsLogger log = NutsLogger.of(Test01_CreateTest.class, s); + Assertions.assertNotNull(log); + NutsLoggerOp logop = NutsLoggerOp.of(Test01_CreateTest.class, s); + Assertions.assertNotNull(logop); + } + { + NutsIdResolver r = NutsIdResolver.of(s); + Assertions.assertNotNull(r); + } + { + NutsIdParser r = NutsIdParser.of(s); + Assertions.assertNotNull(r); + } + { + NutsIdBuilder r = NutsIdBuilder.of(s); + Assertions.assertNotNull(r); + } + { + NutsIdFormat r = NutsIdFormat.of(s); + Assertions.assertNotNull(r); + } + { + NutsIdFilters r = NutsIdFilters.of(s); + Assertions.assertNotNull(r); + } + { + NutsVersionFilters r = NutsVersionFilters.of(s); + Assertions.assertNotNull(r); + } + { + NutsDependencyFilters r = NutsDependencyFilters.of(s); + Assertions.assertNotNull(r); + } + { + NutsDescriptorFilters r = NutsDescriptorFilters.of(s); + Assertions.assertNotNull(r); + } + { + NutsInstallStatusFilters r = NutsInstallStatusFilters.of(s); + Assertions.assertNotNull(r); + } + { + NutsRepositoryFilters r = NutsRepositoryFilters.of(s); + Assertions.assertNotNull(r); + } + { + NutsElements r = NutsElements.of(s); + Assertions.assertNotNull(r); + } + { + NutsDescriptorParser r = NutsDescriptorParser.of(s); + Assertions.assertNotNull(r); + } + { + NutsDescriptorBuilder r = NutsDescriptorBuilder.of(s); + Assertions.assertNotNull(r); + } + { + NutsEnvConditionBuilder r = NutsEnvConditionBuilder.of(s); + Assertions.assertNotNull(r); + } + { + NutsDescriptorPropertyBuilder r = NutsDescriptorPropertyBuilder.of(s); + Assertions.assertNotNull(r); + } + { + NutsArtifactCallBuilder r = NutsArtifactCallBuilder.of(s); + Assertions.assertNotNull(r); + } + { + NutsDescriptorFormat r = NutsDescriptorFormat.of(s); + Assertions.assertNotNull(r); + } + { + NutsDependencySolver r = NutsDependencySolver.of(s); + Assertions.assertNotNull(r); + } + { + NutsDependencyBuilder r = NutsDependencyBuilder.of(s); + Assertions.assertNotNull(r); + } + { + NutsDependencyParser r = NutsDependencyParser.of(s); + Assertions.assertNotNull(r); + } + { + NutsVersionParser r = NutsVersionParser.of(s); + Assertions.assertNotNull(r); + } + { + NutsVersionFormat r = NutsVersionFormat.of(s); + Assertions.assertNotNull(r); + } + { + NutsFilters r = NutsFilters.of(s); + Assertions.assertNotNull(r); + } + { + NutsTexts r = NutsTexts.of(s); + Assertions.assertNotNull(r); + } + { + NutsObjectFormat r = NutsObjectFormat.of(s); + Assertions.assertNotNull(r); + } + { + NutsInfoFormat r = NutsInfoFormat.of(s); + Assertions.assertNotNull(r); + } + { + NutsExecCommandFormat r = NutsExecCommandFormat.of(s); + Assertions.assertNotNull(r); + } + { + NutsCommandLineFormat r = NutsCommandLineFormat.of(s); + Assertions.assertNotNull(r); + } + { + NutsTableFormat r = NutsTableFormat.of(s); + Assertions.assertNotNull(r); + } + { + NutsTreeFormat r = NutsTreeFormat.of(s); + Assertions.assertNotNull(r); + } + { + NutsPropertiesFormat r = NutsPropertiesFormat.of(s); + Assertions.assertNotNull(r); + } + + } } diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test03_CreateLayoutLinuxTest.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test03_CreateLayoutLinuxTest.java index dae4dc663..1c53efbbd 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test03_CreateLayoutLinuxTest.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test03_CreateLayoutLinuxTest.java @@ -63,7 +63,7 @@ public void customLayout_reload() throws Exception { )); if(NDI_COMPANIONS>0) { - NutsId ndiId = s.search().setInstallStatus(s.filters().installStatus().byInstalled(true)).addId("nsh") + NutsId ndiId = s.search().setInstallStatus(NutsInstallStatusFilters.of(s).byInstalled(true)).addId("nsh") .setDistinct(true) .getResultIds().singleton(); Assertions.assertTrue(ndiId.getVersion().getValue().startsWith(TestUtils.NUTS_VERSION + ".")); @@ -154,7 +154,7 @@ public void customLayout_use_export() throws Exception { "info")); if(NDI_COMPANIONS>0) { - NutsId ndiId = s2.search().setInstallStatus(s2.filters().installStatus().byInstalled(true)).addId("nsh") + NutsId ndiId = s2.search().setInstallStatus(NutsInstallStatusFilters.of(s2).byInstalled(true)).addId("nsh") .setDistinct(true).getResultIds().singleton(); Assertions.assertTrue(ndiId.getVersion().getValue().startsWith(TestUtils.NUTS_VERSION + ".")); } @@ -195,10 +195,10 @@ public void customLayout_use_standalone() throws Exception { if(NDI_COMPANIONS>0) { NutsId nshId = null; try { - nshId = s.search().setInstallStatus(s.filters().installStatus().byInstalled(true)).addId("nsh") + nshId = s.search().setInstallStatus(NutsInstallStatusFilters.of(s).byInstalled(true)).addId("nsh") .setDistinct(true).getResultIds().singleton(); } catch (Exception ex) { - nshId = s.search().setInstallStatus(s.filters().installStatus().byInstalled(true)).addId("nsh") + nshId = s.search().setInstallStatus(NutsInstallStatusFilters.of(s).byInstalled(true)).addId("nsh") .setDistinct(true).getResultIds().singleton(); } Assertions.assertTrue(nshId.getVersion().getValue().startsWith(TestUtils.NUTS_VERSION + ".")); diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test06_UpdateTest.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test06_UpdateTest.java index 2e7a6f4b3..84468b35d 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test06_UpdateTest.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test06_UpdateTest.java @@ -16,7 +16,6 @@ import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.*; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @@ -190,19 +189,19 @@ private void testUpdate(boolean implOnly, String callerName) throws Exception { "--json", "version" ); - TestUtils.println(uws.commandLine().create(b.createProcessCommandLine()).toString()); + TestUtils.println(NutsCommandLine.of(b.createProcessCommandLine(),uws).toString()); String ss = uws.exec().setExecutionType(NutsExecutionType.SYSTEM).addCommand(b.createProcessCommandLine()).grabOutputString().run().getOutputString(); TestUtils.println("================"); TestUtils.println(ss); - Map m = uws.elem().setContentType(NutsContentType.JSON).parse(ss, Map.class); + Map m = NutsElements.of(uws).json().parse(ss, Map.class); Assertions.assertEquals(newApiVersion, m.get("nuts-api-version")); Assertions.assertEquals(newRuntimeVersion, m.get("nuts-runtime-version")); } private Path replaceAPIJar(Path p, FromTo api, NutsSession session) { try { - Path zipFilePath = session.io().tmp() + Path zipFilePath = NutsTmp.of(session) .createTempFile(".zip").toFile(); Files.copy(p, zipFilePath, StandardCopyOption.REPLACE_EXISTING); try (FileSystem fs = FileSystems.newFileSystem(zipFilePath, (ClassLoader) null)) { @@ -241,7 +240,7 @@ private Path replaceAPIJar(Path p, FromTo api, NutsSession session) { private Path replaceRuntimeJar(Path p, FromTo api, FromTo impl, NutsSession session) { try { - Path zipFilePath = session.io().tmp() + Path zipFilePath = NutsTmp.of(session) .createTempFile(".zip").toFile(); Files.copy(p, zipFilePath, StandardCopyOption.REPLACE_EXISTING); try (FileSystem fs = FileSystems.newFileSystem(zipFilePath, (ClassLoader) null)) { diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test09_FindLinuxTest.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test09_FindLinuxTest.java index debca7b81..fc284d3cf 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test09_FindLinuxTest.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test09_FindLinuxTest.java @@ -33,7 +33,7 @@ public void find() throws Exception { List def = ws.search().addId("nuts").setOptional(false).setLatest(true).setFailFast(false) // .repository("maven-local") .setDefaultVersions(true) - .setInstallStatus(ws.filters().installStatus().byDeployed(true)) + .setInstallStatus(NutsInstallStatusFilters.of(ws).byDeployed(true)) .getResultIds().toList(); TestUtils.println(def); diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test10_ExecURLTest.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test10_ExecURLTest.java index cfa6cff79..1b68a48ec 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test10_ExecURLTest.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test10_ExecURLTest.java @@ -6,6 +6,7 @@ package net.thevpc.nuts.core.test.blackbox; import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.NutsVersionFormat; import net.thevpc.nuts.core.test.utils.TestUtils; import net.thevpc.nuts.NutsOsFamily; import net.thevpc.nuts.NutsWorkspace; @@ -23,22 +24,23 @@ */ public class Test10_ExecURLTest { - @Test + //disabled, unless we find a good executable example jar + //@Test public void execURL() throws Exception { NutsSession s = TestUtils.openNewTestWorkspace( "--archetype", "default", "--skip-companions", "--verbose" ); - TestUtils.println(s.version().formatter()); + TestUtils.println(NutsVersionFormat.of(s)); String result = s.exec() //there are three classes and no main-class, so need to specify the one .addExecutorOption("--main-class=Version") // .addExecutorOption("--main-class=junit.runner.Version") //get the command .addCommand( - "https://search.maven.org/remotecontent?filepath=junit/junit/4.12/junit-4.12.jar" -// "https://search.maven.org/remotecontent?filepath=net/java/sezpoz/demo/app/1.6/app-1.6.jar" +// "https://search.maven.org/remotecontent?filepath=junit/junit/4.12/junit-4.12.jar" + "https://search.maven.org/remotecontent?filepath=net/java/sezpoz/demo/app/1.6/app-1.6.jar" // "https://search.maven.org/remotecontent?filepath=net/thevpc/hl/hl/0.1.0/hl-0.1.0.jar", // "--version" ).setRedirectErrorStream(true).grabOutputString().setFailFast(true).getOutputString(); @@ -47,24 +49,4 @@ public void execURL() throws Exception { Assertions.assertFalse(result.contains("[0m"),"Message should not contain terminal format"); } - @BeforeAll - public static void setUpClass() throws IOException { - TestUtils.println("####### RUNNING TEST @ "+ TestUtils.getCallerClassSimpleName()); - } - - @AfterAll - public static void tearUpClass() throws IOException { - } - - @BeforeEach - public void startup() throws IOException { -// Assumptions.assumeTrue(NutsOsFamily.getCurrent()== NutsOsFamily.LINUX); - TestUtils.unsetNutsSystemProperties(); - } - - @AfterEach - public void cleanup() { - TestUtils.unsetNutsSystemProperties(); - } - } diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test11_LogTest.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test11_LogTest.java index f0eb496ce..729fb927e 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test11_LogTest.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test11_LogTest.java @@ -6,6 +6,7 @@ package net.thevpc.nuts.core.test.blackbox; import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.NutsVersionFormat; import net.thevpc.nuts.core.test.utils.TestUtils; import net.thevpc.nuts.NutsOsFamily; import net.thevpc.nuts.NutsWorkspace; @@ -29,7 +30,7 @@ public void execURL() throws Exception { "--archetype", "default", "--skip-companions"); - TestUtils.println(ws.version().formatter()); + TestUtils.println(NutsVersionFormat.of(ws)); String result = ws.exec() .addExecutorOption("--main-class=Version") .addCommand( diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test12_CopyTest.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test12_CopyTest.java index 3033902fd..f7e6b07ec 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test12_CopyTest.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test12_CopyTest.java @@ -7,7 +7,6 @@ import net.thevpc.nuts.core.test.utils.TestUtils; import net.thevpc.nuts.*; -import net.thevpc.nuts.runtime.core.util.CoreIOUtils; import org.junit.jupiter.api.*; import java.io.BufferedWriter; @@ -16,10 +15,6 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.stream.Collectors; /** * @@ -34,9 +29,9 @@ public void copy01() throws Exception { "--archetype", "default", "--log-info", "--skip-companions"); - NutsPath from = session.io().tmp() + NutsPath from = NutsTmp.of(session) .createTempFolder("source"); - NutsPath to = session.io().tmp() + NutsPath to = NutsTmp.of(session) .createTempFolder("target"); TestUtils.println("from="+from); TestUtils.println("to="+to); @@ -58,7 +53,7 @@ public void copy01() throws Exception { } TestUtils.println("start-----------"); - session.io().copy().from(from).to(to) + NutsCp.of(session).from(from).to(to) .setLogProgress(true) .setProgressMonitor(new NutsProgressMonitor() { @Override diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test13_Color.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test13_Color.java index 3ce91ac4e..7d7add21b 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test13_Color.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test13_Color.java @@ -56,14 +56,14 @@ public static void testMode(NutsSession session,NutsTerminalMode systemMode,Nuts Assertions.assertThrows(NutsIllegalArgumentException.class,()-> { - NutsSystemTerminal systemTerminal = session.term().getSystemTerminal(); + NutsSystemTerminal systemTerminal = session.config().getSystemTerminal(); NutsPrintStream sysInitMode = systemTerminal.out(); TestUtils.println( "sys-init="+(sysInitMode.mode()==null?"default": sysInitMode.mode().id()) +", sys-fixed="+(systemMode==null?"default":systemMode.id()) +" ->"+sessionMode.id()); - NutsSessionTerminal terminal = session.term().createTerminal(); + NutsSessionTerminal terminal = NutsSessionTerminal.of(session); NutsPrintStream out = terminal.out().setMode(systemMode); NutsTerminalMode initMode = out.mode(); Assertions.assertEquals(systemMode,initMode); @@ -86,9 +86,9 @@ public static void testMode(NutsSession session,NutsTerminalMode systemMode,Nuts ); return; }else{ - NutsSystemTerminal systemTerminal = session.term().getSystemTerminal(); + NutsSystemTerminal systemTerminal = session.config().getSystemTerminal(); NutsPrintStream sysInitMode = systemTerminal.out(); - NutsSessionTerminal terminal = session.term().createTerminal(); + NutsSessionTerminal terminal = NutsSessionTerminal.of(session); NutsPrintStream out = terminal.out().setMode(systemMode); NutsTerminalMode initMode = out.mode(); Assertions.assertEquals(systemMode,initMode); @@ -113,7 +113,7 @@ public void testBuilder(){ NutsSession session = TestUtils.openNewTestWorkspace( "--archetype", "minimal", "--skip-companions"); - NutsText c = session.text().ofCode("java", "public static void main(String[] args){}") + NutsText c = NutsTexts.of(session).ofCode("java", "public static void main(String[] args){}") .highlight(session); session.out().printlnf(c); @@ -124,7 +124,7 @@ public void testBuilder(){ NutsText portion_npar = c.builder().substring(22, 24); session.out().printlnf(portion_npar); Assertions.assertEquals("n##:separator:(##\u001E",portion_npar.toString()); - NutsText rep=c.builder().replace(23,24,session.text().ofStyled("()(",NutsTextStyle.danger())).build(); + NutsText rep=c.builder().replace(23,24,NutsTexts.of(session).ofStyled("()(",NutsTextStyle.danger())).build(); session.out().printlnf(rep); Assertions.assertEquals("##:keyword:public##\u001E ##:keyword:static##\u001E ##:keyword:void##\u001E main##:danger:()(##\u001EString##:separator:[##\u001E##:separator:]##\u001E args##:separator:)##\u001E##:separator:{##\u001E##:separator:}##\u001E", rep.toString()); diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test14_Commandline.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test14_Commandline.java index 60f7e1175..98f5029ed 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test14_Commandline.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test14_Commandline.java @@ -31,7 +31,7 @@ public void test1() throws Exception { "--skip-welcome" ); - NutsArgument[] cmd = session.commandLine().parse("-ad+ +ad--").toArgumentArray(); + NutsArgument[] cmd = NutsCommandLine.parse("-ad+ +ad--",session).toArgumentArray(); Set set = Arrays.stream(cmd).map(x -> x.toString()).collect(Collectors.toSet()); Set expectedSet = new HashSet<>(Arrays.asList( "-a", "-d+", "+a","+d--" diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test15_Yaml.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test15_Yaml.java index 8ac5e5b8e..0c460958b 100644 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test15_Yaml.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test15_Yaml.java @@ -55,9 +55,10 @@ public static void setUpClass() throws IOException { public void test1() throws Exception { NutsSession ws = TestUtils.openNewTestWorkspace("-byZSKk"); String path = "net/thevpc/nuts/core/test/blackbox/yaml1.yml"; - NutsElement e = ws.elem().setContentType(NutsContentType.YAML) + NutsElements elem = NutsElements.of(ws); + NutsElement e = elem.setContentType(NutsContentType.YAML) .parse(getClass().getClassLoader().getResource(path), NutsElement.class); - ws.elem().setContentType(NutsContentType.JSON).setValue(e) + elem.json().setValue(e) .setCompact(false) .println(); } diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test17_Json.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test17_Json.java index e7ee48173..098bc1b7f 100644 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test17_Json.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test17_Json.java @@ -54,11 +54,11 @@ public void test1() throws Exception { // .setNtf(false) // .format(); -// System.out.println(session.text().forPlain("a@@@")); -// System.out.println(session.text().forPlain("a@@@").filteredText()); +// System.out.println(NutsTexts.of(session).forPlain("a@@@")); +// System.out.println(NutsTexts.of(session).forPlain("a@@@").filteredText()); - System.out.println(session.text().ofPlain("a##@")); - System.out.println(session.text().ofPlain("a##@").filteredText()); + System.out.println(NutsTexts.of(session).ofPlain("a##@")); + System.out.println(NutsTexts.of(session).ofPlain("a##@").filteredText()); } @@ -67,7 +67,7 @@ public void test2() { NutsSession ws = TestUtils.openNewTestWorkspace( "-byZSKk" ); - NutsElement a = ws.elem().setContentType(NutsContentType.JSON) + NutsElement a = NutsElements.of(ws).json() .parse( "{\n" + " title: 'NCA Coding Standards',\n" + @@ -218,11 +218,11 @@ public void test2() { // .setNtf(false) // .format(); -// System.out.println(session.text().forPlain("a@@@")); -// System.out.println(session.text().forPlain("a@@@").filteredText()); +// System.out.println(NutsTexts.of(session).forPlain("a@@@")); +// System.out.println(NutsTexts.of(session).forPlain("a@@@").filteredText()); - System.out.println(ws.text().ofPlain("a##@")); - System.out.println(ws.text().ofPlain("a##@").filteredText()); + System.out.println(NutsTexts.of(ws).ofPlain("a##@")); + System.out.println(NutsTexts.of(ws).ofPlain("a##@").filteredText()); } diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test19_expr.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test19_expr.java new file mode 100644 index 000000000..ca4cdb695 --- /dev/null +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/blackbox/Test19_expr.java @@ -0,0 +1,94 @@ +/** + * ==================================================================== + * Nuts : Network Updatable Things Service + * (universal package manager) + *
    + * is a new Open Source Package Manager to help install packages and libraries + * for runtime execution. Nuts is the ultimate companion for maven (and other + * build managers) as it helps installing all package dependencies at runtime. + * Nuts is not tied to java and is a good choice to share shell scripts and + * other 'things' . Its based on an extensible architecture to help supporting a + * large range of sub managers / repositories. + *
    + *

    + * Copyright [2020] [thevpc] Licensed under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law + * or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + *
    ==================================================================== + */ +package net.thevpc.nuts.core.test.blackbox; + +import net.thevpc.nuts.NutsExpr; +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.core.test.utils.TestUtils; +import org.junit.jupiter.api.*; + +import java.io.IOException; + +/** + * + * @author vpc + */ +public class Test19_expr { + + + @AfterAll + public static void tearUpClass() throws IOException { + //CoreIOUtils.delete(null,new File(baseFolder)); + } + private void _retain(NutsExpr expr,String... patterns){ + for (NutsExpr.OpType opt : NutsExpr.OpType.values()) { + for (String o : expr.getOperatorNames(opt)) { + boolean ok=false; + for (String pattern : patterns) { + if(pattern.startsWith("prefix:")) { + String so = pattern.substring("prefix:".length()); + if ((o.equals(so) && opt == NutsExpr.OpType.INFIX)) { + ok = true; + break; + } + }else if(pattern.startsWith("infix:")){ + String so=pattern.substring("infix:".length()); + if((o.equals(so) && opt== NutsExpr.OpType.INFIX)) { + ok=true; + break; + } + }else if(pattern.startsWith("postfix:")){ + String so=pattern.substring("postfix:".length()); + if((o.equals(so) && opt== NutsExpr.OpType.POSTFIX)) { + ok=true; + break; + } + } + } + if(!ok){ + expr.setOperator(o, opt, -1, false, null); + } + } + } + } + @Test + public void test1() throws Exception { + NutsSession session = TestUtils.openNewTestWorkspace(); + NutsExpr expr = NutsExpr.of(session); + _retain(expr,"infix:+"); + NutsExpr.Node n = expr.parse("1+2*3"); + System.out.println(n); + } + + @BeforeEach + public void startup() throws IOException { + //Assumptions.assumeTrue(Nuts.getPlatformOsFamily() == NutsOsFamily.LINUX); + TestUtils.unsetNutsSystemProperties(); + } + + @AfterEach + public void cleanup() { + TestUtils.unsetNutsSystemProperties(); + } +} diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/bundles/ntf/Test07_ColorfulStream.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/bundles/ntf/Test07_ColorfulStream.java index 4fc362a20..e2660c711 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/bundles/ntf/Test07_ColorfulStream.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/bundles/ntf/Test07_ColorfulStream.java @@ -45,7 +45,7 @@ private static void writeColors(String s) { NutsSession ws = TestUtils.openNewTestWorkspace("--verbose","--skip-companions"); { NutsText node = new DefaultNutsTextNodeParser(ws).parse(new StringReader(s)); - NutsTextNodeWriter w = new NutsTextNodeWriterRenderer(ws.io().stdout(), AnsiUnixTermPrintRenderer.ANSI_RENDERER, ws) + NutsTextNodeWriter w = new NutsTextNodeWriterRenderer(NutsPrintStreams.of(ws).stdout(), AnsiUnixTermPrintRenderer.ANSI_RENDERER, ws) .setWriteConfiguration(new NutsTextWriteConfiguration().setTitleNumberEnabled(true)); w.writeNode(node); } @@ -482,7 +482,7 @@ private static void writeColors(String s) { // // NutsWorkspace ws = TestUtils.openNewTestWorkspace(); // { -// NutsText command = ws.text().command(NutsTerminalManager.CMD_LATER_RESET_LINE); +// NutsText command = ws.text().command(NutsTerminals.CMD_LATER_RESET_LINE); // NutsTextNodeWriter w = new NutsTextNodeWriterRenderer(System.out, AnsiUnixTermPrintRenderer.ANSI_RENDERER, ws) // .setWriteConfiguration(new NutsTextWriteConfiguration().setTitleNumberEnabled(true)); // w.writeNode(command); @@ -500,7 +500,7 @@ private static void writeColors(String s) { // NutsWorkspace ws = TestUtils.openNewTestWorkspace(); // NutsSession session = ws.createSession(); // session.out().print("Hi"); -// ws.io().term().sendCommand(session.out(), NutsTerminalManager.CMD_LATER_RESET_LINE); +// ws.io().term().sendCommand(session.out(), NutsTerminals.CMD_LATER_RESET_LINE); // session.out().print("Bye"); // } // diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test01_TestInputSource.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test01_TestInputSource.java index 1b35ac918..1124e8889 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test01_TestInputSource.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test01_TestInputSource.java @@ -19,20 +19,20 @@ public class Test01_TestInputSource { @Test public void test1() throws Exception { NutsSession session = TestUtils.openNewTestWorkspace(); - NutsPath s = session.io().path("http://maven.ibiblio.org/maven2/archetype-catalog.xml"); + NutsPath s = NutsPath.of("http://maven.ibiblio.org/maven2/archetype-catalog.xml",session); //this is a remote file Assertions.assertFalse(s.isFile()); //the file is actually a http url Assertions.assertTrue(s.isURL()); - s = session.io().path("file://maven.ibiblio.org/maven2/archetype-catalog.xml"); + s = NutsPath.of("file://maven.ibiblio.org/maven2/archetype-catalog.xml",session); //the file has an 'authority' (//) so it cannot be converted to a valid file Assertions.assertFalse(s.isFile()); //the file is actually a file url Assertions.assertTrue(s.isURL()); - s = session.io().path("file:/maven.ibiblio.org/maven2/archetype-catalog.xml"); + s = NutsPath.of("file:/maven.ibiblio.org/maven2/archetype-catalog.xml",session); //the file is actually a file url Assertions.assertTrue(s.isFile()); //the file is actually a URL @@ -41,7 +41,7 @@ public void test1() throws Exception { // s = CoreIOUtils.createInputSource("zip://maven.ibiblio.org/maven2/toto.zip?archetype-catalog.xml"); // Assertions.assertFalse(s.isPath()); // Assertions.assertTrue(s.isURL()); - s = session.io().path("/maven.ibiblio.org/maven2/archetype-catalog.xml"); + s = NutsPath.of("/maven.ibiblio.org/maven2/archetype-catalog.xml",session); //the file is actually a file Assertions.assertTrue(s.isFile()); //the file can be converted to URL diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test06_CacheURL.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test06_CacheURL.java index 2f14274fa..fe52b01e9 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test06_CacheURL.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test06_CacheURL.java @@ -12,8 +12,6 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; import net.thevpc.nuts.runtime.core.util.CoreIOUtils; import org.junit.jupiter.api.*; @@ -37,11 +35,11 @@ public void minimal1() throws Exception { final String url = "https://repo.maven.apache.org/maven2/archetype-catalog.xml"; InputStream j1 = CoreIOUtils.getCachedUrlWithSHA1(url, "archetype-catalog", true,session); //just to consume the stream - session.io().copy().from(j1).to(new ByteArrayOutputStream()).setLogProgress(true).run(); + NutsCp.of(session).from(j1).to(new ByteArrayOutputStream()).setLogProgress(true).run(); TestUtils.println(j1); InputStream j2 = CoreIOUtils.getCachedUrlWithSHA1(url, "archetype-catalog", true,session); //just to consume the stream - session.io().copy().from(j2).to(new ByteArrayOutputStream()).setLogProgress(true).run(); + NutsCp.of(session).from(j2).to(new ByteArrayOutputStream()).setLogProgress(true).run(); TestUtils.println(j2); } diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test09_VersionIntervals.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test09_VersionIntervals.java index 44f3eae12..9d9dcf2ad 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test09_VersionIntervals.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test09_VersionIntervals.java @@ -25,10 +25,7 @@ */ package net.thevpc.nuts.core.test.whitebox; -import net.thevpc.nuts.Nuts; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsVersionFilter; -import net.thevpc.nuts.NutsWorkspace; +import net.thevpc.nuts.*; import net.thevpc.nuts.core.test.utils.TestUtils; import net.thevpc.nuts.runtime.core.filters.version.DefaultNutsVersionFilter; import org.junit.jupiter.api.*; @@ -62,6 +59,6 @@ private void check(String a, String b) { @Test public void test2(){ NutsSession session = TestUtils.openNewTestWorkspace(); - TestUtils.println(session.version().parser().parse("").inc(-1).getValue()); + TestUtils.println(NutsVersion.of("",session).inc(-1).getValue()); } } diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test10_ElementPath.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test10_ElementPath.java index 5a77545a1..26aca9557 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test10_ElementPath.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test10_ElementPath.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -10,19 +10,19 @@ * to share shell scripts and other 'things' . Its based on an extensible * architecture to help supporting a large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.core.test.whitebox; import java.io.IOException; @@ -39,53 +39,58 @@ */ public class Test10_ElementPath { + @BeforeAll + public static void setUpClass() throws IOException { + TestUtils.println("####### RUNNING TEST @ " + TestUtils.getCallerClassSimpleName()); + } + @Test public void test1() { NutsSession ws = TestUtils.openNewTestWorkspace(); - NutsElementFormat e = ws.elem(); + NutsElements e = NutsElements.of(ws); NutsElement p = e.forArray() - .add( - e.forObject().set("first", + .add( + e.forObject().set("first", e.forObject() .set("name", e.forString("first name")) .set("valid", e.forTrue()) .set("children", e.forArray().add( - e.forObject() - .set("path", e.forString("path1")) - .set("color", e.forString("red")) - .build()) + e.forObject() + .set("path", e.forString("path1")) + .set("color", e.forString("red")) + .build()) .add( e.forObject() .set("path", e.forString("path2")) .set("color", e.forString("green")) - .build() + .build() ).build() ) - .build() + .build() ) .build() - ).add(e.forObject().set("second", - e.forObject() - .set("name", e.forString("second name")) - .set("valid", e.forTrue()) - .set("children", - e.forArray().add( + ).add(e.forObject().set("second", + e.forObject() + .set("name", e.forString("second name")) + .set("valid", e.forTrue()) + .set("children", + e.forArray().add( e.forObject() .set("path", e.forString("path3")) .set("color", e.forString("yellow")) - .build() + .build() ) - .add( - e.forObject() - .set("path", e.forString("path4")) - .set("color", e.forString("magenta")) + .add( + e.forObject() + .set("path", e.forString("path4")) + .set("color", e.forString("magenta")) .build() - ).build() - ) - .build() - ).build()) + ).build() + ) + .build() + ).build()) .build(); NutsObjectFormat ss = ws.json().formats().object(p); ss.println(); @@ -127,8 +132,8 @@ public void test1() { class TT { - String path; - List expected; + final String path; + final List expected; public TT(String path, String... expected) { this.path = path; @@ -141,136 +146,131 @@ void check(List a) { } for (TT tt : new TT[]{ - new TT("","[\n" + -" [\n" + -" {\n" + -" \"first\": {\n" + -" \"name\": \"first name\",\n" + -" \"valid\": true,\n" + -" \"children\": [\n" + -" {\n" + -" \"path\": \"path1\",\n" + -" \"color\": \"red\"\n" + -" },\n" + -" {\n" + -" \"path\": \"path2\",\n" + -" \"color\": \"green\"\n" + -" }\n" + -" ]\n" + -" }\n" + -" },\n" + -" {\n" + -" \"second\": {\n" + -" \"name\": \"second name\",\n" + -" \"valid\": true,\n" + -" \"children\": [\n" + -" {\n" + -" \"path\": \"path3\",\n" + -" \"color\": \"yellow\"\n" + -" },\n" + -" {\n" + -" \"path\": \"path4\",\n" + -" \"color\": \"magenta\"\n" + -" }\n" + -" ]\n" + -" }\n" + -" }\n" + -" ]\n" + -"]"), - new TT(".","[\n" + -" {\n" + -" \"first\": {\n" + -" \"name\": \"first name\",\n" + -" \"valid\": true,\n" + -" \"children\": [\n" + -" {\n" + -" \"path\": \"path1\",\n" + -" \"color\": \"red\"\n" + -" },\n" + -" {\n" + -" \"path\": \"path2\",\n" + -" \"color\": \"green\"\n" + -" }\n" + -" ]\n" + -" }\n" + -" },\n" + -" {\n" + -" \"second\": {\n" + -" \"name\": \"second name\",\n" + -" \"valid\": true,\n" + -" \"children\": [\n" + -" {\n" + -" \"path\": \"path3\",\n" + -" \"color\": \"yellow\"\n" + -" },\n" + -" {\n" + -" \"path\": \"path4\",\n" + -" \"color\": \"magenta\"\n" + -" }\n" + -" ]\n" + -" }\n" + -" }\n" + -"]"), - new TT("*","[\n" + -" {\n" + -" \"first\": {\n" + -" \"name\": \"first name\",\n" + -" \"valid\": true,\n" + -" \"children\": [\n" + -" {\n" + -" \"path\": \"path1\",\n" + -" \"color\": \"red\"\n" + -" },\n" + -" {\n" + -" \"path\": \"path2\",\n" + -" \"color\": \"green\"\n" + -" }\n" + -" ]\n" + -" }\n" + -" },\n" + -" {\n" + -" \"second\": {\n" + -" \"name\": \"second name\",\n" + -" \"valid\": true,\n" + -" \"children\": [\n" + -" {\n" + -" \"path\": \"path3\",\n" + -" \"color\": \"yellow\"\n" + -" },\n" + -" {\n" + -" \"path\": \"path4\",\n" + -" \"color\": \"magenta\"\n" + -" }\n" + -" ]\n" + -" }\n" + -" }\n" + -"]"), - new TT(".*.name","[\n" + -" \"first name\",\n" + -" \"second name\"\n" + -"]"), - new TT("..name","[\n" + -" \"first name\",\n" + -" \"second name\"\n" + -"]"), - new TT("*.*.name","[\n" + -" \"first name\",\n" + -" \"second name\"\n" + -"]") + new TT("", "[\n" + + " [\n" + + " {\n" + + " \"first\": {\n" + + " \"name\": \"first name\",\n" + + " \"valid\": true,\n" + + " \"children\": [\n" + + " {\n" + + " \"path\": \"path1\",\n" + + " \"color\": \"red\"\n" + + " },\n" + + " {\n" + + " \"path\": \"path2\",\n" + + " \"color\": \"green\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " },\n" + + " {\n" + + " \"second\": {\n" + + " \"name\": \"second name\",\n" + + " \"valid\": true,\n" + + " \"children\": [\n" + + " {\n" + + " \"path\": \"path3\",\n" + + " \"color\": \"yellow\"\n" + + " },\n" + + " {\n" + + " \"path\": \"path4\",\n" + + " \"color\": \"magenta\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + " ]\n" + + "]"), + new TT(".", "[\n" + + " {\n" + + " \"first\": {\n" + + " \"name\": \"first name\",\n" + + " \"valid\": true,\n" + + " \"children\": [\n" + + " {\n" + + " \"path\": \"path1\",\n" + + " \"color\": \"red\"\n" + + " },\n" + + " {\n" + + " \"path\": \"path2\",\n" + + " \"color\": \"green\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " },\n" + + " {\n" + + " \"second\": {\n" + + " \"name\": \"second name\",\n" + + " \"valid\": true,\n" + + " \"children\": [\n" + + " {\n" + + " \"path\": \"path3\",\n" + + " \"color\": \"yellow\"\n" + + " },\n" + + " {\n" + + " \"path\": \"path4\",\n" + + " \"color\": \"magenta\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + "]"), + new TT("*", "[\n" + + " {\n" + + " \"first\": {\n" + + " \"name\": \"first name\",\n" + + " \"valid\": true,\n" + + " \"children\": [\n" + + " {\n" + + " \"path\": \"path1\",\n" + + " \"color\": \"red\"\n" + + " },\n" + + " {\n" + + " \"path\": \"path2\",\n" + + " \"color\": \"green\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " },\n" + + " {\n" + + " \"second\": {\n" + + " \"name\": \"second name\",\n" + + " \"valid\": true,\n" + + " \"children\": [\n" + + " {\n" + + " \"path\": \"path3\",\n" + + " \"color\": \"yellow\"\n" + + " },\n" + + " {\n" + + " \"path\": \"path4\",\n" + + " \"color\": \"magenta\"\n" + + " }\n" + + " ]\n" + + " }\n" + + " }\n" + + "]"), + new TT(".*.name", "[\n" + + " \"first name\",\n" + + " \"second name\"\n" + + "]"), + new TT("..name", "[\n" + + " \"first name\",\n" + + " \"second name\"\n" + + "]"), + new TT("*.*.name", "[\n" + + " \"first name\",\n" + + " \"second name\"\n" + + "]") }) { TestUtils.println("====================================="); - TestUtils.println("CHECKING : '" + tt.path+"'"); + TestUtils.println("CHECKING : '" + tt.path + "'"); List filtered1 = e.compilePath(tt.path).filter(p); ss.setValue(filtered1).println(); NutsString sexpected = NutsString.plain(tt.expected.get(0), e.getSession()); - NutsString sresult = ss.format(); - Assertions.assertEquals(sexpected, sresult); + NutsString sresult = ss.format().immutable(); + Assertions.assertEquals(sexpected.immutable(), sresult.immutable()); } } - @BeforeAll - public static void setUpClass() throws IOException { - TestUtils.println("####### RUNNING TEST @ "+ TestUtils.getCallerClassSimpleName()); - } - } diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test12_ParseNTF.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test12_ParseNTF.java index 6fa523328..e649ba6cc 100755 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test12_ParseNTF.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/Test12_ParseNTF.java @@ -34,8 +34,6 @@ import java.io.File; import java.io.IOException; -import java.util.HashMap; -import java.util.Map; /** * @author thevpc @@ -60,7 +58,7 @@ public void test1() { NutsSession session = TestUtils.openNewTestWorkspace( "--standalone", "--skip-companions"); - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); NutsText parsed = txt.parse("##:error0:n#01##"); System.out.println(parsed); } @@ -72,7 +70,7 @@ public void test2() { "-Z", "--yes", "--skip-companions"); - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); // String str="missing command. try ```sh ndocusaurus pdf | start | build```"; String str = "##:p2:╭───╮##\u001E\n##:p3:│##"; @@ -92,7 +90,7 @@ public void test3() { "-Z", "--yes", "--skip-companions"); - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); // String str="missing command. try ```sh ndocusaurus pdf | start | build```"; String str = "##:p2:╭───╮##\u001E\n##:p3:│##"; @@ -109,7 +107,7 @@ public void test4() { "--standalone", "-Z", "--skip-companions"); - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); // String str="missing command. try ```sh ndocusaurus pdf | start | build```"; //String str="##{error0:##{error0:not installed : ##:p1:ntomcat##\u001E}}##\u001E}##\u001E"; @@ -126,7 +124,7 @@ public void test5() { "--standalone", "-Z", "--skip-companions"); - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); String str = "##:separator0:{##\u001E\n" + " ##:string0:\"id\"##\u001E##:separator0::##\u001E ##:string0:\"

    ://com.github.vatbub:mslinks#1.0.5\"##\u001E##:separator0:,##\u001E\n" + @@ -179,7 +177,7 @@ public void test6() { "--standalone", "-Z", "--skip-companions"); - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); String str = "##:separator0:{##\u001E\n" + " ##:string0:\"id\"##\u001E##:separator0::##\u001E ##{string0:\"
    ://com.github.vatbub:mslinks#1.0.5\"}##\u001E##:separator0:,##\u001E\n" + @@ -233,7 +231,7 @@ public void test7() { "--standalone", "-Z", "--skip-companions"); - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); // String str = "##{string0:\"
    ://com.github.vatbub:mslinks#1.0.5\"}##"; String str = "##{string:a#b}##"; @@ -246,7 +244,7 @@ public void test7() { @Test public void test8() { NutsSession session = TestUtils.openNewTestWorkspace("-ZSkK"); - NutsTextManager txt = session.text(); + NutsTexts txt = NutsTexts.of(session); // String str = "##{string0:\"
    ://com.github.vatbub:mslinks#1.0.5\"}##"; String str = "##:string:\"a#b\"##"; diff --git a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/TestDev.java b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/TestDev.java index 838c0a2ba..b97fd9f68 100644 --- a/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/TestDev.java +++ b/test/nuts-runtime-test/src/test/java/net/thevpc/nuts/core/test/whitebox/TestDev.java @@ -1,9 +1,6 @@ package net.thevpc.nuts.core.test.whitebox; -import net.thevpc.nuts.NutsMessage; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsString; -import net.thevpc.nuts.NutsWorkspace; +import net.thevpc.nuts.*; import net.thevpc.nuts.core.test.utils.TestUtils; import org.junit.jupiter.api.Test; @@ -13,7 +10,7 @@ void test() { NutsSession session = TestUtils.openNewTestWorkspace(); - NutsString s = session.text().toText( + NutsString s = NutsTexts.of(session).toText( NutsMessage.cstyle("%s", "Hello") ); diff --git a/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/FileLookup.java b/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/FileLookup.java index 4bf9f5c8a..e9f5389a6 100644 --- a/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/FileLookup.java +++ b/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/FileLookup.java @@ -6,6 +6,7 @@ package net.thevpc.nuts.toolbox.ncode; import net.thevpc.nuts.NutsApplicationContext; +import net.thevpc.nuts.NutsPath; import net.thevpc.nuts.NutsSession; /** @@ -18,7 +19,7 @@ public FileLookup() { @Override public Object process(Source source, NutsSession session) { - return session.io().path(source.getExternalPath()); + return NutsPath.of(source.getExternalPath(),session); } } diff --git a/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/processors/JavaSourceFormatter.java b/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/processors/JavaSourceFormatter.java index 025e6a7bc..3e47060ee 100644 --- a/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/processors/JavaSourceFormatter.java +++ b/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/processors/JavaSourceFormatter.java @@ -8,6 +8,7 @@ import net.thevpc.nuts.NutsMessage; import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.NutsTextStyle; +import net.thevpc.nuts.NutsTexts; import net.thevpc.nuts.toolbox.ncode.SourceProcessor; import net.thevpc.nuts.toolbox.ncode.Source; import net.thevpc.nuts.toolbox.ncode.sources.JavaTypeSource; @@ -34,16 +35,16 @@ public Object process(Source source, NutsSession session) { } return NutsMessage.cstyle( "%s %s %s %s", - session.text().ofStyled(leftAlign(v1, 4), NutsTextStyle.config()), - session.text().ofStyled(leftAlign(v2, 4), NutsTextStyle.info()), - session.text().ofStyled(leftAlign(n, clsNameSize), NutsTextStyle.primary1()), - session.text().ofStyled(source.getExternalPath(), NutsTextStyle.path()), + NutsTexts.of(session).ofStyled(leftAlign(v1, 4), NutsTextStyle.config()), + NutsTexts.of(session).ofStyled(leftAlign(v2, 4), NutsTextStyle.info()), + NutsTexts.of(session).ofStyled(leftAlign(n, clsNameSize), NutsTextStyle.primary1()), + NutsTexts.of(session).ofStyled(source.getExternalPath(), NutsTextStyle.path()), source.toString() ); } else { return NutsMessage.cstyle( "%s : %s", - session.text().ofStyled("invalid source", NutsTextStyle.error()), + NutsTexts.of(session).ofStyled("invalid source", NutsTextStyle.error()), source.toString() ); } diff --git a/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/processors/PathSourceFormatter.java b/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/processors/PathSourceFormatter.java index 8b68461ab..a4701cdf4 100644 --- a/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/processors/PathSourceFormatter.java +++ b/toolbox/ncode/src/main/java/net/thevpc/nuts/toolbox/ncode/processors/PathSourceFormatter.java @@ -6,6 +6,7 @@ package net.thevpc.nuts.toolbox.ncode.processors; import net.thevpc.nuts.NutsApplicationContext; +import net.thevpc.nuts.NutsPath; import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.toolbox.ncode.SourceProcessor; import net.thevpc.nuts.toolbox.ncode.Source; @@ -20,7 +21,7 @@ public PathSourceFormatter() { @Override public Object process(Source source, NutsSession session) { - return session.io().path(source.getExternalPath()); + return NutsPath.of(source.getExternalPath(),session); } } diff --git a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/DerbyService.java b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/DerbyService.java index 0eadca4f5..3d98511d5 100644 --- a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/DerbyService.java +++ b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/DerbyService.java @@ -47,13 +47,12 @@ public class DerbyService { public DerbyService(NutsApplicationContext appContext) { this.appContext = appContext; - LOG = appContext.getSession().log().of(getClass()); + LOG = NutsLogger.of(getClass(),appContext.getSession()); } public boolean isRunning() { DerbyOptions options=new DerbyOptions(); options.cmd=Command.ping; - NutsTextManager factory = appContext.getSession().text(); try { String s= command(options).setFailFast(true).grabOutputString().getOutputString(); if(s!=null){ @@ -131,7 +130,7 @@ public static String getAbsoluteFile(String path, String cwd) { } private Path download(String id, Path folder, boolean optional) { - final NutsId iid = appContext.getSession().id().parser().parse(id); + final NutsId iid = NutsId.of(id, appContext.getSession()); // Path downloadBaseFolder = folder//.resolve(iid.getVersion().getValue()); Path targetFile = folder.resolve(iid.getArtifactId() + ".jar"); if (!Files.exists(targetFile)) { @@ -155,7 +154,7 @@ public Set findVersions() { NutsId java = session.env().getPlatform(); List all = session.search().setSession(appContext.getSession().copy()).addId("org.apache.derby:derbynet").setDistinct(true) .setIdFilter( - (java.getVersion().compareTo("1.9") < 0) ? session.version().filter().byValue("[,10.15.1.3[").to(NutsIdFilter.class) : + (java.getVersion().compareTo("1.9") < 0) ? NutsVersionFilters.of(session).byValue("[,10.15.1.3[").to(NutsIdFilter.class) : null) .getResultIds().stream().map(x -> x.getVersion().toString()).collect(Collectors.toList()); TreeSet lastFirst = new TreeSet<>(new Comparator() { @@ -177,7 +176,7 @@ public NutsExecCommand command(DerbyOptions options) { NutsId java = session.env().getPlatform(); NutsId best = session.search().setSession(appContext.getSession().copy()).addId("org.apache.derby:derbynet").setDistinct(true).setLatest(true) .setIdFilter( - (java.getVersion().compareTo("1.9") < 0) ? session.version().filter().byValue("[,10.15.1.3[").to(NutsIdFilter.class) : + (java.getVersion().compareTo("1.9") < 0) ? NutsVersionFilters.of(session).byValue("[,10.15.1.3[").to(NutsIdFilter.class) : null) .setSession(appContext.getSession().copy()) .getResultIds().singleton(); diff --git a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/DerbyUtils.java b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/DerbyUtils.java index 3307fe1ed..bef4b7aac 100644 --- a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/DerbyUtils.java +++ b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/DerbyUtils.java @@ -5,6 +5,8 @@ import java.io.InputStream; import java.io.UncheckedIOException; import net.thevpc.nuts.NutsApplicationContext; +import net.thevpc.nuts.NutsPs; +import net.thevpc.nuts.NutsSession; public class DerbyUtils { @@ -25,9 +27,11 @@ public static byte[] loadByteArray(InputStream is) { } public static RunningDerby[] getRunningInstances(NutsApplicationContext context) { - return context.getSession().io().ps().type("java").getResultList() + NutsSession session = context.getSession(); + return NutsPs.of(session) + .type("java").getResultList() .stream().filter((p) -> p.getName().equals("org.apache.derby.drda.NetworkServerControl")) - .map(x -> new RunningDerby(x, context.getSession())).toArray(RunningDerby[]::new); + .map(x -> new RunningDerby(x, session)).toArray(RunningDerby[]::new); } } diff --git a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/NDerbyMain.java b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/NDerbyMain.java index d82202400..55e814f85 100644 --- a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/NDerbyMain.java +++ b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/NDerbyMain.java @@ -69,7 +69,7 @@ public void run(NutsApplicationContext appContext, NutsCommandLine cmdLine) { DerbyService srv = new DerbyService(appContext); int effectivePort = options.port < 0 ? 1527 : options.port; if (options.cmd == Command.start) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (cmdLine.isExecMode()) { if (new DerbyService(appContext).isRunning()) { session.out().printf("derby is %s on port %s%n", @@ -80,7 +80,7 @@ public void run(NutsApplicationContext appContext, NutsCommandLine cmdLine) { } } } else if (options.cmd == Command.shutdown) { - NutsTextManager factory = appContext.getSession().text(); + NutsTexts factory = NutsTexts.of(appContext.getSession()); if (cmdLine.isExecMode()) { if (!new DerbyService(appContext).isRunning()) { session.out().printf("derby is %s on port %s%n", @@ -108,7 +108,7 @@ public void status(NutsCommandLine cmdLine, DerbyOptions options) { } options.cmd = Command.ping; NutsSession session = appContext.getSession(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (cmdLine.isExecMode()) { if (new DerbyService(appContext).isRunning()) { session.out().printf("derby is %s%n", factory.ofStyled("running", NutsTextStyle.primary1())); @@ -165,7 +165,7 @@ public void ps(NutsCommandLine args, DerbyOptions options) { } } NutsSession session = appContext.getSession(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (args.isExecMode()) { if (session.isPlainOut()) { NutsPrintStream out = session.out(); diff --git a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/RunningDerby.java b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/RunningDerby.java index b5c7af15d..ee2da13b8 100644 --- a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/RunningDerby.java +++ b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/derby/RunningDerby.java @@ -12,7 +12,7 @@ public class RunningDerby { public RunningDerby(NutsProcessInfo r, NutsSession session) { pid =r.getPid(); argsLine=r.getCommandLine(); - NutsCommandLine cmdline = session.commandLine().parse(r.getCommandLine()).setExpandSimpleOptions(false); + NutsCommandLine cmdline = NutsCommandLine.parse(r.getCommandLine(),session).setExpandSimpleOptions(false); NutsArgument a=null; while(cmdline.hasNext()){ if((a=cmdline.nextString("-Dderby.system.home"))!=null) { diff --git a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/NMysqlMain.java b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/NMysqlMain.java index 85ac4fc46..260f18292 100644 --- a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/NMysqlMain.java +++ b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/NMysqlMain.java @@ -433,7 +433,7 @@ private void createOrUpdate(NutsCommandLine commandLine, boolean add, NMySqlServ commandLine.required(NutsMessage.cstyle("required --server option")); } NutsSession session = service.getContext().getSession(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (commandLine.isExecMode()) { if (!expectedRemote) { LocalMysqlConfigService c = service.loadLocalMysqlConfig(name.getConfigName(), add ? NutsOpenMode.OPEN_OR_CREATE : NutsOpenMode.OPEN_OR_ERROR); @@ -786,7 +786,7 @@ public void runRemove(NutsCommandLine commandLine, NMySqlService service) { } public Object toObject(String dbName, String confName, LocalMysqlDatabaseConfig config, boolean describe, boolean plain, NutsApplicationContext context) { - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); if (!describe) { if (plain) { return text.builder() @@ -810,7 +810,7 @@ public Object toObject(String dbName, String confName, LocalMysqlDatabaseConfig } public Object toObject(String dbName, String confName, RemoteMysqlDatabaseConfig config, boolean describe, boolean plain, NutsApplicationContext context) { - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); if (!describe) { if (plain) { return text.builder() diff --git a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/local/LocalMysqlConfigService.java b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/local/LocalMysqlConfigService.java index 1026dbba8..38b8e9f77 100644 --- a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/local/LocalMysqlConfigService.java +++ b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/local/LocalMysqlConfigService.java @@ -56,7 +56,7 @@ public LocalMysqlConfig getConfig() { public LocalMysqlConfigService saveConfig() { Path f = getServerConfigPath(); - context.getSession().elem().setNtf(false).setContentType(NutsContentType.JSON).setValue(config).print(f); + NutsElements.of(context.getSession()).setNtf(false).json().setValue(config).print(f); return this; } @@ -88,8 +88,9 @@ public String[] parseApps(String[] args) { public LocalMysqlConfigService loadConfig() { String name = getName(); Path f = getServerConfigPath(); + NutsSession session = context.getSession(); if (Files.exists(f)) { - config = context.getSession().elem().setContentType(NutsContentType.JSON).parse(f, LocalMysqlConfig.class); + config = NutsElements.of(session).json().parse(f, LocalMysqlConfig.class); return this; } else if ("default".equals(name)) { //auto create default config @@ -97,7 +98,7 @@ public LocalMysqlConfigService loadConfig() { saveConfig(); return this; } - throw new NutsIllegalArgumentException(context.getSession(),NutsMessage.cstyle("no such mysql config : %s",name)); + throw new NutsIllegalArgumentException(session,NutsMessage.cstyle("no such mysql config : %s",name)); } public LocalMysqlConfigService removeConfig() { @@ -110,7 +111,8 @@ public LocalMysqlConfigService removeConfig() { } public LocalMysqlConfigService write(PrintStream out) { - context.getSession().elem().setContentType(NutsContentType.JSON).setValue(getConfig()).setNtf(false).print(out); + NutsSession session = context.getSession(); + NutsElements.of(session).json().setValue(getConfig()).setNtf(false).print(out); return this; } diff --git a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/local/LocalMysqlDatabaseConfigService.java b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/local/LocalMysqlDatabaseConfigService.java index c79c82d7b..365149d23 100644 --- a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/local/LocalMysqlDatabaseConfigService.java +++ b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/local/LocalMysqlDatabaseConfigService.java @@ -37,7 +37,7 @@ public LocalMysqlDatabaseConfigService remove() { } public NutsString getBracketsPrefix(String str) { - return context.getSession().text().builder() + return NutsTexts.of(context.getSession()).builder() .append("[") .append(str,NutsTextStyle.primary5()) .append("]"); @@ -52,7 +52,8 @@ public String getName() { } public LocalMysqlDatabaseConfigService write(PrintStream out) { - context.getSession().elem().setContentType(NutsContentType.JSON).setValue(getConfig()).setNtf(false).print(out); + NutsSession session = context.getSession(); + NutsElements.of(session).json().setValue(getConfig()).setNtf(false).print(out); return this; } @@ -100,8 +101,9 @@ public ArchiveResult backup(String path) { } } else { if (session.isPlainTrace()) { - session.out().printf("%s create archive %s%n", getBracketsPrefix(getDatabaseName()), session - .text().ofStyled(path,NutsTextStyle.path())); + session.out().printf("%s create archive %s%n", getBracketsPrefix(getDatabaseName()), + NutsTexts.of(session) + .ofStyled(path,NutsTextStyle.path())); } // ProcessBuilder2 p = new ProcessBuilder2().setCommand("sh", "-c", // "set -o pipefail && \"" + mysql.getMysqldumpCommand() + "\" -u \"$CMD_USER\" -p\"$CMD_PWD\" --databases \"$CMD_DB\" | gzip > \"$CMD_FILE\"" diff --git a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/CachedMapFile.java b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/CachedMapFile.java index cceedf3f6..1b2facaed 100644 --- a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/CachedMapFile.java +++ b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/CachedMapFile.java @@ -1,8 +1,6 @@ package net.thevpc.nuts.toolbox.ndb.nmysql.remote; -import net.thevpc.nuts.NutsApplicationContext; -import net.thevpc.nuts.NutsContentType; -import net.thevpc.nuts.NutsId; +import net.thevpc.nuts.*; import java.io.IOException; import java.nio.file.Files; @@ -32,8 +30,9 @@ public CachedMapFile(NutsApplicationContext context, String name, boolean enable if (enabled) { if (Files.isRegularFile(path)) { try { - map = context.getSession().elem() - .setContentType(NutsContentType.JSON) + NutsSession session = context.getSession(); + map = NutsElements.of(session) + .json() .parse(path, Map.class); loaded=true; } catch (Exception ex) { @@ -91,8 +90,9 @@ public void put(String k, String v) { } map.put(k, v); try { - context.getSession().elem().setValue(map) - .setContentType(NutsContentType.JSON) + NutsSession session = context.getSession(); + NutsElements.of(session).setValue(map) + .json() .setNtf(false) .print(path); } catch (Exception ex) { diff --git a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/RemoteMysqlConfigService.java b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/RemoteMysqlConfigService.java index 95ae641c5..4cd2d54ea 100644 --- a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/RemoteMysqlConfigService.java +++ b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/RemoteMysqlConfigService.java @@ -53,7 +53,8 @@ public RemoteMysqlConfigService setConfig(RemoteMysqlConfig config) { public RemoteMysqlConfigService saveConfig() { Path f = getConfigPath(); - context.getSession().elem().setContentType(NutsContentType.JSON).setValue(config) + NutsSession session = context.getSession(); + NutsElements.of(session).json().setValue(config) .setNtf(false).print(f); return this; } @@ -68,12 +69,13 @@ public boolean existsConfig() { } public RemoteMysqlConfigService loadConfig() { + NutsSession session = context.getSession(); if (name == null) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("missing config name"), 2); + throw new NutsExecutionException(session, NutsMessage.cstyle("missing config name"), 2); } Path f = getConfigPath(); if (Files.exists(f)) { - config = context.getSession().elem().setContentType(NutsContentType.JSON) + config = NutsElements.of(session).json() .setNtf(false) .parse(f, RemoteMysqlConfig.class); return this; @@ -92,7 +94,8 @@ public RemoteMysqlConfigService removeConfig() { } public RemoteMysqlConfigService write(PrintStream out) { - context.getSession().elem().setContentType(NutsContentType.JSON).setValue(getConfig()) + NutsSession session = context.getSession(); + NutsElements.of(session).json().setValue(getConfig()) .setNtf(false).print(out); out.flush(); return this; diff --git a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/RemoteMysqlDatabaseConfigService.java b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/RemoteMysqlDatabaseConfigService.java index 811cdf087..37c884096 100644 --- a/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/RemoteMysqlDatabaseConfigService.java +++ b/toolbox/ndb/src/main/java/net/thevpc/nuts/toolbox/ndb/nmysql/remote/RemoteMysqlDatabaseConfigService.java @@ -20,10 +20,10 @@ public class RemoteMysqlDatabaseConfigService { - private RemoteMysqlDatabaseConfig config; - private NutsApplicationContext context; - private RemoteMysqlConfigService client; - private String name; + private final RemoteMysqlDatabaseConfig config; + private final NutsApplicationContext context; + private final RemoteMysqlConfigService client; + private final String name; public RemoteMysqlDatabaseConfigService(String name, RemoteMysqlDatabaseConfig config, RemoteMysqlConfigService client) { this.config = config; @@ -52,19 +52,20 @@ public String getFullName() { } public void write(PrintStream out) { - context.getSession().elem().setContentType(NutsContentType.JSON).setValue(getConfig()) + NutsSession session = context.getSession(); + NutsElements.of(session).json().setValue(getConfig()) .setNtf(false).print(out); } public String pull(String localPath, boolean restore, boolean deleteRemote) { - CachedMapFile lastRun=new CachedMapFile(context,"pull-" + getName()); + CachedMapFile lastRun = new CachedMapFile(context, "pull-" + getName()); NutsSession session = context.getSession(); - if(lastRun.exists()){ - if(!session.getTerminal().ask() + if (lastRun.exists()) { + if (!session.getTerminal().ask() .resetLine() .forBoolean("a previous pull has failed. would you like to resume (yes) or ignore and re-run the pull (no).") .getBooleanValue() - ){ + ) { lastRun.reset(); } } @@ -76,10 +77,10 @@ public String pull(String localPath, boolean restore, boolean deleteRemote) { if (session.isPlainTrace()) { session.out().printf("%s remote restore%n", getBracketsPrefix(name)); } - String remoteTempPath=null; - if(lastRun.get("remoteTempPath")!=null){ - remoteTempPath= lastRun.get("remoteTempPath"); - }else { + String remoteTempPath = null; + if (lastRun.get("remoteTempPath") != null) { + remoteTempPath = lastRun.get("remoteTempPath"); + } else { remoteTempPath = execRemoteNuts( "net.thevpc.nuts.toolbox:nmysql", "backup", @@ -91,11 +92,12 @@ public String pull(String localPath, boolean restore, boolean deleteRemote) { } //TODO: workaround, must fix me later int t = remoteTempPath.indexOf('{'); - if(t>0){ - remoteTempPath=remoteTempPath.substring(t); + if (t > 0) { + remoteTempPath = remoteTempPath.substring(t); } - Map resMap= session.elem().parse(remoteTempPath.getBytes(),Map.class); - String ppath=(String)resMap.get("path"); + NutsElements elem = NutsElements.of(session); + Map resMap = elem.parse(remoteTempPath.getBytes(), Map.class); + String ppath = (String) resMap.get("path"); if (NutsBlankable.isBlank(localPath)) { localPath = Paths.get(context.getVarFolder()) @@ -104,23 +106,23 @@ public String pull(String localPath, boolean restore, boolean deleteRemote) { .resolve(/*MysqlUtils.newDateString()+"-"+*/Paths.get(ppath).getFileName().toString()) .toString(); } - NutsPath remoteFullFilePath = session.io().path(prepareSshServer(cconfig.getServer())+"/"+ppath); - NutsTextManager text = session.text(); + NutsPath remoteFullFilePath = NutsPath.of(prepareSshServer(cconfig.getServer()) + "/" + ppath, session); + NutsTexts text = NutsTexts.of(session); if (session.isPlainTrace()) { session.out().printf("%s copy '%s' to '%s'%n", getBracketsPrefix(name), - text.ofStyled(remoteFullFilePath.toString(),NutsTextStyle.path()), - text.ofStyled(localPath,NutsTextStyle.path()) + text.ofStyled(remoteFullFilePath.toString(), NutsTextStyle.path()), + text.ofStyled(localPath, NutsTextStyle.path()) ); } - if(lastRun.get("localPath")!=null){ - String s=lastRun.get("localPath"); - session.io().copy().from(s).to(localPath).run(); - }else { - if(Paths.get(localPath).getParent()!=null) { + if (lastRun.get("localPath") != null) { + String s = lastRun.get("localPath"); + NutsCp.of(session).from(s).to(localPath).run(); + } else { + if (Paths.get(localPath).getParent() != null) { try { Files.createDirectories(Paths.get(localPath).getParent()); } catch (IOException e) { - throw new NutsIOException(session,e); + throw new NutsIOException(session, e); } } context.getSession().exec().setExecutionType(NutsExecutionType.EMBEDDED) @@ -138,9 +140,9 @@ public String pull(String localPath, boolean restore, boolean deleteRemote) { lastRun.put("localPath", localPath); } - if(lastRun.get("restored")!=null) { + if (lastRun.get("restored") != null) { String s = lastRun.get("restored"); - }else{ + } else { loc.restore(localPath); lastRun.put("restored", "true"); } @@ -150,14 +152,14 @@ public String pull(String localPath, boolean restore, boolean deleteRemote) { session.out().printf("%s delete %s%n", getBracketsPrefix(name), remoteFullFilePath); } - if(!lastRun.is("deleted")) { + if (!lastRun.is("deleted")) { execRemoteNuts( "nsh", "-c", "rm", remoteFullFilePath.getLocation() ); - lastRun.put("deleted","true"); + lastRun.put("deleted", "true"); } } lastRun.dispose(); @@ -183,18 +185,18 @@ public void push(String localPath, boolean backup) { RemoteMysqlDatabaseConfig cconfig = getConfig(); String remoteTempPath = null; final String searchResultString = execRemoteNuts("search --!color --json net.thevpc.nuts.toolbox:nmysql --display temp-folder --installed --first"); - List result = session.elem().setContentType(NutsContentType.JSON).parse(new StringReader(searchResultString), List.class); + List result = NutsElements.of(session).json().parse(new StringReader(searchResultString), List.class); if (result.isEmpty()) { - throw new NutsIllegalArgumentException(session,NutsMessage.cstyle("Mysql is not installed on the remote machine")); + throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("Mysql is not installed on the remote machine")); } remoteTempPath = (String) result.get(0).get("temp-folder"); - String remoteFilePath = "/"+ remoteTempPath+ "-" + MysqlUtils.newDateString() + "-" + MysqlUtils.getFileName(localPath); - NutsPath remoteFullFilePath = session.io().path(prepareSshServer(cconfig.getServer())+"/"+remoteFilePath); - NutsTextManager text = session.text(); + String remoteFilePath = "/" + remoteTempPath + "-" + MysqlUtils.newDateString() + "-" + MysqlUtils.getFileName(localPath); + NutsPath remoteFullFilePath = NutsPath.of(prepareSshServer(cconfig.getServer()) + "/" + remoteFilePath, session); + NutsTexts text = NutsTexts.of(session); if (session.isPlainTrace()) { session.out().printf("%s copy %s to %s%n", getBracketsPrefix(name), - text.ofStyled(localPath,NutsTextStyle.path()), + text.ofStyled(localPath, NutsTextStyle.path()), remoteFullFilePath ); } @@ -253,7 +255,7 @@ public String execRemoteNuts(String... cmd) { } else { b.addCommand("nsh", "-c", "ssh"); b.addCommand(this.config.getServer()); - b.addCommand("/home/"+System.getProperty("user.name")+"/bin/nuts"); + b.addCommand("/home/" + System.getProperty("user.name") + "/bin/nuts"); b.addCommand("-b"); b.addCommand("-y"); b.addCommand("--trace=false"); @@ -290,9 +292,9 @@ private String prepareSshServer(String server) { } public NutsString getBracketsPrefix(String str) { - return context.getSession().text().builder() + return NutsTexts.of(context.getSession()).builder() .append("[") - .append(str,NutsTextStyle.primary5()) + .append(str, NutsTextStyle.primary5()) .append("]"); } diff --git a/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/NutsIndexSubscriberListManager.java b/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/NutsIndexSubscriberListManager.java index 37c89376f..2bb2a7118 100644 --- a/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/NutsIndexSubscriberListManager.java +++ b/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/NutsIndexSubscriberListManager.java @@ -22,7 +22,7 @@ public NutsIndexSubscriberListManager(NutsSession session,String name) { this.name = name.trim(); Path file = getConfigFile(session); if (Files.exists(file)) { - this.config = this.defaultWorkspace.elem().setContentType(NutsContentType.JSON).parse(file, NutsIndexSubscriberListConfig.class); + this.config = NutsElements.of(defaultWorkspace).json().parse(file, NutsIndexSubscriberListConfig.class); if (this.config.getSubscribers() != null) { for (NutsIndexSubscriber var : this.config.getSubscribers()) { this.subscribers.put(var.getUuid(), var); @@ -39,8 +39,8 @@ public NutsIndexSubscriberListManager(NutsSession session,String name) { private Path getConfigFile(NutsSession session) { return Paths.get(session .locations() - .getStoreLocation(session - .id().resolveId(NutsIndexSubscriberListManager.class), + .getStoreLocation(NutsIdResolver.of(session) + .resolveId(NutsIndexSubscriberListManager.class), NutsStoreLocation.CONFIG)).resolve( name + "-nuts-subscriber-list.json"); } @@ -101,7 +101,7 @@ private void save(NutsSession session) { ? null : new ArrayList<>(this.subscribers.values())); Path file = getConfigFile(session); - this.defaultWorkspace.elem().setContentType(NutsContentType.JSON).setValue(this.config) + NutsElements.of(defaultWorkspace).json().setValue(this.config) .setNtf(false).print(file); } diff --git a/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/NutsIndexerUtils.java b/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/NutsIndexerUtils.java index 9d3531c8f..b5a26af71 100644 --- a/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/NutsIndexerUtils.java +++ b/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/NutsIndexerUtils.java @@ -21,7 +21,7 @@ public static Path getCacheDir(NutsSession session, String entity) { String m = session.env().getProperty(k).getString(); if (m == null) { m = session.locations() - .getStoreLocation(session.id().resolveId(NutsIndexerUtils.class), + .getStoreLocation(NutsIdResolver.of(session).resolveId(NutsIndexerUtils.class), NutsStoreLocation.CACHE) + File.separator + entity; session.env().setProperty(k, m); } @@ -49,9 +49,9 @@ public static Map nutsRepositoryToMap(NutsRepository repository, return entity; } - public static String mapToJson(Map map, NutsSession ws) { + public static String mapToJson(Map map, NutsSession session) { StringWriter s = new StringWriter(); - ws.elem().setContentType(NutsContentType.JSON).setValue(map) + NutsElements.of(session).json().setValue(map) .setNtf(false).print(s); return s.toString(); } @@ -138,13 +138,13 @@ public static BooleanQuery nutsIdToQuery( } public static NutsId mapToNutsId(Map map, NutsSession session) { - return session.id().builder() + return NutsIdBuilder.of(session) .setArtifactId(NutsUtilStrings.trim(map.get("name"))) .setRepository(NutsUtilStrings.trim(map.get("namespace"))) .setGroupId(NutsUtilStrings.trim(map.get("group"))) .setVersion(NutsUtilStrings.trim(map.get("version"))) .setCondition( - session.descriptor().envConditionBuilder() + NutsEnvConditionBuilder.of(session) //TODO what if the result is ',' separated array? .setArch(NutsUtilStrings.trim(map.get(NutsConstants.IdProperties.ARCH))) .setOs(NutsUtilStrings.trim(map.get(NutsConstants.IdProperties.OS))) diff --git a/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/DataService.java b/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/DataService.java index 771cc77a1..5255e39bd 100644 --- a/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/DataService.java +++ b/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/DataService.java @@ -143,7 +143,7 @@ public List> getAllDependencies(NutsSession session, Path di .setContent(false) .getResultIds().toList(); Map oldRow = new HashMap<>(row); - row.put("allDependencies", session.elem().setContentType(NutsContentType.JSON) + row.put("allDependencies", NutsElements.of(session).json() .setValue(allDependencies.stream().map(Object::toString) .collect(Collectors.toList())) .setNtf(false) @@ -152,9 +152,9 @@ public List> getAllDependencies(NutsSession session, Path di ); updateData(dirPath, oldRow, row); } - String[] array = session.elem().setContentType(NutsContentType.JSON).parse(new StringReader(row.get("allDependencies")), String[].class); + String[] array = NutsElements.of(session).json().parse(new StringReader(row.get("allDependencies")), String[].class); List> allDependencies = Arrays.stream(array) - .map(s -> NutsIndexerUtils.nutsIdToMap(session.id().parser().parse(s))) + .map(s -> NutsIndexerUtils.nutsIdToMap(NutsId.of(s,session))) .collect(Collectors.toList()); return allDependencies; } @@ -165,9 +165,9 @@ public List> getDependencies(NutsSession session, Path dirPa return null; } Map row = rows.get(0); - String[] array = session.elem().setContentType(NutsContentType.JSON).parse(new StringReader(row.get("dependencies")), String[].class); + String[] array = NutsElements.of(session).json().parse(new StringReader(row.get("dependencies")), String[].class); List> dependencies = Arrays.stream(array) - .map(s -> NutsIndexerUtils.nutsIdToMap(session.id().parser().parse(s))) + .map(s -> NutsIndexerUtils.nutsIdToMap(NutsId.of(s,session))) .collect(Collectors.toList()); return dependencies; } diff --git a/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/NutsComponentController.java b/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/NutsComponentController.java index 7c57be78f..430aa84c4 100644 --- a/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/NutsComponentController.java +++ b/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/NutsComponentController.java @@ -79,13 +79,13 @@ public ResponseEntity>> getDependencies(@RequestParam(" if (iterator.hasNext()) { NutsWorkspaceLocation workspaceLocation = iterator.next(); NutsSession session = Nuts.openWorkspace("--workspace",workspaceLocation.getLocation()); - NutsId id = session.id().builder() + NutsId id = NutsIdBuilder.of(session) .setArtifactId(name) .setRepository(namespace) .setGroupId(group) .setVersion(version) .setCondition( - session.descriptor().envConditionBuilder() + NutsEnvConditionBuilder.of(session) .setArch(arch) .setOs(os) .setOsDist(osdist).build() @@ -126,7 +126,7 @@ public ResponseEntity>> getAllVersions(@RequestParam("r if (iterator.hasNext()) { NutsWorkspaceLocation workspaceLocation = iterator.next(); NutsSession session = Nuts.openWorkspace("--workspace",workspaceLocation.getLocation()); - NutsId id = session.id().builder() + NutsId id = NutsIdBuilder.of(session) .setArtifactId(name) .setRepository(namespace) .setGroupId(group) @@ -172,7 +172,7 @@ public ResponseEntity deleteComponent(@RequestParam("repositoryUuid") S NutsSession session = Nuts.openWorkspace("--workspace",workspaceLocation.getLocation()); NutsWorkspace ws = session.getWorkspace(); Map data = NutsIndexerUtils.nutsIdToMap( - session.id().builder() + NutsIdBuilder.of(session) .setArtifactId(name) .setRepository(namespace) .setGroupId(group) @@ -216,7 +216,7 @@ public ResponseEntity addDocument(@RequestParam("repositoryUuid") Strin if (iterator.hasNext()) { NutsWorkspaceLocation workspaceLocation = iterator.next(); NutsSession session = Nuts.openWorkspace("--workspace",workspaceLocation.getLocation()); - NutsId id = session.id().builder() + NutsId id = NutsIdBuilder.of(session) .setArtifactId(name) .setRepository(namespace) .setGroupId(group) @@ -246,7 +246,7 @@ public ResponseEntity addDocument(@RequestParam("repositoryUuid") Strin if (it.hasNext()) { NutsDefinition definition = it.next(); NutsDependency[] directDependencies = definition.getEffectiveDescriptor().getDependencies(); - data.put("dependencies", session.elem().setContentType(NutsContentType.JSON) + data.put("dependencies", NutsElements.of(session).json() .setValue(Arrays.stream(directDependencies).map(Object::toString) .collect(Collectors.toList())) .setNtf(false) @@ -271,18 +271,18 @@ private List> cleanNutsIdMap(NutsSession session, List row : rows) { Map d = new HashMap<>(row); if (d.containsKey("dependencies")) { - String[] array = session.elem().setContentType(NutsContentType.JSON).parse(new StringReader(row.get("dependencies")), String[].class); + String[] array = NutsElements.of(session).json().parse(new StringReader(row.get("dependencies")), String[].class); List> dependencies = new ArrayList<>(); for (String s : array) { - dependencies.add(NutsIndexerUtils.nutsIdToMap(session.id().parser().parse(s))); + dependencies.add(NutsIndexerUtils.nutsIdToMap(NutsId.of(s,session))); } d.put("dependencies", dependencies); } if (d.containsKey("allDependencies")) { - String[] array = session.elem().setContentType(NutsContentType.JSON).parse(new StringReader(row.get("allDependencies")), String[].class); + String[] array = NutsElements.of(session).json().parse(new StringReader(row.get("allDependencies")), String[].class); List> allDependencies = new ArrayList<>(); for (String s : array) { - allDependencies.add(NutsIndexerUtils.nutsIdToMap(session.id().parser().parse(s))); + allDependencies.add(NutsIndexerUtils.nutsIdToMap(NutsId.of(s,session))); } d.put("allDependencies", allDependencies); } diff --git a/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/RefreshDataService.java b/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/RefreshDataService.java index a05fb6ef0..72472e2d1 100644 --- a/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/RefreshDataService.java +++ b/toolbox/ndexer/src/main/java/net/thevpc/nuts/indexer/services/RefreshDataService.java @@ -78,7 +78,7 @@ private void refreshSubscriberData(NutsIndexSubscriber subscriber) { NutsDependency[] directDependencies = definition.getEffectiveDescriptor().getDependencies(); id.put("dependencies", - session.elem().setContentType(NutsContentType.JSON).setValue(Arrays.stream(directDependencies).map(Object::toString).collect(Collectors.toList())) + NutsElements.of(session).json().setValue(Arrays.stream(directDependencies).map(Object::toString).collect(Collectors.toList())) .setNtf(false).format().filteredText() ); dataToIndex.add(id); diff --git a/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusContentFile.java b/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusContentFile.java index 09f80059a..6da504f58 100644 --- a/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusContentFile.java +++ b/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusContentFile.java @@ -2,6 +2,7 @@ import net.thevpc.nuts.NutsContentType; import net.thevpc.nuts.NutsElement; +import net.thevpc.nuts.NutsElements; import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.lib.md.MdElement; import net.thevpc.nuts.lib.md.docusaurus.DocusaurusMdParser; @@ -56,7 +57,7 @@ public static DocusaurusFile ofTreeFile(Reader reader, String partialPath, Strin props.put(key, value); if("type".equals(key) && value.length()>0){ try { - config = session.elem().setContentType(NutsContentType.JSON).parse(value); + config = NutsElements.of(session).json().parse(value); }catch (Exception ex){ throw new IllegalArgumentException("invalid json for type in "+location); } diff --git a/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusCtrl.java b/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusCtrl.java index 523773367..28c4e43a9 100644 --- a/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusCtrl.java +++ b/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusCtrl.java @@ -83,15 +83,16 @@ public void run() { boolean genSidebarMenu = Boolean.parseBoolean(genSidebarMenuString); Path basePath = base; Path preProcessor = getPreProcessorBaseDir(); + NutsSession session = appContext.getSession(); if (Files.isDirectory(preProcessor) && Files.isRegularFile(preProcessor.resolve("project.nsh"))) { // Files.walk(base).filter(x->Files.isDirectory(base)) Path docs = basePath.resolve("docs"); if (Files.isDirectory(basePath.resolve("node_modules")) && Files.isRegularFile(basePath.resolve("docusaurus.config.js"))) { - appContext.getSession().out().printf("clear folder %s%n",docs); + session.out().printf("clear folder %s%n",docs); deletePathChildren(docs); } - appContext.getSession().out().printf("process template %s -> %s%n",preProcessor,getTargetBaseDir()); + session.out().printf("process template %s -> %s%n",preProcessor,getTargetBaseDir()); TemplateConfig config = new TemplateConfig() .setProjectPath(preProcessor.toString()) .setTargetFolder(getTargetBaseDir().toString()); @@ -109,22 +110,22 @@ public void run() { if (genSidebarMenu) { DocusaurusFolder root = project.getPhysicalDocsFolder(); root = new DocusaurusFolder( - "someSidebar", "someSidebar", 0, appContext.getSession().elem().forObject().build(), root.getChildren(), - root.getContent(appContext.getSession()), + "someSidebar", "someSidebar", 0, NutsElements.of(session).forObject().build(), root.getChildren(), + root.getContent(session), project.getPhysicalDocsFolderBasePath().toString() ); String s = "module.exports = {\n" + root.toJSON(1) + "\n};"; - if (appContext.getSession().isPlainOut()) { - appContext.getSession().out().printf("build sidebar %s%n", base.resolve("sidebars.js")); - appContext.getSession().out().printf("\tusing release folder : %s%n", project.getPhysicalDocsFolderBasePath()); - appContext.getSession().out().printf("\tusing config folder : %s%n", project.getPhysicalDocsFolderConfigPath()); + if (session.isPlainOut()) { + session.out().printf("build sidebar %s%n", base.resolve("sidebars.js")); + session.out().printf("\tusing release folder : %s%n", project.getPhysicalDocsFolderBasePath()); + session.out().printf("\tusing config folder : %s%n", project.getPhysicalDocsFolderConfigPath()); } try { Files.write(base.resolve("sidebars.js"), s.getBytes()); } catch (IOException e) { - throw new NutsIOException(appContext.getSession(), NutsMessage.cstyle("%s",e)); + throw new NutsIOException(session, NutsMessage.cstyle("%s",e)); } // System.out.println(s); } @@ -133,13 +134,13 @@ public void run() { .getSafe("path") .isNull()) { Docusaurus2Asciidoctor d2a = new Docusaurus2Asciidoctor(project); - appContext.getSession().out().printf("build adoc file : %s%n", d2a.getAdocFile()); + session.out().printf("build adoc file : %s%n", d2a.getAdocFile()); d2a.createAdocFile(); - appContext.getSession().out().printf("build pdf file : %s%n", d2a.getPdfFile()); + session.out().printf("build pdf file : %s%n", d2a.getPdfFile()); d2a.createPdfFile(); } if (isBuildWebSite()) { - appContext.getSession().out().printf("build website%n"); + session.out().printf("build website%n"); runNativeCommand(base, getEffectiveNpmCommandPath(), "run-script", "build"); String copyBuildPath = project.getConfig().getSafeObject("customFields") .getSafe("copyBuildPath") @@ -153,7 +154,7 @@ public void run() { } Path toPath = FileProcessorUtils.toAbsolute(Paths.get(copyBuildPath), base); deleteFolderIfFound(toPath, "index.html", "404.html", "sitemap.xml"); - new FileTemplater(appContext.getSession()) + new FileTemplater(session) .setWorkingDir(fromPath) .setTargetPath(toPath) .setMimeTypeResolver((String path) -> MimeTypeConstants.ANY_TYPE) @@ -325,13 +326,12 @@ public void setVar(String varName, String newValue) { @Override public Object eval(String content, FileTemplater context) { NutsSession session = context.getSession().copy(); - NutsPrintStream out = session.io().createMemoryPrintStream(); + NutsPrintStream out = NutsMemoryPrintStream.of(session); session.setTerminal( - session.term() - .createTerminal( + NutsSessionTerminal.of( new ByteArrayInputStream(new byte[0]), out, - out) + out,session) ); JShellContext ctx = shell.createInlineContext( shell.getRootContext(), diff --git a/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusFolder.java b/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusFolder.java index 0852d1dd6..673e74449 100644 --- a/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusFolder.java +++ b/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusFolder.java @@ -1,9 +1,6 @@ package net.thevpc.nuts.toolbox.docusaurus; -import net.thevpc.nuts.NutsElement; -import net.thevpc.nuts.NutsObjectElement; -import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.NutsUtilStrings; +import net.thevpc.nuts.*; import net.thevpc.nuts.lib.md.MdElement; import net.thevpc.nuts.lib.md.docusaurus.DocusaurusUtils; import net.thevpc.nuts.lib.md.util.MdUtils; @@ -117,7 +114,7 @@ public static DocusaurusFolder ofFolder(NutsSession session, Path path, Path roo } } if (config == null) { - config = session.elem().forObject().build(); + config = NutsElements.of(session).forObject().build(); } if (title == null || title.trim().isEmpty()) { title = path.getFileName().toString(); @@ -157,7 +154,7 @@ public static DocusaurusFolder ofFolder(NutsSession session, Path path, Path roo } public static DocusaurusFolder ofRoot(NutsSession session, DocusaurusFileOrFolder[] children, MdElement tree, String path) { - return new DocusaurusFolder("/", "/", 0, session.elem().forObject().build(), children, tree, path); + return new DocusaurusFolder("/", "/", 0, NutsElements.of(session).forObject().build(), children, tree, path); } public static DocusaurusFolder of(String longId, String title, int order, NutsObjectElement config, DocusaurusFileOrFolder[] children, String path) { diff --git a/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusProject.java b/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusProject.java index 7b3fac0a1..751f9e9c6 100644 --- a/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusProject.java +++ b/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusProject.java @@ -131,7 +131,7 @@ public NutsElement loadModuleExportsFile(String path) { try { a = new String(Files.readAllBytes(Paths.get(resolvePath(path)))); } catch (IOException ex) { - return session.elem().forNull(); + return NutsElements.of(session).forNull(); } //(?s) stands for single line mode in which the dot includes line breaks Pattern p = Pattern.compile("(?s)module.exports[ ]*=[ ]*(?.*[^;])[;]?"); @@ -141,9 +141,9 @@ public NutsElement loadModuleExportsFile(String path) { json = matcher.group("json"); } if (json==null) { - return session.elem().forObject().build(); + return NutsElements.of(session).forObject().build(); } - return session.elem().setContentType(NutsContentType.JSON) + return NutsElements.of(session).json() .parse(json,NutsElement.class); } @@ -169,10 +169,10 @@ private String toCanonicalPath(String path) { // } else if (Files.isDirectory(path)) { // String longId = path.subpath(root.getNameCount(), path.getNameCount()).toString(); // Path dfi = path.resolve(DOCUSAURUS_FOLDER_CONFIG); -// NutsObjectElement config = session.elem().forObject().build(); +// NutsObjectElement config = NutsElements.of(session).forObject().build(); // if (Files.isRegularFile(dfi)) { // try { -// config = session.elem().parse(new String(Files.readAllBytes(dfi))).asSafeObject(); +// config = NutsElements.of(session).parse(new String(Files.readAllBytes(dfi))).asSafeObject(); // } catch (IOException e) { // //ignore... // } @@ -243,7 +243,7 @@ public DocusaurusFileOrFolder[] LJSON_to_DocusaurusFileOrFolder_list(NutsElement member.getKey().asString(),//no id here! member.getKey().asString(), ++order, - session.elem().forObject().build(), + NutsElements.of(session).forObject().build(), cc, resolveFolderContent(parentPath),parentPath==null?null:parentPath.toString() )); @@ -279,7 +279,7 @@ public Path detectFile(DocusaurusFileOrFolder f) { public DocusaurusFolder getSidebarsDocsFolder() { DocusaurusFileOrFolder[] someSidebars = LJSON_to_DocusaurusFileOrFolder_list(getSidebars().getSafe("someSidebar"), getPhysicalDocsFolder()); return new DocusaurusFolder("/", "/", 0, - session.elem().forObject().build(), someSidebars,resolveFolderContent(getPhysicalDocsFolderBasePath()), + NutsElements.of(session).forObject().build(), someSidebars,resolveFolderContent(getPhysicalDocsFolderBasePath()), getPhysicalDocsFolder().getPath() ); } diff --git a/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusTreeTransform.java b/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusTreeTransform.java index e91f97d50..35dd4784b 100644 --- a/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusTreeTransform.java +++ b/toolbox/ndocusaurus/src/main/java/net/thevpc/nuts/toolbox/docusaurus/DocusaurusTreeTransform.java @@ -7,6 +7,7 @@ import net.thevpc.nuts.NutsArrayElement; import net.thevpc.nuts.NutsElement; +import net.thevpc.nuts.NutsElements; import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.lib.md.*; import net.thevpc.nuts.lib.md.docusaurus.DocusaurusUtils; @@ -128,7 +129,7 @@ protected MdElement transformXml(MdElementPath path) { switch (e.getTag()) { case "Tabs": { String props = DocusaurusUtils.skipJsonJSXBrackets(e.getProperties().get("values")); - NutsArrayElement rows = session.elem().parse(props).asSafeArray(); + NutsArrayElement rows = NutsElements.of(session).parse(props).asSafeArray(); Map sub=new HashMap<>(); for (MdElement item : MdFactory.asBody(e.getContent()).getChildren()) { if (item.isXml()) { @@ -136,7 +137,7 @@ protected MdElement transformXml(MdElementPath path) { String t = tabItem.getTag(); if (t.equals("TabItem")) { String tt = "Unknown"; - NutsElement v = session.elem().parse(tabItem.getProperties().get("value")); + NutsElement v = NutsElements.of(session).parse(tabItem.getProperties().get("value")); if (v != null) { tt = v.asString(); } @@ -163,12 +164,12 @@ protected MdElement transformXml(MdElementPath path) { case "TabItem": { String tt = "Unknown"; - NutsElement v = session.elem().parse(e.getProperties().get("value")); + NutsElement v = NutsElements.of(session).parse(e.getProperties().get("value")); if (v != null) { tt = v.asString(); } String props = DocusaurusUtils.skipJsonJSXBrackets(path.getParentPath().getElement().asXml().getProperties().get("values")); - for (NutsElement a : session.elem().parse(props).asSafeArray()) { + for (NutsElement a : NutsElements.of(session).parse(props).asSafeArray()) { if (tt.equals(a.asSafeObject().getSafeString("value"))) { tt = a.asSafeObject().getSafeString("label"); break; diff --git a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/JobServiceCmd.java b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/JobServiceCmd.java index c7df535c4..06c58c57b 100644 --- a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/JobServiceCmd.java +++ b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/JobServiceCmd.java @@ -91,7 +91,7 @@ private void runSummary(NutsCommandLine cmd) { long tasksCount = service.tasks().findTasks(NTaskStatusFilter.OPEN, null, -1, null, null, null, null, null).count(); long jobsCount = service.jobs().findMonthJobs(null).count(); long allJobsCount = service.jobs().findLastJobs(null, -1, null, null, null, null, null).count(); - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); context.getSession().out().printf("%s open task%s\n", text.ofStyled("" + tasksCount, NutsTextStyle.primary1()), tasksCount == 1 ? "" : "s"); context.getSession().out().printf("%s job%s %s\n", text.ofStyled("" + allJobsCount, NutsTextStyle.primary1()), allJobsCount == 1 ? "" : "s", allJobsCount == 0 ? "" @@ -105,14 +105,14 @@ private void runSummary(NutsCommandLine cmd) { } protected void showCustomHelp(String name) { - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); context.getSession().out().println(text.parser().parseResource("/net/thevpc/nuts/toolbox/" + name + ".ntf", text.parser().createLoader(getClass().getClassLoader()) )); } protected NutsString getFormattedProject(String projectName) { - NutsTextBuilder builder = session.text().builder(); + NutsTextBuilder builder = NutsTexts.of(session).builder(); builder.getStyleGenerator() .setIncludeForeground(true) .setUsePaletteColors(); @@ -131,40 +131,40 @@ protected String getFormattedDate(Instant x) { protected NutsString getCheckedString(Boolean x) { if (x == null) { - return context.getSession().text().ofPlain(""); + return NutsTexts.of(context.getSession()).ofPlain(""); } if (x) { - return context.getSession().text().ofPlain("\u2611"); + return NutsTexts.of(context.getSession()).ofPlain("\u2611"); } else { - return context.getSession().text().ofPlain("\u25A1"); + return NutsTexts.of(context.getSession()).ofPlain("\u25A1"); } } protected NutsString getPriorityString(NPriority x) { if (x == null) { - return context.getSession().text().ofPlain("N"); + return NutsTexts.of(context.getSession()).ofPlain("N"); } switch (x) { case NONE: - return session.text().ofStyled("0", NutsTextStyle.pale()); + return NutsTexts.of(session).ofStyled("0", NutsTextStyle.pale()); case LOW: - return session.text().ofStyled("L", NutsTextStyle.pale()); + return NutsTexts.of(session).ofStyled("L", NutsTextStyle.pale()); case NORMAL: - return session.text().ofPlain("N"); + return NutsTexts.of(session).ofPlain("N"); case MEDIUM: - return session.text().ofStyled("M", NutsTextStyle.primary1()); + return NutsTexts.of(session).ofStyled("M", NutsTextStyle.primary1()); case URGENT: - return session.text().ofStyled("U", NutsTextStyle.primary2()); + return NutsTexts.of(session).ofStyled("U", NutsTextStyle.primary2()); case HIGH: - return session.text().ofStyled("H", NutsTextStyle.primary3()); + return NutsTexts.of(session).ofStyled("H", NutsTextStyle.primary3()); case CRITICAL: - return session.text().ofStyled("C", NutsTextStyle.fail()); + return NutsTexts.of(session).ofStyled("C", NutsTextStyle.fail()); } - return context.getSession().text().ofPlain("?"); + return NutsTexts.of(context.getSession()).ofPlain("?"); } protected NutsString getStatusString(NTaskStatus x) { - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); if (x == null) { return text.ofPlain("*"); } @@ -184,15 +184,15 @@ protected NutsString getStatusString(NTaskStatus x) { private NutsString getFlagString(String x, int index) { switch (index) { case 1: - return session.text().ofStyled(x, NutsTextStyle.primary1()); + return NutsTexts.of(session).ofStyled(x, NutsTextStyle.primary1()); case 2: - return session.text().ofStyled(x, NutsTextStyle.primary2()); + return NutsTexts.of(session).ofStyled(x, NutsTextStyle.primary2()); case 3: - return session.text().ofStyled(x, NutsTextStyle.primary3()); + return NutsTexts.of(session).ofStyled(x, NutsTextStyle.primary3()); case 4: - return session.text().ofStyled(x, NutsTextStyle.primary4()); + return NutsTexts.of(session).ofStyled(x, NutsTextStyle.primary4()); case 5: - return session.text().ofStyled(x, NutsTextStyle.primary5()); + return NutsTexts.of(session).ofStyled(x, NutsTextStyle.primary5()); } throw new NutsIllegalArgumentException(context.getSession(), NutsMessage.cstyle("invalid index %s", index)); } @@ -203,7 +203,7 @@ protected NutsString getFlagString(NFlag x) { } switch (x) { case NONE: - return context.getSession().text().ofPlain("\u2690"); + return NutsTexts.of(context.getSession()).ofPlain("\u2690"); case STAR1: return getFlagString("\u2605", 1); @@ -260,7 +260,7 @@ protected NutsString getFlagString(NFlag x) { case PHONE5: return getFlagString("\u260E", 5); } - return context.getSession().text().ofPlain("[" + x.toString().toLowerCase() + "]"); + return NutsTexts.of(context.getSession()).ofPlain("[" + x.toString().toLowerCase() + "]"); } protected Predicate appendPredicate(Predicate whereFilter, Predicate t) { @@ -286,18 +286,17 @@ protected Predicate createStringFilter(String s) { public void runInteractive(NutsCommandLine cmdLine) { NutsSession session = context.getSession(); - session.term().enableRichTerm(); - session.term().getSystemTerminal() + NutsSystemTerminal.enableRichTerm(session); + session.config().getSystemTerminal() .setCommandAutoCompleteResolver(new JobAutoCompleter()) .setCommandHistory( - session.commandLine().createHistory() + NutsCommandHistory.of(session) .setPath(Paths.get(context.getVarFolder()).resolve("njob-history.hist")) - .build() ) .setCommandReadHighlighter(new NutsCommandReadHighlighter() { @Override public NutsText highlight(String buffer, NutsSession session) { - return session.text().ofCode("sh", buffer).highlight(session); + return NutsTexts.of(session).ofCode("sh", buffer).highlight(session); } }); session.env().setProperty(JobServiceCmd.class.getName(), this); @@ -307,7 +306,7 @@ public NutsText highlight(String buffer, NutsSession session) { // session.io().term().getSystemTerminal(), // session // )); - NutsTextManager text = session.text(); + NutsTexts text = NutsTexts.of(session); session.out().printf( "%s interactive mode. type %s to quit.%n", @@ -335,7 +334,7 @@ public NutsText highlight(String buffer, NutsSession session) { lastError.printStackTrace(session.out().asPrintStream()); } } else { - NutsCommandLine cmd = this.session.commandLine().parse(line); + NutsCommandLine cmd = NutsCommandLine.parse(line,this.session); cmd.setCommandName(context.getAppId().getArtifactId()); try { lastError = null; diff --git a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobConfigStore.java b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobConfigStore.java index ba040903a..4644132bd 100644 --- a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobConfigStore.java +++ b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobConfigStore.java @@ -18,12 +18,13 @@ public class NJobConfigStore { private NutsApplicationContext context; - private NutsElementFormat json; + private NutsElements json; private Path dbPath; public NJobConfigStore(NutsApplicationContext applicationContext) { this.context = applicationContext; - json = applicationContext.getSession().elem().setContentType(NutsContentType.JSON).setNtf(false); + NutsSession session = applicationContext.getSession(); + json = NutsElements.of(session).json().setNtf(false); json.setCompact(false); //ensure we always consider the latest config version dbPath = Paths.get(applicationContext.getVersionFolderFolder(NutsStoreLocation.CONFIG, NJobConfigVersions.CURRENT)) diff --git a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobMain.java b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobMain.java index 2040206ca..32af61a4d 100644 --- a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobMain.java +++ b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobMain.java @@ -1,9 +1,6 @@ package net.thevpc.nuts.toolbox.njob; -import net.thevpc.nuts.NutsApplication; -import net.thevpc.nuts.NutsApplicationContext; -import net.thevpc.nuts.NutsArgument; -import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.*; public class NJobMain implements NutsApplication { @@ -35,7 +32,8 @@ public void run(NutsApplicationContext appContext) { cmdLine.unexpectedArgument(); } }; - ts.runCommands(appContext.getSession().commandLine().create("summary")); + NutsSession session = appContext.getSession(); + ts.runCommands(NutsCommandLine.of(new String[]{"summary"}, session)); } } diff --git a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobsSubCmd.java b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobsSubCmd.java index fdbd74d82..a291b7045 100644 --- a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobsSubCmd.java +++ b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NJobsSubCmd.java @@ -14,10 +14,10 @@ public class NJobsSubCmd { - private JobService service; - private NutsApplicationContext context; - private NutsSession session; - private JobServiceCmd parent; + private final JobService service; + private final NutsApplicationContext context; + private final NutsSession session; + private final JobServiceCmd parent; public NJobsSubCmd(JobServiceCmd parent) { this.parent = parent; @@ -87,15 +87,15 @@ public void runJobAdd(NutsCommandLine cmd) { service.jobs().addJob(t); if (context.getSession().isPlainTrace()) { context.getSession().out().printf("job %s (%s) added.\n", - context.getSession().text().ofStyled(t.getId(), NutsTextStyle.primary5()), + NutsTexts.of(context.getSession()).ofStyled(t.getId(), NutsTextStyle.primary5()), t.getName() ); } if (show) { - runJobShow(session.commandLine().create(t.getId())); + runJobShow(NutsCommandLine.of(new String[]{t.getId()}, session)); } if (list) { - runJobList(session.commandLine().create()); + runJobList(NutsCommandLine.of(new String[0], session)); } } } @@ -196,7 +196,7 @@ public void runJobUpdate(NutsCommandLine cmd) { c.accept(job); } } - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); for (NJob job : new LinkedHashSet<>(jobs)) { service.jobs().updateJob(job); if (context.getSession().isPlainTrace()) { @@ -208,11 +208,11 @@ public void runJobUpdate(NutsCommandLine cmd) { } if (show) { for (NJob t : new LinkedHashSet<>(jobs)) { - runJobList(session.commandLine().create(t.getId())); + runJobList(NutsCommandLine.of(new String[]{t.getId()}, session)); } } if (list) { - runJobList(session.commandLine().create()); + runJobList(NutsCommandLine.of(new String[0], session)); } } } @@ -246,7 +246,7 @@ public boolean runJobCommands(NutsCommandLine cmd) { } private void runJobRemove(NutsCommandLine cmd) { - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); while (cmd.hasNext()) { NutsArgument a = cmd.next(); NJob t = findJob(a.toString(), cmd); @@ -282,18 +282,18 @@ private void runJobShow(NutsCommandLine cmd) { job.getId() ); String prefix = "\t "; - context.getSession().out().printf("\t```kw2 job name``` : %s:\n", parent.formatWithPrefix(job.getName(), prefix)); + context.getSession().out().printf("\t```kw2 job name``` : %s:\n", JobServiceCmd.formatWithPrefix(job.getName(), prefix)); String project = job.getProject(); NProject p = service.projects().getProject(project); if (project == null || project.length() == 0) { context.getSession().out().printf("\t```kw2 project``` : %s\n", ""); } else { - context.getSession().out().printf("\t```kw2 project``` : %s (%s)\n", project, parent.formatWithPrefix(p == null ? "?" : p.getName(), prefix)); + context.getSession().out().printf("\t```kw2 project``` : %s (%s)\n", project, JobServiceCmd.formatWithPrefix(p == null ? "?" : p.getName(), prefix)); } - context.getSession().out().printf("\t```kw2 duration``` : %s\n", parent.formatWithPrefix(job.getDuration(), prefix)); - context.getSession().out().printf("\t```kw2 start time``` : %s\n", parent.formatWithPrefix(job.getStartTime(), prefix)); - context.getSession().out().printf("\t```kw2 duration extra```: %s\n", parent.formatWithPrefix(job.getInternalDuration(), prefix)); - context.getSession().out().printf("\t```kw2 observations``` : %s\n", parent.formatWithPrefix(job.getObservations(), prefix)); + context.getSession().out().printf("\t```kw2 duration``` : %s\n", JobServiceCmd.formatWithPrefix(job.getDuration(), prefix)); + context.getSession().out().printf("\t```kw2 start time``` : %s\n", JobServiceCmd.formatWithPrefix(job.getStartTime(), prefix)); + context.getSession().out().printf("\t```kw2 duration extra```: %s\n", JobServiceCmd.formatWithPrefix(job.getInternalDuration(), prefix)); + context.getSession().out().printf("\t```kw2 observations``` : %s\n", JobServiceCmd.formatWithPrefix(job.getObservations(), prefix)); } } } @@ -427,25 +427,25 @@ private void runJobList(NutsCommandLine cmd) { List lastResults = new ArrayList<>(); int[] index = new int[1]; r.forEach(x -> { - NutsString durationString = session.text().ofStyled(String.valueOf(timeUnit0 == null ? x.getDuration() : x.getDuration().toUnit(timeUnit0, hoursPerDay)), NutsTextStyle.keyword()); + NutsString durationString = NutsTexts.of(session).ofStyled(String.valueOf(timeUnit0 == null ? x.getDuration() : x.getDuration().toUnit(timeUnit0, hoursPerDay)), NutsTextStyle.keyword()); index[0]++; lastResults.add(x); m.newRow().addCells( (finalGroupBy != null) ? new Object[]{ - parent.createHashId(index[0], -1), - parent.getFormattedDate(x.getStartTime()), - durationString, - parent.getFormattedProject(x.getProject() == null ? "*" : x.getProject()), - x.getName() + parent.createHashId(index[0], -1), + parent.getFormattedDate(x.getStartTime()), + durationString, + parent.getFormattedProject(x.getProject() == null ? "*" : x.getProject()), + x.getName() } : new Object[]{ - parent.createHashId(index[0], -1), - session.text().ofStyled(x.getId(), NutsTextStyle.pale()), - parent.getFormattedDate(x.getStartTime()), - durationString, - parent.getFormattedProject(x.getProject() == null ? "*" : x.getProject()), - x.getName() + parent.createHashId(index[0], -1), + NutsTexts.of(session).ofStyled(x.getId(), NutsTextStyle.pale()), + parent.getFormattedDate(x.getStartTime()), + durationString, + parent.getFormattedProject(x.getProject() == null ? "*" : x.getProject()), + x.getName() } ); @@ -463,7 +463,7 @@ private void runJobList(NutsCommandLine cmd) { private NJob findJob(String pid, NutsCommandLine cmd) { NJob t = null; if (pid.startsWith("#")) { - int x = parent.parseIntOrFF(pid.substring(1)); + int x = JobServiceCmd.parseIntOrFF(pid.substring(1)); if (x >= 1) { Object lastResults = context.getSession().getProperty("LastResults"); if (lastResults instanceof NJob[] && x <= ((NJob[]) lastResults).length) { @@ -475,7 +475,7 @@ private NJob findJob(String pid, NutsCommandLine cmd) { t = service.jobs().getJob(pid); } if (t == null) { - cmd.throwError(NutsMessage.cstyle("job not found: %s",pid)); + cmd.throwError(NutsMessage.cstyle("job not found: %s", pid)); } return t; } diff --git a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NProjectsSubCmd.java b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NProjectsSubCmd.java index c480a6488..aaced3121 100644 --- a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NProjectsSubCmd.java +++ b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NProjectsSubCmd.java @@ -66,15 +66,15 @@ public void runProjectAdd(NutsCommandLine cmd) { service.projects().addProject(t); if (context.getSession().isPlainTrace()) { context.getSession().out().printf("project %s (%s) added.\n", - context.getSession().text().ofStyled(t.getId(), NutsTextStyle.primary5()), + NutsTexts.of(context.getSession()).ofStyled(t.getId(), NutsTextStyle.primary5()), t.getName() ); } if (show) { - runProjectShow(session.commandLine().create(t.getId())); + runProjectShow(NutsCommandLine.of(new String[]{t.getId()}, session)); } if (list) { - runProjectList(session.commandLine().create()); + runProjectList(NutsCommandLine.of(new String[0], session)); } } } @@ -180,7 +180,7 @@ public void runProjectUpdate(NutsCommandLine cmd) { cmd.throwError(NutsMessage.formatted("project name expected")); } if (cmd.isExecMode()) { - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); for (NProject project : projects) { for (Consumer c : runLater) { c.accept(project); @@ -197,18 +197,18 @@ public void runProjectUpdate(NutsCommandLine cmd) { service.projects().mergeProjects(mergeTo, projects.stream().map(x -> x.getId()).toArray(String[]::new)); if (context.getSession().isPlainTrace()) { context.getSession().out().printf("projects merged to %s.\n", - context.getSession() - .text().ofStyled(mergeTo, NutsTextStyle.primary5()) + NutsTexts.of(context.getSession()) + .ofStyled(mergeTo, NutsTextStyle.primary5()) ); } } if (show) { for (NProject t : new LinkedHashSet<>(projects)) { - runProjectShow(session.commandLine().create(t.getId())); + runProjectShow(NutsCommandLine.of(new String[]{t.getId()}, session)); } } if (list) { - runProjectList(session.commandLine().create()); + runProjectList(NutsCommandLine.of(new String[0], session)); } } } @@ -310,7 +310,7 @@ private void runProjectList(NutsCommandLine cmd) { } private void runProjectRemove(NutsCommandLine cmd) { - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); while (cmd.hasNext()) { NutsArgument a = cmd.next(); if (cmd.isExecMode()) { diff --git a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NTasksSubCmd.java b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NTasksSubCmd.java index 3ca151a2b..ed451fed5 100644 --- a/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NTasksSubCmd.java +++ b/toolbox/njob/src/main/java/net/thevpc/nuts/toolbox/njob/NTasksSubCmd.java @@ -143,7 +143,7 @@ public void runTaskAdd(NutsCommandLine cmd) { runLater.add(t -> t.setPriority(NPriority.NORMAL)); } else { if (cmd.peek().isNonOption() && !nameVisited) { - String n = cmd.next(session.commandLine().createName("name")).getString(); + String n = cmd.next(NutsArgumentName.of("name",session)).getString(); runLater.add(t -> t.setName(n)); } else { cmd.unexpectedArgument(); @@ -158,15 +158,15 @@ public void runTaskAdd(NutsCommandLine cmd) { service.tasks().addTask(t); if (context.getSession().isPlainTrace()) { context.getSession().out().printf("task %s (%s) added.\n", - context.getSession().text().ofStyled(t.getId(), NutsTextStyle.primary5()), + NutsTexts.of(context.getSession()).ofStyled(t.getId(), NutsTextStyle.primary5()), t.getName() ); } if (show) { - runTaskShow(session.commandLine().create(t.getId())); + runTaskShow(NutsCommandLine.of(new String[]{t.getId()}, session)); } if (list) { - runTaskList(session.commandLine().create()); + runTaskList(NutsCommandLine.of(new String[0], session)); } } } @@ -392,7 +392,7 @@ public void runTaskUpdate(NutsCommandLine cmd) { c.accept(task); } } - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); for (NTask task : new LinkedHashSet<>(tasks)) { service.tasks().updateTask(task); if (context.getSession().isPlainTrace()) { @@ -404,11 +404,11 @@ public void runTaskUpdate(NutsCommandLine cmd) { } if (show) { for (NTask t : new LinkedHashSet<>(tasks)) { - runTaskList(session.commandLine().create(t.getId())); + runTaskList(NutsCommandLine.of(new String[]{t.getId()}, session)); } } if (list) { - runTaskList(session.commandLine().create()); + runTaskList(NutsCommandLine.of(new String[0], session)); } } } @@ -600,7 +600,7 @@ private Object[] toTaskRowArray(NTask x, String index) { NProject p = project == null ? null : service.projects().getProject(project); NTaskStatus s = x.getStatus(); String dte0 = parent.getFormattedDate(x.getDueTime()); - NutsTextBuilder dte = session.text().builder(); + NutsTextBuilder dte = NutsTexts.of(session).builder(); if (s == NTaskStatus.CANCELLED || s == NTaskStatus.DONE) { dte.append(dte0, NutsTextStyle.pale()); } else if (x.getDueTime() != null && x.getDueTime().compareTo(Instant.now()) < 0) { @@ -611,7 +611,7 @@ private Object[] toTaskRowArray(NTask x, String index) { String projectName = p != null ? p.getName() : project != null ? project : "*"; return new Object[]{ index, - session.text().builder().append(x.getId(), NutsTextStyle.pale()), + NutsTexts.of(session).builder().append(x.getId(), NutsTextStyle.pale()), parent.getFlagString(x.getFlag()), parent.getStatusString(x.getStatus()), parent.getPriorityString(x.getPriority()), @@ -622,7 +622,7 @@ private Object[] toTaskRowArray(NTask x, String index) { } private void runTaskRemove(NutsCommandLine cmd) { - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); while (cmd.hasNext()) { NutsArgument a = cmd.next(); if (cmd.isExecMode()) { diff --git a/toolbox/nmvn/src/main/java/net/thevpc/nuts/toolbox/mvn/NutsMvnMain.java b/toolbox/nmvn/src/main/java/net/thevpc/nuts/toolbox/mvn/NutsMvnMain.java index 7725eb341..944c55ceb 100644 --- a/toolbox/nmvn/src/main/java/net/thevpc/nuts/toolbox/mvn/NutsMvnMain.java +++ b/toolbox/nmvn/src/main/java/net/thevpc/nuts/toolbox/mvn/NutsMvnMain.java @@ -150,7 +150,7 @@ private static int callMvn(MavenCli2 cli,NutsApplicationContext appContext, Opti } private static Path createTempPom(NutsSession session) { - Path d = session.io().tmp() + Path d = NutsTmp.of(session) .createTempFolder().toFile(); try (Writer out = Files.newBufferedWriter(d.resolve("pom.xml"))) { out.write("\n" diff --git a/toolbox/noapi/src/main/java/net/thevpc/nuts/toolbox/noapi/NOpenAPIService.java b/toolbox/noapi/src/main/java/net/thevpc/nuts/toolbox/noapi/NOpenAPIService.java index dff622a94..392347627 100644 --- a/toolbox/noapi/src/main/java/net/thevpc/nuts/toolbox/noapi/NOpenAPIService.java +++ b/toolbox/noapi/src/main/java/net/thevpc/nuts/toolbox/noapi/NOpenAPIService.java @@ -40,17 +40,18 @@ public void run(String source, String target, boolean keep) { targetType = "adoc"; } MdDocument md = toMarkdown(source); + NutsSession session = appContext.getSession(); if (targetType.equals("adoc")) { - writeAdoc(md, target, appContext.getSession().isPlainTrace()); + writeAdoc(md, target, session.isPlainTrace()); } else if (targetType.equals("pdf")) { String temp = null; if (keep) { temp = addExtension(source, "adoc").toString(); } else { - temp = appContext.getSession().io().tmp() + temp = NutsTmp.of(session) .createTempFile("temp.adoc").toString(); } - writeAdoc(md, temp, keep && appContext.getSession().isPlainTrace()); + writeAdoc(md, temp, keep && session.isPlainTrace()); if (new File(target).getParentFile() != null) { new File(target).getParentFile().mkdirs(); } @@ -62,9 +63,9 @@ public void run(String source, String target, boolean keep) { .safe(SafeMode.UNSAFE) .toFile(new File(target)) ); - if (appContext.getSession().isPlainTrace()) { - appContext.getSession().out().printf("generated pdf %s\n", - appContext.getSession().text().ofStyled( + if (session.isPlainTrace()) { + session.out().printf("generated pdf %s\n", + NutsTexts.of(session).ofStyled( target, NutsTextStyle.primary4() ) ); @@ -73,7 +74,7 @@ public void run(String source, String target, boolean keep) { new File(temp).delete(); } } else { - throw new NutsIllegalArgumentException(appContext.getSession(), NutsMessage.cstyle("unsupported")); + throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("unsupported")); } } @@ -85,7 +86,7 @@ private void writeAdoc(MdDocument md, String target, boolean trace) { } if (trace) { appContext.getSession().out().printf("generated src %s\n", - appContext.getSession().text().ofStyled( + NutsTexts.of(appContext.getSession()).ofStyled( target, NutsTextStyle.primary4() ) ); @@ -131,17 +132,19 @@ private MdDocument toMarkdown(String source) { } private NutsElement loadElement(InputStream inputStream, boolean json) { + NutsSession session = appContext.getSession(); if (json) { - return appContext.getSession().elem().setContentType(NutsContentType.JSON).parse(inputStream, NutsElement.class); + return NutsElements.of(session).json().parse(inputStream, NutsElement.class); } else { - return appContext.getSession().elem().setContentType(NutsContentType.YAML).parse(inputStream, NutsElement.class); + return NutsElements.of(session).json().parse(inputStream, NutsElement.class); // final Object o = new Yaml().load(inputStream); // return appContext.getWorkspace().elem().toElement(o); } } private MdDocument toMarkdown(InputStream inputStream, boolean json) { - NutsElementFormat prv = appContext.getSession().elem(); + NutsSession session = appContext.getSession(); + NutsElements prv = NutsElements.of(session); MdDocumentBuilder doc = new MdDocumentBuilder(); doc.setProperty("headers", new String[]{ ":source-highlighter: coderay", @@ -400,7 +403,8 @@ private MdDocument toMarkdown(InputStream inputStream, boolean json) { } private String toCode(NutsElement o, String indent) { - NutsElementFormat prv = appContext.getSession().elem(); + NutsSession session = appContext.getSession(); + NutsElements prv = NutsElements.of(session); String descSep = " // "; if (o.isObject()) { NutsElement a = o.asObject().get(prv.forString("schema")); diff --git a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/NutsServerComponent.java b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/NutsServerComponent.java index 388adfc08..bcc6fb2ae 100644 --- a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/NutsServerComponent.java +++ b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/NutsServerComponent.java @@ -27,12 +27,13 @@ import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.spi.NutsComponent; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; /** * Created by vpc on 1/24/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public interface NutsServerComponent extends NutsComponent { /** diff --git a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/NutsServerMain.java b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/NutsServerMain.java index af71e706f..a5cc7eeb7 100644 --- a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/NutsServerMain.java +++ b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/NutsServerMain.java @@ -57,7 +57,7 @@ private void list(NutsApplicationContext context, NutsCommandLine cmdLine) { if (servers.isEmpty()) { out.print("No Server is Running by current instance\n"); } - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); for (NutsServer o : servers) { if (o.isRunning()) { out.printf("%s %s\n", @@ -74,8 +74,8 @@ private void list(NutsApplicationContext context, NutsCommandLine cmdLine) { } private void stop(NutsApplicationContext context, NutsCommandLine cmdLine) { - NutsWorkspaceServerManager serverManager = new DefaultNutsWorkspaceServerManager(context.getSession()); - NutsCommandLineManager commandLineFormat = context.getSession().commandLine(); + NutsSession session = context.getSession(); + NutsWorkspaceServerManager serverManager = new DefaultNutsWorkspaceServerManager(session); String s; int count = 0; while (cmdLine.hasNext()) { @@ -85,7 +85,7 @@ private void stop(NutsApplicationContext context, NutsCommandLine cmdLine) { break; } count++; - s = cmdLine.nextRequiredNonOption(commandLineFormat.createName("ServerName")).getString(); + s = cmdLine.nextRequiredNonOption(NutsArgumentName.of("ServerName",session)).getString(); if (cmdLine.isExecMode()) { serverManager.stopServer(s); } @@ -94,7 +94,6 @@ private void stop(NutsApplicationContext context, NutsCommandLine cmdLine) { private void start(NutsApplicationContext context, NutsCommandLine commandLine) { NutsWorkspaceServerManager serverManager = new DefaultNutsWorkspaceServerManager(context.getSession()); - NutsCommandLineManager commandLineFormat = context.getSession().commandLine(); SrvInfoList servers = new SrvInfoList(context.getSession()); NutsArgument a; while (commandLine.hasNext()) { @@ -309,7 +308,6 @@ public String getStatus() { private void status(NutsApplicationContext context, NutsCommandLine commandLine) { NutsWorkspaceServerManager serverManager = new DefaultNutsWorkspaceServerManager(context.getSession()); - NutsCommandLineManager commandLineFormat = context.getSession().commandLine(); SrvInfoList servers = new SrvInfoList(context.getSession()); NutsArgument a; while (commandLine.hasNext()) { @@ -391,7 +389,7 @@ private void status(NutsApplicationContext context, NutsCommandLine commandLine) } } if (context.getSession().isPlainOut()) { - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(context.getSession()); for (StatusResult result : results) { context.getSession().out().printf( "%s server at %s is %s%n", diff --git a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/admin/AdminServerRunnable.java b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/admin/AdminServerRunnable.java index 0f7778f28..5ea879a0a 100644 --- a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/admin/AdminServerRunnable.java +++ b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/admin/AdminServerRunnable.java @@ -35,7 +35,8 @@ import net.thevpc.nuts.*; import net.thevpc.nuts.spi.NutsComponent; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShell; import net.thevpc.nuts.toolbox.nutsserver.NutsServer; @@ -51,18 +52,18 @@ public class AdminServerRunnable implements NutsServer, Runnable { int finalBacklog; InetAddress address; Executor finalExecutor; - NutsSession invokerWorkspace; + NutsSession invokerSession; boolean running; ServerSocket serverSocket = null; NutsSession session = null; - public AdminServerRunnable(String serverId, int finalPort, int finalBacklog, InetAddress address, Executor finalExecutor, NutsSession invokerWorkspace, NutsSession session) { + public AdminServerRunnable(String serverId, int finalPort, int finalBacklog, InetAddress address, Executor finalExecutor, NutsSession invokerSession, NutsSession session) { this.serverId = serverId; this.finalPort = finalPort; this.finalBacklog = finalBacklog; this.address = address; this.finalExecutor = finalExecutor; - this.invokerWorkspace = invokerWorkspace; + this.invokerSession = invokerSession; this.session = session; } @@ -117,15 +118,16 @@ public void run() { try { try { PrintStream out = new PrintStream(finalAccept.getOutputStream()); - NutsPrintStream eout = invokerWorkspace.io().createPrintStream(out, NutsTerminalMode.FORMATTED); - NutsSession session = invokerWorkspace; + NutsPrintStream eout = NutsPrintStream.of(out, NutsTerminalMode.FORMATTED, invokerSession); + NutsSession session = invokerSession; session.setTerminal( - invokerWorkspace.term().createTerminal( + NutsSessionTerminal.of( finalAccept.getInputStream(), - eout,eout) + eout,eout, invokerSession) ); cli = new JShell(session, - invokerWorkspace.id().setSession(session).resolveId(AdminServerRunnable.class), + NutsIdResolver.of(invokerSession) + .resolveId(AdminServerRunnable.class), serverId,new String[0]); cli.getRootContext().builtins().unset("connect"); cli.getRootContext().builtins().set(new StopServerBuiltin2(finalServerSocket)); @@ -153,7 +155,7 @@ public String toString() { return "Nuts Admin Server{" + "running=" + running + '}'; } - @NutsSingleton + @NutsComponentScope(NutsComponentScopeType.WORKSPACE) private static class StopServerBuiltin2 extends SimpleNshBuiltin { private final ServerSocket socket; diff --git a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/admin/NutsAdminServerComponent.java b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/admin/NutsAdminServerComponent.java index bb041fae5..a0a978491 100644 --- a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/admin/NutsAdminServerComponent.java +++ b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/admin/NutsAdminServerComponent.java @@ -89,7 +89,7 @@ public NutsServer start(NutsSession invokerWorkspace, ServerConfig config) { } InetSocketAddress inetSocketAddress = new InetSocketAddress(address, port); NutsPrintStream out = session.out(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); out.printf("Nuts Admin Service '%s' running %s at %s\n", serverId, factory.ofStyled("telnet nsh",NutsTextStyle.primary1()), inetSocketAddress); out.printf("Serving workspace : %s\n", invokerWorkspace.locations().getWorkspaceLocation()); AdminServerRunnable myNutsServer = new AdminServerRunnable(serverId, port, backlog, address, executor, invokerWorkspace, session); diff --git a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/NutsHttpServerComponent.java b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/NutsHttpServerComponent.java index 5511bb249..c6b7abdf4 100644 --- a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/NutsHttpServerComponent.java +++ b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/NutsHttpServerComponent.java @@ -233,7 +233,7 @@ public void handle(final HttpExchange httpExchange) throws IOException { }); server.start(); NutsPrintStream out = session.out(); - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); out.printf("Nuts Http Service '%s' running %s at %s\n", serverId, factory.ofStyled( (httpConfig.isTls() ? "https" : "http"), NutsTextStyle.primary1() diff --git a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/DeployFacadeCommand.java b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/DeployFacadeCommand.java index ffc3c351e..bfd408fd7 100644 --- a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/DeployFacadeCommand.java +++ b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/DeployFacadeCommand.java @@ -1,9 +1,6 @@ package net.thevpc.nuts.toolbox.nutsserver.http.commands; -import net.thevpc.nuts.NutsBlankable; -import net.thevpc.nuts.NutsDescriptor; -import net.thevpc.nuts.NutsId; -import net.thevpc.nuts.NutsUtilStrings; +import net.thevpc.nuts.*; import net.thevpc.nuts.toolbox.nutsserver.AbstractFacadeCommand; import net.thevpc.nuts.toolbox.nutsserver.FacadeCommandContext; import net.thevpc.nuts.toolbox.nutsserver.util.ItemStreamInfo; @@ -28,7 +25,8 @@ public void executeImpl(FacadeCommandContext context) throws IOException { context.sendError(400, "invalid JShellCommandNode arguments : " + getName() + " . invalid format."); return; } - MultipartStreamHelper stream = new MultipartStreamHelper(context.getRequestBody(), boundary,context.getSession()); + NutsSession session = context.getSession(); + MultipartStreamHelper stream = new MultipartStreamHelper(context.getRequestBody(), boundary, session); NutsDescriptor descriptor = null; String receivedContentHash = null; InputStream content = null; @@ -38,28 +36,28 @@ public void executeImpl(FacadeCommandContext context) throws IOException { switch (name) { case "descriptor": try { - descriptor = context.getSession().descriptor().parser() - .setSession(context.getSession()).parse(info.getContent()); + descriptor = NutsDescriptorParser.of(session) + .setSession(session).parse(info.getContent()); } finally { info.getContent().close(); } break; case "content-hash": try { - receivedContentHash = context.getSession().io().hash().setSource(info.getContent()).computeString(); + receivedContentHash = NutsHash.of(session).setSource(info.getContent()).computeString(); } finally { info.getContent().close(); } break; case "content": - contentFile = context.getSession().io().tmp() - .setSession(context.getSession()) + contentFile = NutsTmp.of(session) + .setSession(session) .createTempFile( - context.getSession().locations().getDefaultIdFilename( + session.locations().getDefaultIdFilename( descriptor.getId().builder().setFaceDescriptor().build() )).toString(); - context.getSession().io().copy() - .setSession(context.getSession()) + NutsCp.of(session) + .setSession(session) .setSource(info.getContent()) .setTarget(contentFile) .run(); @@ -69,10 +67,10 @@ public void executeImpl(FacadeCommandContext context) throws IOException { if (contentFile == null) { context.sendError(400, "invalid JShellCommandNode arguments : " + getName() + " : missing file"); } - NutsId id = context.getSession().deploy().setContent(contentFile) + NutsId id = session.deploy().setContent(contentFile) .setSha1(receivedContentHash) .setDescriptor(descriptor) - .setSession(context.getSession().copy()) + .setSession(session.copy()) .getResult()[0]; // NutsId id = workspace.deploy(content, descriptor, null); context.sendResponseText(200, id.toString()); diff --git a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/ExecFacadeCommand.java b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/ExecFacadeCommand.java index 33349b806..b1cf31ee4 100644 --- a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/ExecFacadeCommand.java +++ b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/ExecFacadeCommand.java @@ -1,5 +1,6 @@ package net.thevpc.nuts.toolbox.nutsserver.http.commands; +import net.thevpc.nuts.NutsPrintStream; import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.NutsTerminalMode; import net.thevpc.nuts.NutsWorkspace; @@ -57,7 +58,7 @@ public void executeImpl(FacadeCommandContext context) throws IOException { } NutsSession session = context.getSession(); ByteArrayOutputStream out = new ByteArrayOutputStream(); - session.getTerminal().setOut(session.io().createPrintStream(out, NutsTerminalMode.FILTERED)); + session.getTerminal().setOut(NutsPrintStream.of(out, NutsTerminalMode.FILTERED,session)); session.getTerminal().setIn(new ByteArrayInputStream(new byte[0])); int result = session.exec() diff --git a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/GetMavenFacadeCommand.java b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/GetMavenFacadeCommand.java index 513898fc3..faec32a62 100644 --- a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/GetMavenFacadeCommand.java +++ b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/GetMavenFacadeCommand.java @@ -25,12 +25,13 @@ public void executeImpl(FacadeCommandContext context) throws IOException { // System.out.println("get-mvn " + uri.toString()); List split = NutsServerUtils.split(uri.toString(), "/"); String n = split.get(split.size() - 1); + NutsSession session = context.getSession(); if (n.endsWith(".pom")) { if (split.size() >= 4) { - NutsId id = context.getSession().id().builder().setArtifactId(split.get(split.size() - 3)) + NutsId id = NutsIdBuilder.of(session).setArtifactId(split.get(split.size() - 3)) .setGroupId(String.join(".", split.subList(0, split.size() - 3))) .setVersion(split.get(split.size() - 2)).build(); - NutsDefinition fetch = context.getSession().fetch().setId(id).setSession(context.getSession()) + NutsDefinition fetch = session.fetch().setId(id).setSession(session) .getResultDefinition(); NutsDescriptor d = fetch.getDescriptor(); if(context.isHeadMethod()){ @@ -105,10 +106,10 @@ public void executeImpl(FacadeCommandContext context) throws IOException { } } else if (n.endsWith(".jar")) { if (split.size() >= 4) { - NutsId id = context.getSession().id().builder().setArtifactId(split.get(split.size() - 3)) + NutsId id = NutsIdBuilder.of(session).setArtifactId(split.get(split.size() - 3)) .setGroupId(String.join(".", split.subList(0, split.size() - 3))) .setVersion(split.get(split.size() - 2)).build(); - NutsDefinition fetch = context.getSession().fetch().setId(id).setSession(context.getSession()) + NutsDefinition fetch = session.fetch().setId(id).setSession(session) .getResultDefinition(); if(context.isHeadMethod()){ context.sendResponseHeaders(200,-1); @@ -120,9 +121,9 @@ public void executeImpl(FacadeCommandContext context) throws IOException { } } else if (n.equals("maven-metadata.xml")) { if (split.size() >= 3) { - NutsId id = context.getSession().id().builder().setArtifactId(split.get(split.size() - 2)) + NutsId id = NutsIdBuilder.of(session).setArtifactId(split.get(split.size() - 2)) .setGroupId(String.join(".", split.subList(0, split.size() - 2))).build(); - NutsStream resultIds = context.getSession().search().addId(id).setDistinct(true).setSorted(true).getResultIds(); + NutsStream resultIds = session.search().addId(id).setDistinct(true).setSorted(true).getResultIds(); if(context.isHeadMethod()){ context.sendResponseHeaders(200,-1); return; diff --git a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/VersionFacadeCommand.java b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/VersionFacadeCommand.java index 8de58ae84..6aac18d09 100644 --- a/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/VersionFacadeCommand.java +++ b/toolbox/nserver/src/main/java/net/thevpc/nuts/toolbox/nutsserver/http/commands/VersionFacadeCommand.java @@ -1,5 +1,7 @@ package net.thevpc.nuts.toolbox.nutsserver.http.commands; +import net.thevpc.nuts.NutsIdBuilder; +import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.toolbox.nutsserver.AbstractFacadeCommand; import net.thevpc.nuts.toolbox.nutsserver.FacadeCommandContext; @@ -12,13 +14,13 @@ public VersionFacadeCommand() { @Override public void executeImpl(FacadeCommandContext context) throws IOException { + NutsSession session = context.getSession(); context.sendResponseText(200, - context.getSession() - .id().builder() + NutsIdBuilder.of(session) .setRepository(context.getServerId()) .setGroupId("net.thevpc.nuts") .setArtifactId("nuts-server") - .setVersion(context.getSession().getWorkspace().getRuntimeId().getVersion().toString()) + .setVersion(session.getWorkspace().getRuntimeId().getVersion().toString()) .build().toString() ); } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/AbstractNshBuiltin.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/AbstractNshBuiltin.java index 2a964e439..049f46eec 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/AbstractNshBuiltin.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/AbstractNshBuiltin.java @@ -56,7 +56,8 @@ public AbstractNshBuiltin(String name, int supportLevel) { } protected NutsCommandLine cmdLine(String[] args, JShellExecutionContext context) { - return context.getSession().commandLine().create(args) + NutsSession session = context.getSession(); + return NutsCommandLine.of(args,session) .setAutoComplete(context.getShellContext().getAutoComplete()) .setCommandName(getName()); } @@ -163,7 +164,7 @@ public String getHelpHeader() { protected void throwExecutionException(Object errObject,int errorCode,NutsSession session) { session=session.copy(); - NutsPrintStream printStream = session.io().createMemoryPrintStream(); + NutsPrintStream printStream = NutsMemoryPrintStream.of(session); if (errObject != null) { printStream.printf(errObject); }else{ diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/Nsh.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/Nsh.java index 67a363fd3..e189a1188 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/Nsh.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/Nsh.java @@ -87,7 +87,7 @@ public void onInstallApplication(NutsApplicationContext applicationContext) { }); } if (session.isPlainTrace()) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); if (firstInstalled.size() > 0) { session.out().printf("registered %s nsh commands : %s \n", factory.ofStyled(""+firstInstalled.size(),NutsTextStyle.primary3()) @@ -135,7 +135,7 @@ public void onUninstallApplication(NutsApplicationContext applicationContext) { session.commands().removeCommand(command.getName()); } catch (Exception ex) { if (applicationContext.getSession().isPlainTrace()) { - NutsTextManager factory = session.text(); + NutsTexts factory = NutsTexts.of(session); applicationContext.getSession().err().printf("unable to uninstall %s.\n", factory.ofStyled(command.getName(),NutsTextStyle.primary3()) ); diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/NshEvaluator.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/NshEvaluator.java index be67ef0b1..45772abd8 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/NshEvaluator.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/NshEvaluator.java @@ -25,12 +25,10 @@ */ package net.thevpc.nuts.toolbox.nsh; +import net.thevpc.nuts.*; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.*; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.util.JavaShellNonBlockingInputStream; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.util.JavaShellNonBlockingInputStreamAdapter; -import net.thevpc.nuts.NutsPrintStream; -import net.thevpc.nuts.NutsSessionTerminal; -import net.thevpc.nuts.NutsTerminalMode; import java.io.*; import java.util.logging.Level; @@ -48,7 +46,7 @@ public int evalBinaryPipeOperation(JShellCommandNode left, JShellCommandNode rig final JavaShellNonBlockingInputStream in2; try { out = new PipedOutputStream(); - nout = context.getSession().io().createPrintStream(out, NutsTerminalMode.FORMATTED); + nout = NutsPrintStream.of(out, NutsTerminalMode.FORMATTED, context.getSession()); in = new PipedInputStream(out, 1024); in2 = (in instanceof JavaShellNonBlockingInputStream) ? (JavaShellNonBlockingInputStream) in : new JavaShellNonBlockingInputStreamAdapter("jpipe-" + right.toString(), in); } catch (IOException ex) { @@ -98,16 +96,17 @@ public void run() { public String evalCommandAndReturnString(JShellCommandNode command, JShellContext context) { JShellContext c1 = context.getShell().createNewContext(context); DefaultJShellContext c2 = (DefaultJShellContext) c1; - c2.setSession(c2.getSession().copy()); - c2.getSession().setLogLevel(Level.OFF); + NutsSession session = c2.getSession(); + c2.setSession(session.copy()); + session.setLogLevel(Level.OFF); - NutsPrintStream out = NutsPrintStream.ofMemory(c2.getSession()); - NutsPrintStream err = NutsPrintStream.ofMemory(c2.getSession()); + NutsPrintStream out = NutsMemoryPrintStream.of(session); + NutsPrintStream err = NutsMemoryPrintStream.of(session); - NutsSessionTerminal terminal = c2.getSession().term().createTerminal( - new ByteArrayInputStream(new byte[0]), out, err + NutsSessionTerminal terminal = NutsSessionTerminal.of( + new ByteArrayInputStream(new byte[0]), out, err,session ); - c2.getSession().setTerminal(terminal); + session.setTerminal(terminal); context.getShell().evalNode(command,c1); String str = evalFieldSubstitutionAfterCommandSubstitution(out.toString(), context); String s = context.getShell().escapeString(str); diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/NutsErrorHandler.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/NutsErrorHandler.java index 951702cc4..19ebeecf6 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/NutsErrorHandler.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/NutsErrorHandler.java @@ -27,6 +27,7 @@ package net.thevpc.nuts.toolbox.nsh; import net.thevpc.nuts.NutsPrintStream; +import net.thevpc.nuts.NutsTexts; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.*; import net.thevpc.nuts.NutsExecutionException; import net.thevpc.nuts.NutsTextStyle; @@ -63,8 +64,7 @@ public String errorToMessage(Throwable th) { public void onError(String message, Throwable th, JShellContext context) { NutsPrintStream err = context.getSession().getTerminal().err(); err.printf("%s\n", - context.getSession() - .text().ofStyled(message, NutsTextStyle.error()) + NutsTexts.of(context.getSession()).ofStyled(message, NutsTextStyle.error()) ); err.flush(); } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/SimpleNshBuiltin.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/SimpleNshBuiltin.java index 1b8636028..e148f5a84 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/SimpleNshBuiltin.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/SimpleNshBuiltin.java @@ -113,7 +113,8 @@ public int execImpl(String[] args, JShellExecutionContext context) { boolean conf = false; int maxLoops = 1000; boolean robustMode = false; - NutsCommandLine commandLine = context.getSession().commandLine().create(args).setCommandName(getName()); + NutsSession session = context.getSession(); + NutsCommandLine commandLine = NutsCommandLine.of(args,session).setCommandName(getName()); initCommandLine(commandLine); SimpleNshCommandContext context2 = new SimpleNshCommandContext(args, context, createOptions()); while (commandLine.hasNext()) { diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/collections/EvictingQueue.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/collections/EvictingQueue.java new file mode 100644 index 000000000..b822bfb8c --- /dev/null +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/collections/EvictingQueue.java @@ -0,0 +1,69 @@ +package net.thevpc.nuts.toolbox.nsh.bundles.collections; + +import java.util.AbstractList; +import java.util.Arrays; + +public class EvictingQueue extends AbstractList{ + private int from=0; + private int len; + private Object[] values; + + public EvictingQueue(int max) { + this.values=new Object[max]; + } + + public void clear() { + from=0; + len=0; + } + + public int size() { + return len; + } + + public T get(int pos) { + if(pos>=0 && pos0){ + sb.append(","); + } + sb.append(get(i)); + } + sb.append("}"); + return sb.toString(); + } +} diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/AbstractJShellContext.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/AbstractJShellContext.java index e1f452cdb..77b9ebbf2 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/AbstractJShellContext.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/AbstractJShellContext.java @@ -92,7 +92,7 @@ public Watcher bindStreams(InputStream out, InputStream err, OutputStream in) { @Override public JShellContext setOut(PrintStream out) { getSession().getTerminal().setOut( - getSession().io().createPrintStream(out) + NutsPrintStream.of(out,getSession()) ); // commandContext.getTerminal().setOut(workspace.createPrintStream(out, // true//formatted @@ -102,7 +102,7 @@ public JShellContext setOut(PrintStream out) { public JShellContext setErr(PrintStream err) { getSession().getTerminal().setErr( - getSession().io().createPrintStream(err) + NutsPrintStream.of(err,getSession()) ); return this; } @@ -166,8 +166,7 @@ public List resolveAutoCompleteCandidates(String co if (s.length() > 0) { if (s.startsWith(NutsApplicationContext.AUTO_COMPLETE_CANDIDATE_PREFIX)) { s = s.substring(NutsApplicationContext.AUTO_COMPLETE_CANDIDATE_PREFIX.length()).trim(); - NutsCommandLineManager commandLineFormat = session.commandLine(); - NutsCommandLine args = commandLineFormat.parse(s); + NutsCommandLine args = NutsCommandLine.parse(s,session); String value = null; String display = null; if (args.hasNext()) { @@ -181,9 +180,9 @@ public List resolveAutoCompleteCandidates(String co display = value; } autoComplete.addCandidate( - commandLineFormat.createCandidate( + new NutsArgumentCandidate( value - ).build() + ) ); } } else { @@ -225,7 +224,7 @@ public void copyFrom(JShellContext other) { setParentNode(other.getParentNode()); setFileSystem(other.getFileSystem()); setCwd(other.getCwd()); - setSession(other.session() == null ? null : other.session().copy()); + setSession(other.getSession() == null ? null : other.getSession().copy()); setFunctionManager(other.functions()); } } @@ -271,11 +270,6 @@ public List getArgsList() { return args; } - @Override - public NutsSession session() { - return getSession(); - } - @Override public NutsSession getSession() { return session; @@ -287,11 +281,6 @@ public JShellContext setSession(NutsSession session) { return this; } - @Override - public NutsWorkspace workspace() { - return getWorkspace(); - } - @Override public NutsWorkspace getWorkspace() { return getSession().getWorkspace(); diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/DefaultJShellExecutionContext.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/DefaultJShellExecutionContext.java index 88528df5d..6b6d92271 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/DefaultJShellExecutionContext.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/DefaultJShellExecutionContext.java @@ -76,7 +76,7 @@ public boolean configureFirst(NutsCommandLine cmd) { case "--version": { cmd.skip(); if (cmd.isExecMode()) { - out().printf("%s%n", getSession().id().setSession(getSession()).resolveId(getClass()).getVersion().toString()); + out().printf("%s%n", NutsIdResolver.of(getSession()).resolveId(getClass()).getVersion().toString()); cmd.skipAll(); } throw new NutsExecutionException(shellContext.getSession(), NutsMessage.cstyle("Help"), 0); diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/DefaultJShellOptionsParser.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/DefaultJShellOptionsParser.java index 464fde9c0..50f86e9d5 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/DefaultJShellOptionsParser.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/DefaultJShellOptionsParser.java @@ -2,6 +2,7 @@ import net.thevpc.nuts.NutsApplicationContext; import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.NutsSession; import java.util.ArrayList; import java.util.Arrays; @@ -197,8 +198,9 @@ protected void parseNextArgument(List args, JShellOptions options) { } protected void parseUnsupportedNextArgument(List args, JShellOptions options) { - NutsCommandLine a = appContext.getSession().commandLine().create(args); - if(appContext.getSession().configureFirst(a)){ + NutsSession session = appContext.getSession(); + NutsCommandLine a = NutsCommandLine.of(args,session); + if(session.configureFirst(a)){ //replace remaining... args.clear(); args.addAll(Arrays.asList(a.toStringArray())); diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/JShell.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/JShell.java index 2e7938e17..c2f6e322a 100755 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/JShell.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/JShell.java @@ -80,15 +80,15 @@ public JShell(NutsApplicationContext appContext, String[] args) { } public JShell(NutsSession session, String[] args) { - this(session.apps().createApplicationContext(null, new String[]{}, 0, Nsh.class, null), null, null, args); + this(NutsApplicationContext.of(new String[]{}, 0, Nsh.class, null,session), null, null, args); } public JShell(NutsSession session, NutsId appId, String[] args) { - this(session.apps().createApplicationContext(session, new String[]{}, 0, Nsh.class, null), appId, null, args); + this(NutsApplicationContext.of(new String[]{}, 0, Nsh.class, null,session), appId, null, args); } public JShell(NutsSession session, NutsId appId, String serviceName, String[] args) { - this(session.apps().createApplicationContext(session, new String[]{}, 0, Nsh.class, null), appId, serviceName, args); + this(NutsApplicationContext.of(new String[]{}, 0, Nsh.class, null,session), appId, serviceName, args); } private JShell(NutsApplicationContext appContext, NutsId appId, String serviceName, String[] args) { @@ -101,7 +101,7 @@ private JShell(NutsApplicationContext appContext, NutsId appId, String serviceNa this.appId = appId; //super.setCwd(workspace.getConfigManager().getCwd()); if (this.appId == null) { - this.appId = appContext.getSession().id().resolveId(JShell.class); + this.appId = NutsIdResolver.of(appContext.getSession()).resolveId(JShell.class); } if (this.appId == null) { throw new IllegalArgumentException("unable to resolve application id"); @@ -192,7 +192,7 @@ private static String[] resolveArgs(NutsApplicationContext appContext, String[] private static String resolveServiceName(NutsApplicationContext appContext, String serviceName, NutsId appId) { if ((serviceName == null || serviceName.trim().isEmpty())) { if (appId == null) { - appId = appContext.getSession().id().resolveId(JShell.class); + appId = NutsIdResolver.of(appContext.getSession()).resolveId(JShell.class); } serviceName = appId.getArtifactId(); } @@ -558,7 +558,7 @@ protected String readInteractiveLine(JShellContext context) { } protected void printHeader(NutsPrintStream out) { - out.resetLine().println(appContext.getSession().text().builder() + out.resetLine().println(NutsTexts.of(appContext.getSession()).builder() .appendCode("sh", "nuts") .append(" shell ") .append("v" + getRootContext().getWorkspace().getRuntimeId().getVersion().toString(), NutsTextStyle.version()) @@ -575,18 +575,18 @@ protected void executeVersion(JShellContext context) { } protected void executeInteractive(JShellContext context) { - appContext.getSession().term().enableRichTerm(); - appContext.getSession().term().getSystemTerminal() + NutsSession session = appContext.getSession(); + NutsSystemTerminal.enableRichTerm(session); + session.config().getSystemTerminal() .setCommandAutoCompleteResolver(new NshAutoCompleter()) .setCommandHistory( - appContext.getSession().commandLine().createHistory() + NutsCommandHistory.of(session) .setPath(Paths.get(appContext.getVarFolder()).resolve("nsh-history.hist")) - .build() ) .setCommandReadHighlighter(new NutsCommandReadHighlighter() { @Override public NutsText highlight(String buffer, NutsSession session) { - return session.text().ofCode("sh", buffer).highlight(session); + return NutsTexts.of(session).ofCode("sh", buffer).highlight(session); } }); prepareContext(getRootContext()); @@ -1084,7 +1084,7 @@ public JShellHistory getHistory() { } public String getVersion() { - NutsId nutsId = appContext.getSession().id().resolveId(getClass()); + NutsId nutsId = NutsIdResolver.of(appContext.getSession()).resolveId(getClass()); if (nutsId == null) { return "dev"; } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/JShellContext.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/JShellContext.java index 965bf5fc3..f643ca8fd 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/JShellContext.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/JShellContext.java @@ -98,14 +98,10 @@ public interface JShellContext { // JShellContext copy() ; - NutsSession session(); - NutsSession getSession(); JShellContext setSession(NutsSession session); - NutsWorkspace workspace(); - NutsWorkspace getWorkspace(); NutsCommandAutoComplete getAutoComplete(); diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/NshAutoCompleter.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/NshAutoCompleter.java index 146be2200..6df06205a 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/NshAutoCompleter.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/NshAutoCompleter.java @@ -15,7 +15,7 @@ public List resolveCandidates(NutsCommandLine commandline if (wordIndex == 0) { for (JShellBuiltin command : fileContext.builtins().getAll()) { - candidates.add(session.commandLine().createCandidate(command.getName()).build()); + candidates.add(new NutsArgumentCandidate(command.getName())); } } else { List autoCompleteWords = new ArrayList<>(Arrays.asList(commandline.toStringArray())); @@ -32,7 +32,7 @@ public List resolveCandidates(NutsCommandLine commandline if (NutsBlankable.isBlank(display)) { display = value; } - candidates.add(session.commandLine().createCandidate(value).setDisplay(display).build()); + candidates.add(new NutsArgumentCandidate(value,display)); } } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/parser/Yaccer.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/parser/Yaccer.java index 906cc7621..84c858c07 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/parser/Yaccer.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/bundles/jshell/parser/Yaccer.java @@ -614,10 +614,10 @@ public Argument readArgument() { return null; } return new Argument(a); -// List ok = new ArrayList<>(); +// List ok = new ArrayList<>(); // boolean loop = true; // while (loop) { -// Token t = jShellParser2.lexer().peedToken(); +// NutsToken t = jShellParser2.lexer().peedToken(); // if (t == null) { // break; // } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/AliasCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/AliasCommand.java index 40772cd13..3c0aa2280 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/AliasCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/AliasCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -10,62 +10,40 @@ * to share shell scripts and other 'things' . Its based on an extensible * architecture to help supporting a large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; import net.thevpc.nuts.NutsArgument; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShell; -import net.thevpc.nuts.NutsCommandLine; + +import java.util.*; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class AliasCommand extends SimpleNshBuiltin { public AliasCommand() { super("alias", DEFAULT_SUPPORT); } - private static class Options { - - LinkedHashMap add = new LinkedHashMap(); - Set show = new LinkedHashSet(); - List displayOptions = new ArrayList(); - } - - private static class ResultItem { - - String name; - String value; - - public ResultItem(String name, String value) { - this.name = name; - this.value = value; - } - - } - @Override protected Object createOptions() { return new Options(); @@ -113,8 +91,8 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext outRes.add(new ResultItem(a, v)); } } - switch (context.getSession().getOutputFormat()){ - case PLAIN:{ + switch (context.getSession().getOutputFormat()) { + case PLAIN: { for (ResultItem resultItem : outRes) { if (resultItem.value == null) { context.getSession().err().printf("alias : %s ```error not found```%n", resultItem.name); @@ -124,14 +102,33 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } break; } - default:{ + default: { context.getSession().out().printlnf(outRes); } } if (!errRes.isEmpty()) { - throwExecutionException(errRes,1,context.getSession()); + throwExecutionException(errRes, 1, context.getSession()); } } + private static class Options { + + LinkedHashMap add = new LinkedHashMap(); + Set show = new LinkedHashSet(); + List displayOptions = new ArrayList(); + } + + private static class ResultItem { + + String name; + String value; + + public ResultItem(String name, String value) { + this.name = name; + this.value = value; + } + + } + } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/AutocompleteCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/AutocompleteCommand.java index cf594e346..80fb04e6d 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/AutocompleteCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/AutocompleteCommand.java @@ -10,7 +10,7 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -22,33 +22,27 @@ * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellAutoCompleteCandidate; import java.util.*; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class AutocompleteCommand extends SimpleNshBuiltin { public AutocompleteCommand() { super("autocomplete", DEFAULT_SUPPORT); } - private static class Options { - - String cmd = null; - List items = new ArrayList<>(); - int index = -1; - } - @Override protected Object createOptions() { return new Options(); @@ -79,8 +73,9 @@ protected boolean configureFirst(NutsCommandLine cmdLine, SimpleNshCommandContex @Override protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext context) { Options options = context.getOptions(); + NutsSession session = context.getSession(); if (options.cmd == null) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("missing JShellCommandNode"), 1); + throw new NutsExecutionException(session, NutsMessage.cstyle("missing JShellCommandNode"), 1); } if (options.index < 0) { options.index = options.items.size(); @@ -88,7 +83,7 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } List aa = context.getRootContext().resolveAutoCompleteCandidates( options.cmd, options.items, options.index, - context.getSession().commandLine().create(options.items).toString() + NutsCommandLine.of(options.items, session).toString() ); Properties p = new Properties(); for (JShellAutoCompleteCandidate autoCompleteCandidate : aa) { @@ -99,27 +94,34 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } p.setProperty(value == null ? "" : value, dvalue == null ? "" : dvalue); } - switch (context.getSession().getOutputFormat()) { + switch (session.getOutputFormat()) { case PLAIN: { - NutsTextManager text = context.getSession().text(); + NutsTexts text = NutsTexts.of(session); for (String o : new TreeSet((Set) p.keySet())) { if (o.startsWith("-")) { // option - context.getSession().out().printf("%s\n", text.ofStyled(o,NutsTextStyle.primary4())); + session.out().printf("%s\n", text.ofStyled(o, NutsTextStyle.primary4())); } else if (o.startsWith("<")) { - context.getSession().out().printf("%s\n", text.ofStyled(o,NutsTextStyle.primary1())); + session.out().printf("%s\n", text.ofStyled(o, NutsTextStyle.primary1())); } else { - context.getSession().out().printf("%s\n", - text.ofStyled(o,NutsTextStyle.pale()) + session.out().printf("%s\n", + text.ofStyled(o, NutsTextStyle.pale()) ); } } break; } default: { - context.getSession().out().printlnf(p); + session.out().printlnf(p); } } } + private static class Options { + + String cmd = null; + List items = new ArrayList<>(); + int index = -1; + } + } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/BaseNameCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/BaseNameCommand.java index c98cba6cb..f09cf8b31 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/BaseNameCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/BaseNameCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -10,46 +10,40 @@ * to share shell scripts and other 'things' . Its based on an extensible * architecture to help supporting a large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; -import java.util.ArrayList; -import java.util.List; import net.thevpc.nuts.NutsArgument; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; + +import java.util.ArrayList; +import java.util.List; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class BaseNameCommand extends SimpleNshBuiltin { public BaseNameCommand() { super("basename", DEFAULT_SUPPORT); } - private static class Options { - - String sep = "\n"; - List names = new ArrayList<>(); - boolean multi = false; - String suffix = null; - } - @Override protected Object createOptions() { return new Options(); @@ -135,7 +129,7 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext case PLAIN: { for (int i = 0; i < results.size(); i++) { String name = results.get(i); - if(i>0){ + if (i > 0) { context.getSession().out().print(options.sep); } context.getSession().out().print(name); @@ -148,5 +142,13 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } } + private static class Options { + + String sep = "\n"; + List names = new ArrayList<>(); + boolean multi = false; + String suffix = null; + } + } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CatCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CatCommand.java index fe41d2923..4aac4ce31 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CatCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CatCommand.java @@ -26,22 +26,23 @@ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.*; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; - -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.bundles._IOUtils; import net.thevpc.nuts.toolbox.nsh.bundles._StringUtils; +import net.thevpc.nuts.toolbox.nsh.util.ColumnRuler; import net.thevpc.nuts.toolbox.nsh.util.FileInfo; import net.thevpc.nuts.toolbox.nsh.util.ShellHelper; +import java.io.*; +import java.util.ArrayList; +import java.util.List; + /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class CatCommand extends SimpleNshBuiltin { public CatCommand() { @@ -90,6 +91,15 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext NutsPrintStream out = context.getSession().out(); try { options.currentNumber = 1; + + OutputStream os = null; + boolean plain = true; + if (context.getSession().getOutputFormat() == NutsContentType.PLAIN) { + os = out.asOutputStream(); + } else { + plain = false; + } + List results = new ArrayList<>(); //text mode for (FileInfo f : options.files) { boolean close = false; @@ -112,18 +122,76 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext close = true; } try { - catText(in, out.asOutputStream(), options, context, f); + if (plain) { + catText(in, os, options, context, f); + } else { + catText2(in, options, context, f, results); + } } finally { if (close) { in.close(); } } } + if (!plain) { + out.printf(results); + } } catch (IOException ex) { throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("%s", ex), ex, 100); } } + private void catText2(InputStream in, Options options, SimpleNshCommandContext context, FileInfo info, List results) throws IOException { + boolean whole = true; + NutsSession session = context.getSession(); + if (whole && info.getHighlighter() != null) { + ByteArrayOutputStream bout = new ByteArrayOutputStream(); + NutsCp.of(session).from(in).to(bout).run(); + String text = bout.toString(); + NutsTextBuilder nutsText = NutsTexts.of(session).ofCode(info.getHighlighter(), text).highlight(session) + .builder() + .flatten(); + List children = nutsText.getChildren(); + Tracker tracker = new Tracker(); + boolean n = options.n; + options.n = false; + while (true) { + NutsText line = nextLine(children, session, tracker, options, true); + if (line != null) { + CatResult r = new CatResult(); + if (n) { + r.number = tracker.line; + } + r.line = line; + results.add(r); + } else { + break; + } + } + options.n = n; + } else { + //do not close!! + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + String line = null; + while ((line = reader.readLine()) != null) { + CatResult r = new CatResult(); + if (options.n) { + r.number = options.currentNumber; + } + if (options.T) { + line = line.replace("\t", "^I"); + } + NutsTextCode c = NutsTexts.of(session).ofCode(info.getHighlighter(), line); + line = c.highlight(session).toString(); + if (options.E) { + line += "$"; + } + r.line = NutsTexts.of(session).ofPlain(line); + options.currentNumber++; + } + } + } + private void catText(InputStream in, OutputStream os, Options options, SimpleNshCommandContext context, FileInfo info) throws IOException { if (info.getHighlighter() == null || "plain".equalsIgnoreCase(info.getHighlighter()) || "text".equalsIgnoreCase(info.getHighlighter())) { if (!options.n && !options.T && !options.E) { @@ -132,17 +200,27 @@ private void catText(InputStream in, OutputStream os, Options options, SimpleNsh } } boolean whole = true; + NutsSession session = context.getSession(); if (whole && info.getHighlighter() != null) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); - context.getSession().io().copy().from(in).to(bout).run(); + NutsCp.of(session).from(in).to(bout).run(); String text = bout.toString(); - NutsTextBuilder nutsText = context.getSession().text().ofCode(options.highlighter, text).highlight(context.getSession()) + NutsTextBuilder nutsText = NutsTexts.of(session).ofCode(info.getHighlighter(), text).highlight(session) .builder() .flatten(); - NutsPrintStream out = context.getSession().io().createPrintStream(os); - writeNode(nutsText.build(), context.getSession(), new Tracker(), out, options); + NutsPrintStream out = NutsPrintStream.of(os, session); + List children = nutsText.getChildren(); + Tracker tracker = new Tracker(); + while (true) { + NutsText line = nextLine(children, session, tracker, options, false); + if (line != null) { + out.printf(line); + } else { + break; + } + } } else { - NutsPrintStream out = context.getSession().io().createPrintStream(os); + NutsPrintStream out = NutsPrintStream.of(os, session); try { //do not close!! @@ -157,8 +235,8 @@ private void catText(InputStream in, OutputStream os, Options options, SimpleNsh line = line.replace("\t", "^I"); } - NutsTextCode c = context.getSession().text().ofCode(options.highlighter, line); - line = c.highlight(context.getSession()).toString(); + NutsTextCode c = NutsTexts.of(session).ofCode(info.getHighlighter(), line); + line = c.highlight(session).toString(); out.print(line); @@ -174,19 +252,30 @@ private void catText(InputStream in, OutputStream os, Options options, SimpleNsh } } + private NutsText nextLine(List t, NutsSession session, Tracker tracker, Options options, boolean skipNewline) { + NutsTextBuilder b = NutsTexts.of(session).builder(); + while (!t.isEmpty()) { + NutsText ii = t.remove(0); + NutsText n = nextNode(ii, session, tracker, options); + if (tracker.wasNewline) { + if (!skipNewline) { + b.append(n); + } + return b.build(); + } else { + b.append(n); + } + } + return null; + } - private void writeNode(NutsText t, NutsSession session, Tracker tracker, NutsPrintStream out, Options options) { + private NutsText nextNode(NutsText t, NutsSession session, Tracker tracker, Options options) { switch (t.getType()) { case PLAIN: { String text = ((NutsTextPlain) t).getText(); - NutsTextBuilder tb = session.text().builder(); + NutsTextBuilder tb = NutsTexts.of(session).builder(); if (options.n && tracker.wasNewline) { - String ruleText = String.valueOf(tracker.line); - if (tracker.ruleWidth <= ruleText.length()) { - tracker.ruleWidth = ruleText.length() + 1; - } - tb.append(_StringUtils.formatRight(ruleText, tracker.ruleWidth), NutsTextStyle.number()); - tb.append(" "); + tb.append(tracker.ruler.nextNum(tracker.line, session)); } if (text.charAt(0) == '\n' || text.charAt(0) == '\r') { //this is a new line @@ -206,29 +295,16 @@ private void writeNode(NutsText t, NutsSession session, Tracker tracker, NutsPri } tracker.wasNewline = false; } - out.printf(tb.build()); - break; - } - case LIST: { - NutsTextList tt = (NutsTextList) t; - for (NutsText n : tt) { - writeNode(n, session, tracker, out, options); - } - break; + return tb.build(); } case STYLED: { NutsTextStyled tt = (NutsTextStyled) t; NutsTextPlain pt = (NutsTextPlain) tt.getChild(); String text = pt.getText(); - NutsTextBuilder tb = session.text().builder(); + NutsTextBuilder tb = NutsTexts.of(session).builder(); if (options.n && tracker.wasNewline) { - String ruleText = String.valueOf(tracker.line); - if (tracker.ruleWidth <= ruleText.length()) { - tracker.ruleWidth = ruleText.length() + 1; - } - tb.append(_StringUtils.formatRight(ruleText, tracker.ruleWidth), NutsTextStyle.number()); - tb.append(" "); + tb.append(tracker.ruler.nextNum(tracker.line, session)); } for (String s : ShellHelper.splitOn(text, '\t')) { if (s.startsWith("\t")) { @@ -238,10 +314,15 @@ private void writeNode(NutsText t, NutsSession session, Tracker tracker, NutsPri } } tracker.wasNewline = false; - out.printf(tb.build()); - break; + return tb.build(); } } + throw new NutsIllegalArgumentException(session, NutsMessage.cstyle("unsupported")); + } + + public static class CatResult { + Long number; + NutsString line; } private static class Options { @@ -255,7 +336,7 @@ private static class Options { } private class Tracker { - int ruleWidth = 6; + ColumnRuler ruler = new ColumnRuler(6); long line; boolean wasNewline = true; } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CdCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CdCommand.java index 9821cee63..5daa3c3cd 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CdCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CdCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -11,7 +11,7 @@ * architecture to help supporting a large range of sub managers / repositories. * *
    - * + *

    * Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -23,28 +23,24 @@ * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class CdCommand extends SimpleNshBuiltin { public CdCommand() { super("cd", DEFAULT_SUPPORT); } - private static class Options { - - String dirname; - } - @Override protected Object createOptions() { return new Options(); @@ -72,4 +68,9 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } context.getRootContext().setCwd(options.dirname); } + + private static class Options { + + String dirname; + } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ChmodCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ChmodCommand.java index 403240a2a..aabdf6fed 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ChmodCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ChmodCommand.java @@ -10,7 +10,7 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -22,23 +22,25 @@ * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; +import net.thevpc.nuts.NutsArgument; +import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; + import java.io.File; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import net.thevpc.nuts.NutsArgument; -import net.thevpc.nuts.NutsCommandLine; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class ChmodCommand extends SimpleNshBuiltin { public ChmodCommand() { @@ -61,44 +63,6 @@ private boolean isRights(String r) { return true; } - private static class Mods { - - int x = 0; - int w = 0; - int r = 0; - boolean user = false; - boolean recursive = false; - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - if (user) { - sb.append("u"); - } else { - sb.append("a"); - } - if (r > 0) { - sb.append("+r"); - } else if (r < 0) { - sb.append("-r"); - } - if (w > 0) { - sb.append("+w"); - } else if (w < 0) { - sb.append("-w"); - } - if (x > 0) { - sb.append("+x"); - } else if (x < 0) { - sb.append("-x"); - } - if (recursive) { - sb.append(" [recursive]"); - } - return sb.toString(); - } - } - public void apply(String s, Mods m, int v) { for (char c : s.toCharArray()) { switch (c) { @@ -118,12 +82,6 @@ public void apply(String s, Mods m, int v) { } } - private static class Options { - - List files = new ArrayList<>(); - Mods m = new Mods(); - } - @Override protected Object createOptions() { return new Options(); @@ -203,7 +161,7 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext chmod(f, options.m, errors); } if (!errors.isEmpty()) { - throwExecutionException(errors,1, context.getSession()); + throwExecutionException(errors, 1, context.getSession()); } } @@ -236,4 +194,48 @@ private void chmod(File f, Mods m, Map errors) { } } } + + private static class Mods { + + int x = 0; + int w = 0; + int r = 0; + boolean user = false; + boolean recursive = false; + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + if (user) { + sb.append("u"); + } else { + sb.append("a"); + } + if (r > 0) { + sb.append("+r"); + } else if (r < 0) { + sb.append("-r"); + } + if (w > 0) { + sb.append("+w"); + } else if (w < 0) { + sb.append("-w"); + } + if (x > 0) { + sb.append("+x"); + } else if (x < 0) { + sb.append("-x"); + } + if (recursive) { + sb.append(" [recursive]"); + } + return sb.toString(); + } + } + + private static class Options { + + List files = new ArrayList<>(); + Mods m = new Mods(); + } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CommandCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CommandCommand.java index 9907661cb..19992b197 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CommandCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CommandCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -11,7 +11,7 @@ * architecture to help supporting a large range of sub managers / repositories. * *
    - * + *

    * Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -23,33 +23,28 @@ * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; -import java.util.Arrays; -import java.util.List; import net.thevpc.nuts.NutsArgument; import net.thevpc.nuts.NutsCommandLine; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; +import java.util.Arrays; +import java.util.List; + /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class CommandCommand extends SimpleNshBuiltin { public CommandCommand() { super("command", DEFAULT_SUPPORT); } - private static class Options { - - boolean p; - String commandName; - List args; - } - @Override protected Object createOptions() { return new Options(); @@ -83,4 +78,11 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } } + private static class Options { + + boolean p; + String commandName; + List args; + } + } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CpCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CpCommand.java index 35fd08e7f..4de2c1ff4 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CpCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/CpCommand.java @@ -10,50 +10,42 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellExecutionContext; import net.thevpc.nuts.toolbox.nsh.util.ShellHelper; + import java.util.ArrayList; import java.util.List; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; - /** * Created by vpc on 1/7/17. ssh copy credits to Chanaka Lakmal from * https://medium.com/ldclakmal/scp-with-java-b7b7dbcdbc85 */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class CpCommand extends SimpleNshBuiltin { public CpCommand() { super("cp", DEFAULT_SUPPORT); } - public static class Options { - - boolean mkdir; - boolean recursive; - ShellHelper.WsSshListener sshlistener; - List files = new ArrayList<>(); - List xfiles = new ArrayList<>(); - } - @Override protected Object createOptions() { return new Options(); @@ -63,19 +55,19 @@ protected Object createOptions() { protected boolean configureFirst(NutsCommandLine commandLine, SimpleNshCommandContext context) { Options options = context.getOptions(); NutsArgument a; - switch (commandLine.peek().getKey().getString()){ - case "--mkdir":{ + switch (commandLine.peek().getKey().getString()) { + case "--mkdir": { options.mkdir = commandLine.nextBoolean().getValue().getBoolean(); return true; } case "-r": case "-R": - case "--recursive":{ + case "--recursive": { options.recursive = commandLine.nextBoolean().getValue().getBoolean(); return true; } - default:{ - if(commandLine.peek().isNonOption()){ + default: { + if (commandLine.peek().isNonOption()) { options.files.add(commandLine.next().getString()); return true; } @@ -87,31 +79,32 @@ protected boolean configureFirst(NutsCommandLine commandLine, SimpleNshCommandCo @Override protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext context) { Options options = context.getOptions(); + NutsSession session = context.getSession(); for (String value : options.files) { if (NutsBlankable.isBlank(value)) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("empty file path"), 2); + throw new NutsExecutionException(session, NutsMessage.cstyle("empty file path"), 2); } - options.xfiles.add(context.getSession().io().path((value.contains("://") ? value : - context.getSession().io().path(value).builder().withWorkspaceBaseDir().build().toString() - ))); + options.xfiles.add(NutsPath.of((value.contains("://") ? value : + NutsPath.of(value, session).builder().withWorkspaceBaseDir().build().toString() + ), session)); } if (options.xfiles.size() < 2) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("missing parameters"), 2); + throw new NutsExecutionException(session, NutsMessage.cstyle("missing parameters"), 2); } - options.sshlistener = new ShellHelper.WsSshListener(context.getSession()); + options.sshlistener = new ShellHelper.WsSshListener(session); for (int i = 0; i < options.xfiles.size() - 1; i++) { copy(options.xfiles.get(i), options.xfiles.get(options.xfiles.size() - 1), options, context.getExecutionContext()); } } public void copy(NutsPath from, NutsPath to, Options o, JShellExecutionContext context) { - NutsIOCopyAction ccp = context.getSession().io().copy() + NutsSession session = context.getSession(); + NutsCp ccp = NutsCp.of(session) .from(from) .to(to) .setRecursive(o.recursive) - .setMkdirs(o.mkdir) - ; + .setMkdirs(o.mkdir); ccp.run(); // if (from.getProtocol().equals("file") && to.getProtocol().equals("file")) { // File from1 = ((JavaXFile) from).getFile(); @@ -186,6 +179,15 @@ public void copy(NutsPath from, NutsPath to, Options o, JShellExecutionContext c // } } + public static class Options { + + boolean mkdir; + boolean recursive; + ShellHelper.WsSshListener sshlistener; + List files = new ArrayList<>(); + List xfiles = new ArrayList<>(); + } + // private void copyFolder(File from1, File to1) { // try { // Files.walk(from1.toPath()) diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/DateCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/DateCommand.java index 2f7bc2a49..9097b0e2e 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/DateCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/DateCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -11,7 +11,7 @@ * architecture to help supporting a large range of sub managers / repositories. * *
    - * + *

    * Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -23,59 +23,36 @@ * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.NutsArgument; import net.thevpc.nuts.NutsCommandLine; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; -import java.time.*; +import java.time.LocalDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class DateCommand extends SimpleNshBuiltin { public DateCommand() { super("date", DEFAULT_SUPPORT); } - private static class Options { - //other date - String date; - boolean debug; - String file; - String iso; - boolean rfcMail; - String rfc8601; - String rfc3339; - String reference; - String setdate; - boolean utc; - } - @Override protected Object createOptions() { return new Options(); } - @Override - protected void initCommandLine(NutsCommandLine commandLine) { - for (String s : new String[]{ - "-Id","-Idate", - "-Ih","-Ihours", - "-Im","-Iminutes", - "-Is","-Iseconds", - "-Ins" - }) { - commandLine.registerSpecialSimpleOption(s); - } - } - @Override protected boolean configureFirst(NutsCommandLine cmdLine, SimpleNshCommandContext context) { Options options = context.getOptions(); @@ -83,89 +60,88 @@ protected boolean configureFirst(NutsCommandLine cmdLine, SimpleNshCommandContex switch (a.getKey().getString()) { case "-d": case "--date": { - if(context.getShell().getOptions().isNsh()){ + if (context.getShell().getOptions().isNsh()) { a = cmdLine.nextString(); - if(a.isEnabled()){ - options.date=a.getValue().getString(); + if (a.isEnabled()) { + options.date = a.getValue().getString(); } - }else { + } else { a = cmdLine.next(); - options.date=a.getValue().getString(); + options.date = a.getValue().getString(); } return true; } case "-f": case "--file": { - if(context.getShell().getOptions().isNsh()){ + if (context.getShell().getOptions().isNsh()) { a = cmdLine.nextString(); - if(a.isEnabled()){ - options.file=a.getValue().getString(); + if (a.isEnabled()) { + options.file = a.getValue().getString(); } - }else { + } else { a = cmdLine.next(); - options.file=a.getValue().getString(); + options.file = a.getValue().getString(); } return true; } case "--rfc-3339": { - if(context.getShell().getOptions().isNsh()){ + if (context.getShell().getOptions().isNsh()) { a = cmdLine.next(); - if(a.isEnabled()){ + if (a.isEnabled()) { String s = a.getValue().getString(); - if(s==null){ - s=""; + if (s == null) { + s = ""; } - options.rfc3339=s; + options.rfc3339 = s; } - }else { + } else { a = cmdLine.next(); String s = a.getValue().getString(); - if(s==null){ - s=""; + if (s == null) { + s = ""; } - options.rfc3339=s; + options.rfc3339 = s; } return true; } case "--iso-8601": { - if(context.getShell().getOptions().isNsh()){ + if (context.getShell().getOptions().isNsh()) { a = cmdLine.next(); - if(a.isEnabled()){ + if (a.isEnabled()) { String s = a.getValue().getString(); - if(s==null){ - s=""; + if (s == null) { + s = ""; } - options.rfc8601=s; + options.rfc8601 = s; } - }else { + } else { a = cmdLine.next(); String s = a.getValue().getString(); - if(s==null){ - s=""; + if (s == null) { + s = ""; } - options.rfc8601=s; + options.rfc8601 = s; } return true; } case "-s": - case "--set": - { - if(context.getShell().getOptions().isNsh()){ + case "--set": { + if (context.getShell().getOptions().isNsh()) { a = cmdLine.next(); - if(a.isEnabled()){ + if (a.isEnabled()) { String s = a.getValue().getString(); - if(s==null){ - s=""; + if (s == null) { + s = ""; } - options.setdate=s; + options.setdate = s; } - }else { + } else { a = cmdLine.next(); String s = a.getValue().getString(); - if(s==null){ - s=""; + if (s == null) { + s = ""; } - options.setdate=s; + options.setdate = s; } return true; } @@ -177,56 +153,54 @@ protected boolean configureFirst(NutsCommandLine cmdLine, SimpleNshCommandContex case "-Iminutes": case "-Is": case "-Iseconds": - case "-Ins": - { - if(context.getShell().getOptions().isNsh()){ + case "-Ins": { + if (context.getShell().getOptions().isNsh()) { a = cmdLine.next(); - if(a.isEnabled()){ - options.rfc8601=a.getString().substring(2); + if (a.isEnabled()) { + options.rfc8601 = a.getString().substring(2); } - }else { + } else { a = cmdLine.next(); - options.rfc8601=a.getString().substring(2); + options.rfc8601 = a.getString().substring(2); } return true; } case "--debug": { - if(context.getShell().getOptions().isNsh()){ + if (context.getShell().getOptions().isNsh()) { a = cmdLine.nextBoolean(); - if(a.isEnabled()){ - options.debug=a.getValue().getBoolean(); + if (a.isEnabled()) { + options.debug = a.getValue().getBoolean(); } - }else { + } else { a = cmdLine.next(); - options.debug=true; + options.debug = true; } return true; } case "-u": case "--utc": - case "--universal": - { - if(context.getShell().getOptions().isNsh()){ + case "--universal": { + if (context.getShell().getOptions().isNsh()) { a = cmdLine.nextBoolean(); - if(a.isEnabled()){ - options.utc=a.getValue().getBoolean(); + if (a.isEnabled()) { + options.utc = a.getValue().getBoolean(); } - }else { + } else { a = cmdLine.next(); - options.utc=true; + options.utc = true; } return true; } case "-R": - case "--rfc-email":{ - if(context.getShell().getOptions().isNsh()){ + case "--rfc-email": { + if (context.getShell().getOptions().isNsh()) { a = cmdLine.nextBoolean(); - if(a.isEnabled()){ - options.rfcMail=a.getValue().getBoolean(); + if (a.isEnabled()) { + options.rfcMail = a.getValue().getBoolean(); } - }else { + } else { a = cmdLine.next(); - options.rfcMail=true; + options.rfcMail = true; } return true; } @@ -239,69 +213,96 @@ protected void execBuiltin(NutsCommandLine cmdLine, SimpleNshCommandContext cont Options options = context.getOptions(); ZonedDateTime dateTimeInMyZone = ZonedDateTime. of(LocalDateTime.now(), ZoneId.systemDefault()); - if(options.utc) { + if (options.utc) { dateTimeInMyZone = dateTimeInMyZone.withZoneSameInstant(ZoneOffset.UTC); } - if(options.iso!=null){ - switch (options.iso){ + if (options.iso != null) { + switch (options.iso) { case "": case "d": - case "date":{ + case "date": { context.getSession().out().printlnf(dateTimeInMyZone.toLocalDate().toString()); break; } case "m": - case "minutes":{ + case "minutes": { context.getSession().out().printlnf(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm").format(dateTimeInMyZone.toLocalDateTime())); break; } case "s": - case "seconds":{ + case "seconds": { context.getSession().out().printlnf(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss").format(dateTimeInMyZone.toLocalDateTime())); break; } - case "ns":{ + case "ns": { context.getSession().out().printlnf(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSSSSS").format(dateTimeInMyZone.toLocalDateTime())); break; } - default:{ + default: { //error?? context.getSession().out().printlnf(dateTimeInMyZone.toLocalDate().toString()); break; } } - }else if(options.rfc3339!=null){ - switch (options.rfc3339){ + } else if (options.rfc3339 != null) { + switch (options.rfc3339) { case "": case "d": - case "date":{ + case "date": { context.getSession().out().printlnf(dateTimeInMyZone.toLocalDate().toString()); break; } case "m": - case "minutes":{ + case "minutes": { context.getSession().out().printlnf(DateTimeFormatter.ofPattern("uuuu-MM-dd' 'HH:mmXXX").format(dateTimeInMyZone.toLocalDate())); break; } case "s": - case "seconds":{ + case "seconds": { context.getSession().out().printlnf(DateTimeFormatter.ofPattern("uuuu-MM-dd' 'HH:mm:ssXXX").format(dateTimeInMyZone.toLocalDateTime())); break; } - case "ns":{ + case "ns": { context.getSession().out().printlnf(DateTimeFormatter.ofPattern("uuuu-MM-dd' 'HH:mm:ss.SSSSSSSSSXXX").format(dateTimeInMyZone.toLocalDateTime())); break; } - default:{ + default: { //error?? context.getSession().out().printlnf(dateTimeInMyZone.toLocalDate().toString()); break; } } - }else if(options.rfcMail){ + } else if (options.rfcMail) { context.getSession().out().printlnf(DateTimeFormatter.ofPattern("EEE, d MMM yyyy HH:mm:ss Z").format(dateTimeInMyZone)); - }else{ + } else { context.getSession().out().printlnf(DateTimeFormatter.ofPattern("EEE MMM d hh:mm:ss a Z yyyy").format(dateTimeInMyZone)); } } + + @Override + protected void initCommandLine(NutsCommandLine commandLine) { + for (String s : new String[]{ + "-Id", "-Idate", + "-Ih", "-Ihours", + "-Im", "-Iminutes", + "-Is", "-Iseconds", + "-Ins" + }) { + commandLine.registerSpecialSimpleOption(s); + } + } + + private static class Options { + //other date + String date; + boolean debug; + String file; + String iso; + boolean rfcMail; + String rfc8601; + String rfc3339; + String reference; + String setdate; + boolean utc; + } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/DirNameCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/DirNameCommand.java index 7b8779515..c09587b52 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/DirNameCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/DirNameCommand.java @@ -26,18 +26,19 @@ */ package net.thevpc.nuts.toolbox.nsh.cmds; -import java.util.ArrayList; -import java.util.List; - import net.thevpc.nuts.NutsArgument; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; + +import java.util.ArrayList; +import java.util.List; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class DirNameCommand extends SimpleNshBuiltin { public DirNameCommand() { diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EchoCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EchoCommand.java index 73ffb2fca..d91d1a9db 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EchoCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EchoCommand.java @@ -25,16 +25,18 @@ */ package net.thevpc.nuts.toolbox.nsh.cmds; +import net.thevpc.nuts.NutsCommandLine; import net.thevpc.nuts.NutsTextCode; +import net.thevpc.nuts.NutsTexts; import net.thevpc.nuts.NutsUtilStrings; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; -import net.thevpc.nuts.NutsCommandLine; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class EchoCommand extends SimpleNshBuiltin { public EchoCommand() { @@ -87,7 +89,7 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext if (options.highlighter == null || "text".equalsIgnoreCase(options.highlighter) || "plain".equalsIgnoreCase(options.highlighter)) { ns = options.message.toString(); } else { - NutsTextCode c = context.getSession().text().ofCode(options.highlighter, options.message.toString()); + NutsTextCode c = NutsTexts.of(context.getSession()).ofCode(options.highlighter, options.message.toString()); ns = c.highlight(context.getSession()); } if (options.newLine) { diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EnableCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EnableCommand.java index 4761adf13..86d4d51ab 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EnableCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EnableCommand.java @@ -26,22 +26,19 @@ */ package net.thevpc.nuts.toolbox.nsh.cmds; -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.NutsArgument; +import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellBuiltin; +import java.util.*; + /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class EnableCommand extends SimpleNshBuiltin { public EnableCommand() { diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EnvCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EnvCommand.java index 74c5b9c78..aba830793 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EnvCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/EnvCommand.java @@ -10,57 +10,38 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; - import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; +import java.util.*; + /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class EnvCommand extends SimpleNshBuiltin { public EnvCommand() { super("env", DEFAULT_SUPPORT); } - public static class Options { - - int readStatus = 0; - LinkedHashMap newEnv = new LinkedHashMap<>(); - List command = new ArrayList(); - Set unsetVers = new HashSet(); - boolean sort = true; - boolean ignoreEnvironment = false; - String dir = null; - NutsExecutionType executionType = null; - NutsRunAs runAs = null; - } - @Override protected Object createOptions() { return new Options(); @@ -90,27 +71,27 @@ protected boolean configureFirst(NutsCommandLine commandLine, SimpleNshCommandCo options.executionType = (NutsExecutionType.EMBEDDED); return true; } - case "--system":{ + case "--system": { commandLine.skip(); options.executionType = (NutsExecutionType.SYSTEM); return true; } - case "--current-user":{ + case "--current-user": { commandLine.skip(); options.runAs = NutsRunAs.currentUser(); return true; } - case "--as-root":{ + case "--as-root": { commandLine.skip(); options.runAs = NutsRunAs.root(); return true; } - case "--sudo":{ + case "--sudo": { commandLine.skip(); options.runAs = NutsRunAs.sudo(); return true; } - case "--as-user":{ + case "--as-user": { a = commandLine.nextString(); options.runAs = NutsRunAs.user(a.getValue().getString()); return true; @@ -201,4 +182,17 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } } + public static class Options { + + int readStatus = 0; + LinkedHashMap newEnv = new LinkedHashMap<>(); + List command = new ArrayList(); + Set unsetVers = new HashSet(); + boolean sort = true; + boolean ignoreEnvironment = false; + String dir = null; + NutsExecutionType executionType = null; + NutsRunAs runAs = null; + } + } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ExitCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ExitCommand.java index 305d635fa..e2381fbdb 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ExitCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ExitCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -11,43 +11,39 @@ * architecture to help supporting a large range of sub managers / repositories. * *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.NutsArgument; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.NutsCommandLine; import net.thevpc.nuts.NutsVal; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellQuitException; -import net.thevpc.nuts.NutsCommandLine; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class ExitCommand extends SimpleNshBuiltin { public ExitCommand() { super("exit", DEFAULT_SUPPORT); } - private static class Options { - - int code; - } - @Override protected Object createOptions() { return new Options(); @@ -75,4 +71,9 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext throw new JShellQuitException(options.code); } + private static class Options { + + int code; + } + } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/FalseCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/FalseCommand.java index 59bdb1dc0..66de4f945 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/FalseCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/FalseCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -11,31 +11,32 @@ * architecture to help supporting a large range of sub managers / repositories. * *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; +import net.thevpc.nuts.NutsCommandLine; import net.thevpc.nuts.NutsExecutionException; import net.thevpc.nuts.NutsMessage; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; -import net.thevpc.nuts.NutsCommandLine; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class FalseCommand extends SimpleNshBuiltin { public FalseCommand() { diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/GrepCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/GrepCommand.java index 9fa45bd6a..080f1c891 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/GrepCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/GrepCommand.java @@ -36,6 +36,7 @@ import java.util.stream.Collectors; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellExecutionContext; +import net.thevpc.nuts.toolbox.nsh.util.ColumnRuler; import net.thevpc.nuts.toolbox.nsh.util.FileInfo; /** @@ -116,6 +117,8 @@ public int execImpl(String[] args, JShellExecutionContext context) { options.ignoreCase = true; } else if ((a = commandLine.next("-H", "--highlighter")) != null) { options.highlighter = NutsUtilStrings.trim(a.getValue().getString()); + } else if ((a = commandLine.next("-S", "--selection-style")) != null) { + options.selectionStyle = NutsUtilStrings.trimToNull(a.getValue().getString()); } else if (commandLine.next("--version") != null) { out.printf("%s\n", "1.0"); return 0; @@ -155,20 +158,20 @@ public int execImpl(String[] args, JShellExecutionContext context) { //text mode boolean prefixFileName = files.size() > 1; int x = 0; - List results = new ArrayList<>(); + List results = new ArrayList<>(); for (FileInfo f : files) { x = grepFile(f, p, options, context, prefixFileName, results); } switch (context.getSession().getOutputFormat()) { case PLAIN: { - for (ResultItem result : results) { + ColumnRuler ruler=new ColumnRuler(); + for (GrepResultItem result : results) { if (options.n) { if (result.path != null && prefixFileName) { - out.print(result.path); + out.printf(result.path); out.print(":"); } - out.print(result.number); - out.print(":"); + out.print(ruler.nextNum(result.number, context.getSession())); } out.println(result.line); } @@ -188,16 +191,17 @@ public int execImpl(String[] args, JShellExecutionContext context) { return x; } - protected int grepFile(FileInfo f, Pattern p, Options options, JShellExecutionContext context, boolean prefixFileName, List results) { + protected int grepFile(FileInfo f, Pattern p, Options options, JShellExecutionContext context, boolean prefixFileName, List results) { Reader reader = null; boolean closeReader = false; + NutsSession session = context.getSession(); try { try { if (f == null) { closeReader = false; reader = new InputStreamReader(context.in()); - processByLine(reader, options, p, f, results, context.getSession()); + processByLine(reader, options, p, f, results, session); } else if (f.getFile().isDirectory()) { NutsPath[] files = f.getFile().getChildren(); if (files != null) { @@ -210,10 +214,13 @@ protected int grepFile(FileInfo f, Pattern p, Options options, JShellExecutionCo closeReader = true; reader = new InputStreamReader(f.getFile().getInputStream()); if (f.getHighlighter() == null) { - processByLine(reader, options, p, f, results, context.getSession()); + processByLine(reader, options, p, f, results, session); } else { - String text = new String(context.getSession().io().copy().from(f.getFile()).getByteArrayResult()); - processByText(text, options, p, f, results, context.getSession()); + String text = new String(NutsCp.of(session).from(f.getFile()).getByteArrayResult()); + if(NutsBlankable.isBlank(f.getHighlighter())){ + f.setHighlighter(f.getFile().getContentType()); + } + processByText(text, options, p, f, results, session); } } } finally { @@ -222,7 +229,7 @@ protected int grepFile(FileInfo f, Pattern p, Options options, JShellExecutionCo } } } catch (IOException ex) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("%s", ex), ex, 100); + throw new NutsExecutionException(session, NutsMessage.cstyle("%s", ex), ex, 100); } return 0; } @@ -248,26 +255,54 @@ private NutsTextBuilder readLine(NutsTextBuilder flattened, NutsSession session) } r.add(t); } - return session.text().builder().appendAll(r); + return NutsTexts.of(session).builder().appendAll(r); } - private void processByLine(Reader reader, Options options, Pattern p, FileInfo f, List results, NutsSession session) throws IOException { + private void processByLine(Reader reader, Options options, Pattern p, FileInfo f, List results, NutsSession session) throws IOException { try (BufferedReader r = new BufferedReader(reader)) { String line = null; long nn = 1; while ((line = r.readLine()) != null) { - boolean matches = p.matcher(line).matches(); - if (matches != options.invertMatch) { - NutsText cl = session.text().ofCode(f.getHighlighter(), line).highlight(session); - results.add(new ResultItem(f.getFile(), nn, cl)); + GrepResultItem rr = createResult(nn, line, null, options, p, f, session); + if (rr!=null) { + results.add(rr); } nn++; } } } - private void processByText(String text, Options options, Pattern p, FileInfo f, List results, NutsSession session) throws IOException { - NutsTextBuilder flattened = session.text().ofCode(f.getHighlighter(), text).highlight(session) + private GrepResultItem createResult(long nn, String line, NutsTextBuilder coloredLine, Options options, Pattern p, FileInfo f, NutsSession session) { + if (coloredLine == null) { + coloredLine = NutsTexts.of(session).ofCode(f.getHighlighter(), line).highlight(session).builder(); + } + Matcher matcher = p.matcher(line); + boolean anyMatch = false; + while (matcher.find()) { + anyMatch = true; + int pos = matcher.start(); + int end = matcher.end(); + coloredLine.replace(pos, end, + NutsTexts.of(session).ofStyled( + coloredLine.substring(pos, end) + , selectionStyle(options) + ) + ); + } + if (anyMatch != options.invertMatch) { + return new GrepResultItem(f.getFile(), nn, coloredLine.build(),true); + } + if(options.all){ + return new GrepResultItem(f.getFile(), nn, coloredLine.build(),false); + } + if(options.all){ + + } + return null; + } + + private void processByText(String text, Options options, Pattern p, FileInfo f, List results, NutsSession session) throws IOException { + NutsTextBuilder flattened = NutsTexts.of(session).ofCode(f.getHighlighter(), text).highlight(session) .builder() .flatten(); try (BufferedReader r = new BufferedReader(new InputStreamReader(f.getFile().getInputStream()))) { @@ -275,46 +310,50 @@ private void processByText(String text, Options options, Pattern p, FileInfo f, long nn = 1; while ((line = r.readLine()) != null) { NutsTextBuilder coloredLine = readLine(flattened, session); - if (coloredLine == null) { - coloredLine = session.text().ofCode(f.getHighlighter(), line).highlight(session).builder(); - } - Matcher matcher = p.matcher(line); - boolean anyMatch = false; - while (matcher.find()) { - anyMatch = true; - int pos = matcher.start(); - int end = matcher.end(); - NutsText toh = coloredLine.substring(pos, end); - coloredLine.replace(pos, end, session.text().ofStyled(toh, NutsTextStyle.underlined())); - } - if (anyMatch != options.invertMatch) { - results.add(new ResultItem(f.getFile(), nn, coloredLine.build())); + GrepResultItem rr = createResult(nn, line, coloredLine, options, p, f, session); + if (rr != null) { + results.add(rr); } nn++; } } } + public NutsTextStyles selectionStyle(Options options) { + String s = options.selectionStyle; + NutsTextStyles def = NutsTextStyles.of(NutsTextStyle.secondary(2)); + if (NutsBlankable.isBlank(s)) { + return def; + } + return NutsTextStyles.parseLenient(s, def, def); + } + private static class Options { -// boolean regexp = false; + // boolean regexp = false; boolean invertMatch = false; boolean word = false; boolean lineRegexp = false; boolean ignoreCase = false; String highlighter; + String selectionStyle; boolean n = false; + boolean all = false; + int windowBefore = 0; + int windowAfter = 0; } - private static class ResultItem { + private static class GrepResultItem { NutsPath path; long number; NutsText line; + Boolean match; - public ResultItem(NutsPath path, long number, NutsText line) { + public GrepResultItem(NutsPath path, long number, NutsText line,Boolean match) { this.path = path; this.number = number; this.line = line; + this.match = match; } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HeadCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HeadCommand.java index 322578bed..19fc09d09 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HeadCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HeadCommand.java @@ -26,7 +26,8 @@ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import java.io.BufferedReader; @@ -39,7 +40,7 @@ /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class HeadCommand extends SimpleNshBuiltin { public HeadCommand() { super("head", DEFAULT_SUPPORT); @@ -80,14 +81,15 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext private void head(String file, int max, SimpleNshCommandContext context) { BufferedReader r = null; + NutsSession session = context.getSession(); try { try { - r = new BufferedReader(new InputStreamReader(context.getSession().io().path(file) + r = new BufferedReader(new InputStreamReader(NutsPath.of(file, session) .getInputStream())); String line = null; int count = 0; while (count < max && (line = r.readLine()) != null) { - context.getSession().out().println(line); + session.out().println(line); count++; } } finally { @@ -96,7 +98,7 @@ private void head(String file, int max, SimpleNshCommandContext context) { } } } catch (IOException ex) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("%s",ex), ex, 100); + throw new NutsExecutionException(session, NutsMessage.cstyle("%s", ex), ex, 100); } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HelpCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HelpCommand.java index 25801f88d..f5d3be454 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HelpCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HelpCommand.java @@ -66,7 +66,7 @@ public int execImpl(String[] args, JShellExecutionContext context) { context.configureLast(commandLine); } } - final NutsTextManager text = context.getSession().text(); + final NutsTexts text = NutsTexts.of(context.getSession()); Function ss = code ? new Function() { @Override public String apply(String t) { @@ -80,7 +80,7 @@ public String apply(String t) { ); String helpText = (n==null?"no help found":n.toString()); context.out().println(ss.apply(helpText)); - context.out().println(context.getSession().text().ofStyled("AVAILABLE COMMANDS ARE:", NutsTextStyle.primary1())); + context.out().println(NutsTexts.of(context.getSession()).ofStyled("AVAILABLE COMMANDS ARE:", NutsTextStyle.primary1())); JShellBuiltin[] commands = context.getShellContext().builtins().getAll(); Arrays.sort(commands, new Comparator() { @Override diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HistoryCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HistoryCommand.java index e8f9e6615..4fc160379 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HistoryCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/HistoryCommand.java @@ -10,52 +10,37 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; +import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; +import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellHistory; + import java.io.IOException; import java.util.LinkedHashMap; import java.util.List; -import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellHistory; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; - /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class HistoryCommand extends SimpleNshBuiltin { - private static enum Action { - CLEAR, - DELETE, - REMOVE_DUPLICATES, - WRITE, - READ, - PRINT - } - - private static class Options { - - public String sval; - int ival = -1; - Action action = Action.PRINT; - } - public HistoryCommand() { super("history", DEFAULT_SUPPORT); } @@ -114,6 +99,7 @@ protected boolean configureFirst(NutsCommandLine commandLine, SimpleNshCommandCo protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext context) { Options options = context.getOptions(); JShellHistory shistory = context.getShell().getHistory(); + NutsSession session = context.getSession(); switch (options.action) { case PRINT: { List history = shistory.getElements(options.ival <= 0 ? 1000 : options.ival); @@ -123,7 +109,7 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext String historyElement = history.get(i); result.put(String.valueOf(offset + i + 1), historyElement); } - context.getSession().out().printlnf(result); + session.out().printlnf(result); break; } case CLEAR: { @@ -144,10 +130,10 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext shistory.save(); } else { - shistory.save(context.getSession().io().path(options.sval).builder().withWorkspaceBaseDir().build()); + shistory.save(NutsPath.of(options.sval, session).builder().withWorkspaceBaseDir().build()); } } catch (IOException ex) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("%s",ex), ex, 100); + throw new NutsExecutionException(session, NutsMessage.cstyle("%s", ex), ex, 100); } return; } @@ -157,16 +143,32 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext shistory.clear(); shistory.load(); } else { - shistory.load(context.getSession().io().path(options.sval).builder().withWorkspaceBaseDir().build()); + shistory.load(NutsPath.of(options.sval, session).builder().withWorkspaceBaseDir().build()); } } catch (IOException ex) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("%s",ex), ex, 100); + throw new NutsExecutionException(session, NutsMessage.cstyle("%s", ex), ex, 100); } return; } default: { - throw new NutsUnsupportedArgumentException(context.getSession(), NutsMessage.cstyle("unsupported %s",String.valueOf(options.action))); + throw new NutsUnsupportedArgumentException(session, NutsMessage.cstyle("unsupported %s", String.valueOf(options.action))); } } } + + private enum Action { + CLEAR, + DELETE, + REMOVE_DUPLICATES, + WRITE, + READ, + PRINT + } + + private static class Options { + + public String sval; + int ival = -1; + Action action = Action.PRINT; + } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/JpsCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/JpsCommand.java index 5164730b1..613ee9720 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/JpsCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/JpsCommand.java @@ -10,58 +10,71 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; +import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; + import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; -import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; - /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class JpsCommand extends SimpleNshBuiltin { public JpsCommand() { super("jps", DEFAULT_SUPPORT); } - private static class JpsRow { - - String id; - String name; - String fullName; - String vmOptions; - String arguments; + public static String resolveJpsCommand(NutsSession session) { + return resolveJavaToolCommand(session, null, "jps"); } - private static class Options { - - boolean m = false; - boolean v = false; - boolean V = false; - boolean q = false; - boolean l = false; - String host; + public static String resolveJavaToolCommand(NutsSession session, String javaHome, String javaCommand) { + String exe = session.env().getOsFamily().equals(NutsOsFamily.WINDOWS) ? (javaCommand + ".exe") : javaCommand; + if (javaHome == null) { + javaHome = System.getProperty("java.home"); + } + Path jh = Paths.get(javaHome); + Path p = jh.resolve("bin").resolve(exe); + if (Files.exists(p)) { + return p.toString(); + } + p = jh.resolve(exe); + if (Files.exists(p)) { + return p.toString(); + } + if (jh.getFileName().toString().equals("jre")) { + p = jh.getParent().resolve("bin").resolve(exe); + if (Files.exists(p)) { + return p.toString(); + } + p = jh.getParent().resolve(exe); + if (Files.exists(p)) { + return p.toString(); + } + } + return exe; } @Override @@ -139,34 +152,22 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext context.getSession().out().printlnf(results); } - public static String resolveJpsCommand(NutsSession session) { - return resolveJavaToolCommand(session,null, "jps"); + private static class JpsRow { + + String id; + String name; + String fullName; + String vmOptions; + String arguments; } - public static String resolveJavaToolCommand(NutsSession session,String javaHome, String javaCommand) { - String exe = session.env().getOsFamily().equals(NutsOsFamily.WINDOWS) ? (javaCommand + ".exe") : javaCommand; - if (javaHome == null) { - javaHome = System.getProperty("java.home"); - } - Path jh = Paths.get(javaHome); - Path p = jh.resolve("bin").resolve(exe); - if (Files.exists(p)) { - return p.toString(); - } - p = jh.resolve(exe); - if (Files.exists(p)) { - return p.toString(); - } - if (jh.getFileName().toString().equals("jre")) { - p = jh.getParent().resolve("bin").resolve(exe); - if (Files.exists(p)) { - return p.toString(); - } - p = jh.getParent().resolve(exe); - if (Files.exists(p)) { - return p.toString(); - } - } - return exe; + private static class Options { + + boolean m = false; + boolean v = false; + boolean V = false; + boolean q = false; + boolean l = false; + String host; } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/JsonCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/JsonCommand.java index 686757010..74ee66753 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/JsonCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/JsonCommand.java @@ -26,7 +26,8 @@ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellContext; import org.w3c.dom.Document; @@ -47,7 +48,7 @@ /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class JsonCommand extends SimpleNshBuiltin { public JsonCommand() { @@ -85,12 +86,13 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext // commandLine.required(); // } + NutsSession session = context.getSession(); if (options.queries.isEmpty()) { NutsElement inputDocument = readJsonConvertElement(options.input, context.getRootContext()); - if (context.getSession().getOutputFormat() == NutsContentType.PLAIN) { - context.getSession().out().printlnf(context.getSession().elem().setContentType(NutsContentType.JSON).setValue(inputDocument).format()); + if (session.getOutputFormat() == NutsContentType.PLAIN) { + session.out().printlnf(NutsElements.of(session).json().setValue(inputDocument).format()); } else { - context.getSession().out().printlnf(inputDocument); + session.out().printlnf(inputDocument); } } else { switch (options.queryType) { @@ -102,7 +104,7 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext try { resultDocument = documentFactory.newDocumentBuilder().newDocument(); } catch (ParserConfigurationException ex) { - throw new NutsExecutionException(context.getSession(), NutsMessage.plain("failed to create xml document"), ex, 1); + throw new NutsExecutionException(session, NutsMessage.plain("failed to create xml document"), ex, 1); } Element resultElement = resultDocument.createElement("result"); resultDocument.appendChild(resultElement); @@ -115,13 +117,13 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext resultElement.appendChild(o); } } catch (XPathExpressionException ex) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("%s", ex), ex, 103); + throw new NutsExecutionException(session, NutsMessage.cstyle("%s", ex), ex, 103); } } - if (context.getSession().getOutputFormat(null) == null) { - context.getSession().out().printlnf(context.getSession().elem().setContentType(NutsContentType.JSON).setValue(resultDocument).format()); + if (session.getOutputFormat(null) == null) { + session.out().printlnf(NutsElements.of(session).json().setValue(resultDocument).format()); } else { - context.getSession().out().printlnf(resultDocument); + session.out().printlnf(resultDocument); } break; } @@ -129,17 +131,16 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext NutsElement inputDocument = readJsonConvertElement(options.input, context.getRootContext()); List all = new ArrayList<>(); for (String query : options.queries) { - all.addAll(context.getSession().elem() - .setSession(context.getSession()) + all.addAll(NutsElements.of(session) .compilePath(query) .filter(inputDocument) ); } Object result = all.size() == 1 ? all.get(0) : all; - if (context.getSession().getOutputFormat(null) == null) { - context.getSession().out().printlnf(context.getSession().elem().setContentType(NutsContentType.JSON).setValue(result).format()); + if (session.getOutputFormat(null) == null) { + session.out().printlnf(NutsElements.of(session).json().setValue(result).format()); } else { - context.getSession().out().printlnf(result); + session.out().printlnf(result); } break; } @@ -157,14 +158,15 @@ private NutsElement readJsonConvertElement(String path, JShellContext context) { } private T readJsonConvertAny(String path, Class cls, JShellContext context) { - NutsElementFormat njson = context.getSession().elem().setContentType(NutsContentType.JSON); + NutsSession session = context.getSession(); + NutsElements njson = NutsElements.of(session).json(); T inputDocument = null; if (path != null) { File file = new File(context.getAbsolutePath(path)); if (file.isFile()) { inputDocument = njson.parse(file, cls); } else { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("invalid path %s", path), 1); + throw new NutsExecutionException(session, NutsMessage.cstyle("invalid path %s", path), 1); } } else { StringBuilder sb = new StringBuilder(); @@ -174,7 +176,7 @@ private T readJsonConvertAny(String path, Class cls, JShellContext contex try { line = reader.readLine(); } catch (IOException ex) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("broken Input"), 2); + throw new NutsExecutionException(session, NutsMessage.cstyle("broken Input"), 2); } if (line == null) { inputDocument = njson.parse(new StringReader(sb.toString()), cls); diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LoginCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LoginCommand.java index c22fb6abc..89f6e8166 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LoginCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LoginCommand.java @@ -10,7 +10,7 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] Licensed under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. * You may obtain a copy of the License at @@ -24,25 +24,20 @@ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class LoginCommand extends SimpleNshBuiltin { public LoginCommand() { super("login", DEFAULT_SUPPORT); } - private static class Options { - - String login; - char[] password; - } - @Override protected Object createOptions() { return new Options(); @@ -53,11 +48,12 @@ protected boolean configureFirst(NutsCommandLine commandLine, SimpleNshCommandCo Options options = context.getOptions(); NutsArgument a = commandLine.peek(); if (!a.isOption()) { + NutsSession session = context.getSession(); if (options.login == null) { - options.login = commandLine.next(context.getSession().commandLine().createName("username")).getString(); + options.login = commandLine.next(NutsArgumentName.of("username", session)).getString(); return true; } else if (options.password == null) { - options.password = commandLine.next(context.getSession().commandLine().createName("password")).getString().toCharArray(); + options.password = commandLine.next(NutsArgumentName.of("password", session)).getString().toCharArray(); return true; } } @@ -78,4 +74,10 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext context.getSession().security().login(options.login, options.password); } + private static class Options { + + String login; + char[] password; + } + } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LogoutCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LogoutCommand.java index abe39e9e6..87b5ec230 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LogoutCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LogoutCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -11,7 +11,7 @@ * architecture to help supporting a large range of sub managers / repositories. * *
    - * + *

    * Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -23,17 +23,18 @@ * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.NutsCommandLine; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class LogoutCommand extends SimpleNshBuiltin { public LogoutCommand() { diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LsCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LsCommand.java index d78dc3bc3..aa060a812 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LsCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/LsCommand.java @@ -25,20 +25,21 @@ */ package net.thevpc.nuts.toolbox.nsh.cmds; +import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; +import net.thevpc.nuts.toolbox.nsh.bundles.BytesSizeFormat; + import java.text.SimpleDateFormat; import java.time.Instant; import java.util.*; import java.util.stream.Collectors; -import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; -import net.thevpc.nuts.toolbox.nsh.bundles.BytesSizeFormat; - /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class LsCommand extends SimpleNshBuiltin { private static final FileSorter FILE_SORTER = new FileSorter(); @@ -73,7 +74,8 @@ protected boolean configureFirst(NutsCommandLine commandLine, SimpleNshCommandCo options.h = a.getValue().getBoolean(); return true; } else if (commandLine.peek().isNonOption()) { - String path = commandLine.next(context.getSession().commandLine().createName("file")).getString(); + NutsSession session = context.getSession(); + String path = commandLine.next(NutsArgumentName.of("file", session)).getString(); options.paths.add(path); options.paths.addAll(Arrays.asList(commandLine.toStringArray())); commandLine.skip(); @@ -92,8 +94,9 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext if (options.paths.isEmpty()) { options.paths.add(context.getRootContext().getAbsolutePath(".")); } + NutsSession session = context.getSession(); for (String path : options.paths) { - NutsPath file = NutsPath.of(path, context.getSession()).toAbsolute(NutsPath.of(context.getRootContext().getCwd(), context.getSession())); + NutsPath file = NutsPath.of(path, session).toAbsolute(NutsPath.of(context.getRootContext().getCwd(), session)); if (!file.exists()) { exitCode = 1; if (errors == null) { @@ -123,8 +126,8 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } } if (success != null) { - NutsPrintStream out = context.getSession().out(); - switch (context.getSession().getOutputFormat()) { + NutsPrintStream out = session.out(); + switch (session.getOutputFormat()) { case XML: case JSON: case YAML: @@ -141,7 +144,7 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext out.printlnf(success.result.stream() .flatMap(x -> x.children.stream().map(y -> { - Map m = (Map) context.getSession().elem().destruct(y); + Map m = (Map) NutsElements.of(session).destruct(y); m.put("group", x.name); return m; })).collect(Collectors.toList())); @@ -155,10 +158,10 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext out.printf("%s:\n", resultGroup.name); } for (ResultItem resultItem : resultGroup.children) { - printPlain(resultItem, options, out, context.getSession()); + printPlain(resultItem, options, out, session); } } else { - printPlain(resultGroup.file, options, out, context.getSession()); + printPlain(resultGroup.file, options, out, session); } } break; @@ -169,14 +172,14 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext // if plain // ResultError s = context.getResult(); // for (Map.Entry e : s.result.entrySet()) { -// NutsTextManager text = session.text(); +// NutsTexts text = NutsTexts.of(session); // out.printf("%s%n", // text.builder().append(e.getKey(),NutsTextStyle.primary5()) // .append(" : ") // .append(e.getValue(),NutsTextStyle.error()) // ); // } - throwExecutionException(errors.result, exitCode, context.getSession()); + throwExecutionException(errors.result, exitCode, session); } } @@ -200,8 +203,8 @@ private void printPlain(ResultItem item, Options options, NutsPrintStream out, N out.printf("%s", SIMPLE_DATE_FORMAT.format(item.modified)); out.print(" "); } - String name = session.io().path(item.path).getName(); - NutsTextManager text = session.text(); + String name = NutsPath.of(item.path, session).getName(); + NutsTexts text = NutsTexts.of(session); if (item.hidden) { out.println(text.ofStyled(name, NutsTextStyle.pale())); } else if (item.type == 'd') { diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/MkdirCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/MkdirCommand.java index 0efbe471f..2f1031e01 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/MkdirCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/MkdirCommand.java @@ -10,7 +10,7 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -22,38 +22,32 @@ * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; -import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.NutsArgument; +import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.NutsPath; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.util.ShellHelper; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; - /** * Created by vpc on 1/7/17. ssh copy credits to Chanaka Lakmal from * https://medium.com/ldclakmal/scp-with-java-b7b7dbcdbc85 */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class MkdirCommand extends SimpleNshBuiltin { public MkdirCommand() { super("mkdir", DEFAULT_SUPPORT); } - public static class Options { - - List files = new ArrayList<>(); - List xfiles = new ArrayList<>(); - - boolean p; - } - @Override protected Object createOptions() { return new Options(); @@ -77,7 +71,7 @@ protected boolean configureFirst(NutsCommandLine commandLine, SimpleNshCommandCo @Override protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext context) { Options options = context.getOptions(); - options.xfiles = ShellHelper.xfilesOf(options.files, context.getCwd(),context.getSession()); + options.xfiles = ShellHelper.xfilesOf(options.files, context.getCwd(), context.getSession()); if (options.xfiles.size() < 1) { commandLine.required(); } @@ -89,4 +83,12 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext v.mkdir(options.p); } } + + public static class Options { + + List files = new ArrayList<>(); + List xfiles = new ArrayList<>(); + + boolean p; + } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/PropsCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/PropsCommand.java index b8ee6fc62..865e97396 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/PropsCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/PropsCommand.java @@ -48,7 +48,7 @@ public int execImpl(String[] args, JShellExecutionContext context) { NutsCommandLine commandLine = cmdLine(args, context); Options o = new Options(); NutsArgument a; - NutsCommandLineManager commandLineFormat = context.getSession().commandLine(); + NutsSession session = context.getSession(); commandLine.setCommandName(getName()); do { if (commandLine.next("get") != null) { @@ -58,7 +58,7 @@ public int execImpl(String[] args, JShellExecutionContext context) { if (commandLine.next("--xml") != null) { o.sourceFormat = Format.XML; o.sourceType = SourceType.FILE; - o.sourceFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.sourceFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else if (commandLine.next("--system") != null) { o.sourceFormat = Format.PROPS; @@ -68,12 +68,12 @@ public int execImpl(String[] args, JShellExecutionContext context) { } else if (commandLine.next("--props") != null) { o.sourceFormat = Format.PROPS; o.sourceType = SourceType.FILE; - o.sourceFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.sourceFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else if (commandLine.next("--file") != null) { o.sourceFormat = Format.AUTO; o.sourceType = SourceType.FILE; - o.sourceFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.sourceFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else { commandLine.setCommandName(getName()).unexpectedArgument(); } @@ -90,16 +90,16 @@ public int execImpl(String[] args, JShellExecutionContext context) { } else if (commandLine.next("--to-props-file") != null) { o.targetFormat = Format.PROPS; o.targetType = TargetType.FILE; - o.targetFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.targetFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else if (commandLine.next("--to-xml-file") != null) { o.targetFormat = Format.XML; o.targetType = TargetType.FILE; - o.targetFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.targetFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else if (commandLine.next("--to-file") != null) { o.targetFormat = Format.AUTO; o.targetType = TargetType.FILE; - o.targetFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.targetFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else if (commandLine.next("--print-props") != null) { o.targetFormat = Format.PROPS; @@ -117,11 +117,11 @@ public int execImpl(String[] args, JShellExecutionContext context) { o.targetFile = null; } else if (commandLine.next("--sort") != null) { o.sort = true; - context.getSession().addOutputFormatOptions("--sort"); + session.addOutputFormatOptions("--sort"); } else if (commandLine.next("--xml") != null) { o.sourceFormat = Format.XML; o.sourceType = SourceType.FILE; - o.sourceFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.sourceFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else if (commandLine.next("--system") != null) { o.sourceFormat = Format.PROPS; @@ -131,11 +131,11 @@ public int execImpl(String[] args, JShellExecutionContext context) { } else if (commandLine.next("--props") != null) { o.sourceFormat = Format.PROPS; o.sourceType = SourceType.FILE; - o.sourceFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.sourceFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else if (commandLine.next("--file") != null) { o.sourceFormat = Format.AUTO; o.sourceType = SourceType.FILE; - o.sourceFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.sourceFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else { commandLine.setCommandName(getName()).unexpectedArgument(); } @@ -146,7 +146,7 @@ public int execImpl(String[] args, JShellExecutionContext context) { if (commandLine.next("--xml") != null) { o.sourceFormat = Format.XML; o.sourceType = SourceType.FILE; - o.sourceFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.sourceFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else if (commandLine.next("--system") != null) { o.sourceFormat = Format.PROPS; @@ -156,15 +156,15 @@ public int execImpl(String[] args, JShellExecutionContext context) { } else if (commandLine.next("--props") != null) { o.sourceFormat = Format.PROPS; o.sourceType = SourceType.FILE; - o.sourceFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.sourceFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else if (commandLine.next("--file") != null) { o.sourceFormat = Format.AUTO; o.sourceType = SourceType.FILE; - o.sourceFile = commandLine.required().nextNonOption(commandLineFormat.createName("file")).getString(); + o.sourceFile = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); } else if (commandLine.next("--sort") != null) { o.sort = true; - context.getSession().addOutputFormatOptions("--sort"); + session.addOutputFormatOptions("--sort"); } else { commandLine.setCommandName(getName()).unexpectedArgument(); } @@ -174,13 +174,13 @@ public int execImpl(String[] args, JShellExecutionContext context) { } } while (commandLine.hasNext()); if (o.sourceType != SourceType.FILE && o.sourceFile != null) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("props: Should not use file with --system flag"), 2); + throw new NutsExecutionException(session, NutsMessage.cstyle("props: Should not use file with --system flag"), 2); } if (o.sourceType == SourceType.FILE && o.sourceFile == null) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("props: Missing file"), 3); + throw new NutsExecutionException(session, NutsMessage.cstyle("props: Missing file"), 3); } if (o.action == null) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("props: Missing action"), 4); + throw new NutsExecutionException(session, NutsMessage.cstyle("props: Missing action"), 4); } switch (o.action) { case "get": { @@ -194,14 +194,14 @@ public int execImpl(String[] args, JShellExecutionContext context) { } return storeProperties(p, o, context); } catch (Exception ex) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("%s", ex), ex, 100); + throw new NutsExecutionException(session, NutsMessage.cstyle("%s", ex), ex, 100); } } case "list": { return action_list(context, o); } default: { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("props: Unsupported action %s", o.action), 2); + throw new NutsExecutionException(session, NutsMessage.cstyle("props: Unsupported action %s", o.action), 2); } } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/PwdCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/PwdCommand.java index 8eb579448..8788cc49f 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/PwdCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/PwdCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -10,39 +10,36 @@ * to share shell scripts and other 'things' . Its based on an extensible * architecture to help supporting a large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.NutsCommandLine; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class PwdCommand extends SimpleNshBuiltin { public PwdCommand() { super("pwd", DEFAULT_SUPPORT); } - private static class Options { - - } - @Override protected Object createOptions() { return new Options(); @@ -58,4 +55,8 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext //Options options=context.getOptions(); context.getSession().out().printlnf(context.getRootContext().getCwd()); } + + private static class Options { + + } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/RmCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/RmCommand.java index 61ce04e10..ac86d76c1 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/RmCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/RmCommand.java @@ -26,7 +26,8 @@ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.util.ShellHelper; @@ -34,10 +35,9 @@ import java.util.List; /** - * Created by vpc on 1/7/17. ssh copy credits to Chanaka Lakmal from - * https://medium.com/ldclakmal/scp-with-java-b7b7dbcdbc85 + * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class RmCommand extends SimpleNshBuiltin { public RmCommand() { diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SetCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SetCommand.java index 657aad9a0..4e25f74a0 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SetCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SetCommand.java @@ -10,46 +10,43 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; +import net.thevpc.nuts.NutsArgument; +import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; +import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellFunction; + import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import net.thevpc.nuts.NutsArgument; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; -import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellFunction; -import net.thevpc.nuts.NutsCommandLine; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class SetCommand extends SimpleNshBuiltin { public SetCommand() { super("set", DEFAULT_SUPPORT); } - private static class Options { - - LinkedHashMap vars = new LinkedHashMap<>(); - } - @Override protected Object createOptions() { return new Options(); @@ -86,4 +83,9 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } } } + + private static class Options { + + LinkedHashMap vars = new LinkedHashMap<>(); + } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ShowerrCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ShowerrCommand.java index cee39ceff..288b44ced 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ShowerrCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ShowerrCommand.java @@ -26,14 +26,15 @@ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellResult; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; +import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellResult; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class ShowerrCommand extends SimpleNshBuiltin { public ShowerrCommand() { @@ -50,11 +51,12 @@ protected boolean configureFirst(NutsCommandLine commandLine, SimpleNshCommandCo Options options = context.getOptions(); NutsArgument a = commandLine.peek(); if (!a.isOption()) { + NutsSession session = context.getSession(); if (options.login == null) { - options.login = commandLine.next(context.getSession().commandLine().createName("username")).getString(); + options.login = commandLine.next(NutsArgumentName.of("username", session)).getString(); return true; } else if (options.password == null) { - options.password = commandLine.next(context.getSession().commandLine().createName("password")).getString().toCharArray(); + options.password = commandLine.next(NutsArgumentName.of("password", session)).getString().toCharArray(); return true; } } @@ -69,22 +71,22 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext case PLAIN: { if (r.getCode() == 0) { out.println( - context.getSession().text().ofStyled( + NutsTexts.of(context.getSession()).ofStyled( "last command ended successfully with no errors.", NutsTextStyle.success() )); } else { out.println( - context.getSession().text() + NutsTexts.of(context.getSession()) .ofStyled("last command ended abnormally with the following error :", NutsTextStyle.error()) ); if (r.getMessage() != null) { - out.println(context.getSession().text() + out.println(NutsTexts.of(context.getSession()) .ofStyled(r.getMessage(), NutsTextStyle.error() )); } if (r.getStackTrace() != null) { context.err().println( - context.getSession().text() + NutsTexts.of(context.getSession()) .ofStyled(r.getStackTrace(), NutsTextStyle.error()) ); } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SourceCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SourceCommand.java index b3b2a109e..b9713cfd6 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SourceCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SourceCommand.java @@ -29,7 +29,8 @@ import net.thevpc.nuts.NutsCommandLine; import net.thevpc.nuts.NutsPath; import net.thevpc.nuts.NutsSession; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellContext; @@ -39,7 +40,7 @@ /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class SourceCommand extends SimpleNshBuiltin { public SourceCommand() { @@ -79,8 +80,8 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } } if (!NutsPath.of(file, session).isFile()) { - if (NutsPath.of(context.getRootContext().getCwd(),session).resolve(file).isFile()) { - file = NutsPath.of(context.getRootContext().getCwd(),session).resolve(file).toString(); + if (NutsPath.of(context.getRootContext().getCwd(), session).resolve(file).isFile()) { + file = NutsPath.of(context.getRootContext().getCwd(), session).resolve(file).toString(); } } if (NutsPath.of(file, session).isFile()) { @@ -96,7 +97,7 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext // c2.setArgs(context.getArgs()); JShellContext c2 = context.getExecutionContext().getShellContext(); for (NutsPath goodFile : goodFiles) { - JShellContext c=context.getShell().createInlineContext(c2,goodFile.toString(),context.getArgs()); + JShellContext c = context.getShell().createInlineContext(c2, goodFile.toString(), context.getArgs()); context.getShell().executeServiceFile(c, false); } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SshCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SshCommand.java index 0728fe7cc..abeca3f41 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SshCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/SshCommand.java @@ -103,7 +103,7 @@ public int execImpl(String[] args, JShellExecutionContext context) { List cmd = new ArrayList<>(); if (o.invokeNuts) { String workspace = null; - NutsCommandLine c = session.commandLine().create(o.cmd.subList(1, o.cmd.size()).toArray(new String[0])); + NutsCommandLine c = NutsCommandLine.of(o.cmd.subList(1, o.cmd.size()),session); NutsArgument arg = null; while (c.hasNext()) { if ((arg = c.next("--workspace")) != null) { diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TailCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TailCommand.java index 75978e3a2..c0895ca8c 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TailCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TailCommand.java @@ -80,9 +80,10 @@ public int execImpl(String[] args, JShellExecutionContext context) { private void tail(String file, int max, JShellExecutionContext context) { BufferedReader r = null; + NutsSession session = context.getSession(); try { try { - r = new BufferedReader(new InputStreamReader(context.getSession().io().path(file) + r = new BufferedReader(new InputStreamReader(NutsPath.of(file,session) .getInputStream())); String line = null; int count = 0; @@ -103,7 +104,7 @@ private void tail(String file, int max, JShellExecutionContext context) { } } } catch (IOException ex) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("%s",ex), ex, 100); + throw new NutsExecutionException(session, NutsMessage.cstyle("%s",ex), ex, 100); } } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TestCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TestCommand.java index 95d565672..5f53d0664 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TestCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TestCommand.java @@ -35,6 +35,7 @@ import java.nio.file.attribute.UserPrincipal; import java.util.Stack; import net.thevpc.nuts.NutsArgument; +import net.thevpc.nuts.NutsSession; import net.thevpc.nuts.toolbox.nsh.AbstractNshBuiltin; import net.thevpc.nuts.NutsCommandLine; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellExecutionContext; @@ -171,7 +172,8 @@ && getArgsPrio(operators.peek()) >= prio) { @Override public int execImpl(String[] args, JShellExecutionContext context) { - NutsCommandLine commandLine = context.getSession().commandLine().create(args) + NutsSession session = context.getSession(); + NutsCommandLine commandLine = NutsCommandLine.of(args,session) .setCommandName("test") .setExpandSimpleOptions(false) ; diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TrueCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TrueCommand.java index 9715f19d0..1b3ace6ca 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TrueCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TrueCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -11,29 +11,30 @@ * architecture to help supporting a large range of sub managers / repositories. * *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class TrueCommand extends SimpleNshBuiltin { public TrueCommand() { diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TypeCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TypeCommand.java index 0cbb3e09c..d33167274 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TypeCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/TypeCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -10,63 +10,43 @@ * to share shell scripts and other 'things' . Its based on an extensible * architecture to help supporting a large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; -import java.util.ArrayList; -import java.util.List; import net.thevpc.nuts.NutsArgument; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShell; -import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellCommandType; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellBuiltin; -import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellCommandType; + +import java.util.ArrayList; +import java.util.List; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class TypeCommand extends SimpleNshBuiltin { public TypeCommand() { super("type", DEFAULT_SUPPORT); } - private static class Options { - - List commands = new ArrayList<>(); - } - - private static class ResultItem { - - String command; - String type; - String message; - - public ResultItem(String command, String type, String message) { - this.command = command; - this.type = type; - this.message = message; - } - - public ResultItem() { - } - - } - @Override protected Object createOptions() { return new Options(); @@ -143,5 +123,27 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } } + private static class Options { + + List commands = new ArrayList<>(); + } + + private static class ResultItem { + + String command; + String type; + String message; + + public ResultItem(String command, String type, String message) { + this.command = command; + this.type = type; + this.message = message; + } + + public ResultItem() { + } + + } + } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnaliasCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnaliasCommand.java index 35b6c41f7..0795e533d 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnaliasCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnaliasCommand.java @@ -1,7 +1,7 @@ /** * ==================================================================== - * Nuts : Network Updatable Things Service - * (universal package manager) + * Nuts : Network Updatable Things Service + * (universal package manager) *
    * is a new Open Source Package Manager to help install packages * and libraries for runtime execution. Nuts is the ultimate companion for @@ -10,45 +10,41 @@ * to share shell scripts and other 'things' . Its based on an extensible * architecture to help supporting a large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; +import net.thevpc.nuts.NutsArgument; +import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; + import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import net.thevpc.nuts.NutsArgument; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; -import net.thevpc.nuts.NutsCommandLine; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class UnaliasCommand extends SimpleNshBuiltin { public UnaliasCommand() { super("unalias", DEFAULT_SUPPORT); } - private static class Options { - - boolean all; - Set list = new HashSet<>(); - } - @Override protected Object createOptions() { return new Options(); @@ -84,4 +80,10 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } } } + + private static class Options { + + boolean all; + Set list = new HashSet<>(); + } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnameCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnameCommand.java index a2660bf03..7a1e7e697 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnameCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnameCommand.java @@ -23,8 +23,12 @@ */ package net.thevpc.nuts.toolbox.nsh.cmds; -import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; +import net.thevpc.nuts.NutsArchFamily; +import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.NutsId; +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import java.util.ArrayList; @@ -33,7 +37,7 @@ /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class UnameCommand extends SimpleNshBuiltin { public UnameCommand() { @@ -119,7 +123,6 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } - private static class Options { boolean farch = false; diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnsetCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnsetCommand.java index f8056a780..99f398a7d 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnsetCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnsetCommand.java @@ -10,45 +10,41 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; +import net.thevpc.nuts.NutsArgument; +import net.thevpc.nuts.NutsCommandLine; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; + import java.util.Arrays; import java.util.HashSet; import java.util.Set; -import net.thevpc.nuts.NutsArgument; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; -import net.thevpc.nuts.NutsCommandLine; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class UnsetCommand extends SimpleNshBuiltin { public UnsetCommand() { super("unset", DEFAULT_SUPPORT); } - private static class Options { - - boolean fct; - Set list = new HashSet<>(); - } - @Override protected Object createOptions() { return new Options(); @@ -86,4 +82,10 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } } } + + private static class Options { + + boolean fct; + Set list = new HashSet<>(); + } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnzipCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnzipCommand.java index a4a7324f8..96b011c8d 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnzipCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/UnzipCommand.java @@ -10,49 +10,41 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; - /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class UnzipCommand extends SimpleNshBuiltin { public UnzipCommand() { super("unzip", DEFAULT_SUPPORT); } - private static class Options { - - boolean l = false; - boolean skipRoot = false; - String dir = null; - List files = new ArrayList<>(); - } - @Override protected Object createOptions() { return new Options(); @@ -88,35 +80,43 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext NutsPath file = NutsPath.of(path, session).toAbsolute(context.getRootContext().getCwd()); try { if (options.l) { - session.io().uncompress() + NutsUncompress.of(session) .from(file) - .visit(new NutsIOUncompressVisitor() { - @Override - public boolean visitFolder(String path) { - return true; - } + .visit(new NutsIOUncompressVisitor() { + @Override + public boolean visitFolder(String path) { + return true; + } - @Override - public boolean visitFile(String path, InputStream inputStream) { - session.out().printf("%s\n", path); - return true; - } - }); + @Override + public boolean visitFile(String path, InputStream inputStream) { + session.out().printf("%s\n", path); + return true; + } + }); } else { String dir = options.dir; if (NutsBlankable.isBlank(dir)) { dir = context.getRootContext().getCwd(); } dir = context.getRootContext().getAbsolutePath(dir); - session.io().uncompress() - .from(file) - .to(dir) - .setSkipRoot(options.skipRoot) - .run(); + NutsUncompress.of(session) + .from(file) + .to(dir) + .setSkipRoot(options.skipRoot) + .run(); } - } catch (UncheckedIOException| NutsIOException ex) { - throw new NutsExecutionException(session, NutsMessage.cstyle("%s",ex), ex, 1); + } catch (UncheckedIOException | NutsIOException ex) { + throw new NutsExecutionException(session, NutsMessage.cstyle("%s", ex), ex, 1); } } } + + private static class Options { + + boolean l = false; + boolean skipRoot = false; + String dir = null; + List files = new ArrayList<>(); + } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/VersionCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/VersionCommand.java index baa218a54..30ac3dbc1 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/VersionCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/VersionCommand.java @@ -43,12 +43,12 @@ public VersionCommand() { @Override public int execImpl(String[] args, JShellExecutionContext context) { - NutsSession ws = context.getSession(); - NutsCommandLine cmdLine = context.getSession().commandLine().create(args); - NutsVersionFormat version = ws.version().formatter(); + NutsSession session = context.getSession(); + NutsCommandLine cmdLine = NutsCommandLine.of(args,session); + NutsVersionFormat version = NutsVersionFormat.of(session); version.configure(true, cmdLine); version - .setSession(context.getSession()) + .setSession(session) .addProperty("nsh-version", context.getAppContext().getAppId().getVersion().getValue()) .println(context.out()); return 0; diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/WgetCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/WgetCommand.java index a7ff81897..b0952a0d5 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/WgetCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/WgetCommand.java @@ -10,7 +10,7 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain a @@ -22,10 +22,15 @@ * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; +import net.thevpc.nuts.toolbox.nsh.bundles._URLUtils; +import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellExecutionContext; import java.net.MalformedURLException; import java.net.URL; @@ -34,27 +39,16 @@ import java.util.ArrayList; import java.util.List; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; -import net.thevpc.nuts.toolbox.nsh.bundles._URLUtils; -import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellExecutionContext; - /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class WgetCommand extends SimpleNshBuiltin { public WgetCommand() { super("wget", DEFAULT_SUPPORT); } - private static class Options { - - String outputDocument = null; - List files = new ArrayList<>(); - } - @Override protected Object createOptions() { return new Options(); @@ -89,20 +83,25 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext protected void download(String path, String output, JShellExecutionContext context) { String output2 = output; URL url; + NutsSession session = context.getSession(); try { url = new URL(path); } catch (MalformedURLException ex) { - throw new NutsExecutionException(context.getSession(), NutsMessage.cstyle("%s",ex), ex, 100); + throw new NutsExecutionException(session, NutsMessage.cstyle("%s", ex), ex, 100); } String urlName = _URLUtils.getURLName(url); if (!NutsBlankable.isBlank(output2)) { output2 = output2.replace("{}", urlName); } Path file = Paths.get(context.getShellContext().getAbsolutePath(NutsBlankable.isBlank(output2) ? urlName : output2)); - context.getSession().io() - .copy() - .setSession(context.getSession()) - .from(path).to(file).setSession(context.getSession()) + NutsCp.of(session) + .from(path).to(file).setSession(session) .setLogProgress(true).run(); } + + private static class Options { + + String outputDocument = null; + List files = new ArrayList<>(); + } } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/WhoamiCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/WhoamiCommand.java index 354712ef1..279264513 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/WhoamiCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/WhoamiCommand.java @@ -10,74 +10,43 @@ * to share shell scripts and other 'things' . Its based on an extensible * architecture to help supporting a large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; -import java.util.ArrayList; - -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; -import java.util.Arrays; -import java.util.List; -import java.util.Set; -import java.util.TreeSet; +import java.util.*; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class WhoamiCommand extends SimpleNshBuiltin { public WhoamiCommand() { super("whoami", DEFAULT_SUPPORT); } - private static class Options { - - boolean argAll = false; - boolean nutsUser = false; - } - - private static class RepoResult { - - private String name; - private String[] identities; - private String[] rights; - private String[] inherited; - private String remoteId; - - } - @Override protected Object createOptions() { return new Options(); } - private static class Result { - - private String login; - private String[] loginStack; - private String[] groups; - private String[] rights; - private String[] inherited; - private String remoteId; - private RepoResult[] repos; - } - @Override protected boolean configureFirst(NutsCommandLine commandLine, SimpleNshCommandContext context) { Options config = context.getOptions(); @@ -177,66 +146,66 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext NutsPrintStream out = context.getSession().out(); out.printf("%s\n", result.login); if (options.nutsUser) { - NutsTextManager factory = context.getSession().text(); + NutsTexts factory = NutsTexts.of(context.getSession()); if (result.loginStack != null) { out.printf("%s :", - factory.ofStyled("stack",NutsTextStyle.primary5()) + factory.ofStyled("stack", NutsTextStyle.primary5()) ); for (String log : result.loginStack) { out.printf(" %s", - factory.ofStyled(log,NutsTextStyle.primary3()) + factory.ofStyled(log, NutsTextStyle.primary3()) ); } out.println(); } if (result.groups != null && result.groups.length > 0) { out.printf("%s : %s\n", - factory.ofStyled("identities",NutsTextStyle.primary5()), + factory.ofStyled("identities", NutsTextStyle.primary5()), Arrays.toString(result.groups)); } if (result.rights != null && result.rights.length > 0) { out.printf("%s : %s\n", - factory.ofStyled("rights",NutsTextStyle.primary5()), + factory.ofStyled("rights", NutsTextStyle.primary5()), Arrays.toString(result.rights)); } if (result.inherited != null && result.inherited.length > 0) { out.printf("%s : %s\n", - factory.ofStyled("inherited",NutsTextStyle.primary5()), + factory.ofStyled("inherited", NutsTextStyle.primary5()), Arrays.toString(result.inherited)); } else { out.printf("%s : %s\n", - factory.ofStyled("inherited",NutsTextStyle.primary5()), + factory.ofStyled("inherited", NutsTextStyle.primary5()), "NONE"); } if (result.remoteId != null) { out.printf("%s : %s\n", - factory.ofStyled("remote-id",NutsTextStyle.primary5()), + factory.ofStyled("remote-id", NutsTextStyle.primary5()), result.remoteId); } if (result.repos != null) { for (RepoResult repo : result.repos) { out.printf( "[ %s ]: \n", - factory.ofStyled(repo.name,NutsTextStyle.primary4()) + factory.ofStyled(repo.name, NutsTextStyle.primary4()) ); if (repo.identities.length > 0) { out.printf(" %s : %s\n", - factory.ofStyled("identities",NutsTextStyle.primary5()), + factory.ofStyled("identities", NutsTextStyle.primary5()), Arrays.toString(repo.identities)); } if (result.rights != null && repo.rights.length > 0) { out.printf(" %s : %s\n", - factory.ofStyled("rights",NutsTextStyle.primary5()), + factory.ofStyled("rights", NutsTextStyle.primary5()), Arrays.toString(repo.rights)); } if (repo.inherited != null && repo.inherited.length > 0) { out.printf(" %s : %s\n", - factory.ofStyled("inherited",NutsTextStyle.primary5()), + factory.ofStyled("inherited", NutsTextStyle.primary5()), Arrays.toString(repo.inherited)); } if (repo.remoteId != null) { out.printf(" %s : %s\n", - factory.ofStyled("remote-id",NutsTextStyle.primary5()), + factory.ofStyled("remote-id", NutsTextStyle.primary5()), repo.remoteId); } } @@ -250,5 +219,32 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } } + private static class Options { + + boolean argAll = false; + boolean nutsUser = false; + } + + private static class RepoResult { + + private String name; + private String[] identities; + private String[] rights; + private String[] inherited; + private String remoteId; + + } + + private static class Result { + + private String login; + private String[] loginStack; + private String[] groups; + private String[] rights; + private String[] inherited; + private String remoteId; + private RepoResult[] repos; + } + } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/XmlCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/XmlCommand.java index fd00ec444..2f47e87a2 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/XmlCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/XmlCommand.java @@ -10,53 +10,49 @@ * other 'things' . Its based on an extensible architecture to help supporting a * large range of sub managers / repositories. *
    - * + *

    * Copyright [2020] [thevpc] - * Licensed under the Apache License, Version 2.0 (the "License"); you may - * not use this file except in compliance with the License. You may obtain a + * Licensed under the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. You may obtain a * copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language * governing permissions and limitations under the License. *
    * ==================================================================== -*/ + */ package net.thevpc.nuts.toolbox.nsh.cmds; -import java.io.*; -import java.util.*; +import net.thevpc.nuts.*; +import net.thevpc.nuts.spi.NutsComponentScope; +import net.thevpc.nuts.spi.NutsComponentScopeType; +import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; +import org.w3c.dom.Document; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; - -import net.thevpc.nuts.*; -import net.thevpc.nuts.spi.NutsSingleton; -import net.thevpc.nuts.toolbox.nsh.SimpleNshBuiltin; -import org.w3c.dom.Document; -import org.w3c.dom.NodeList; -import org.xml.sax.InputSource; +import java.io.*; +import java.util.ArrayList; +import java.util.List; /** * Created by vpc on 1/7/17. */ -@NutsSingleton +@NutsComponentScope(NutsComponentScopeType.WORKSPACE) public class XmlCommand extends SimpleNshBuiltin { public XmlCommand() { super("xml", DEFAULT_SUPPORT); } - private static class Options { - - String input; - List xpaths = new ArrayList<>(); - } - @Override protected Object createOptions() { return new Options(); @@ -96,13 +92,13 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext if (options.input != null) { NutsPath file = NutsPath.of(options.input, session).toAbsolute(context.getRootContext().getCwd()); if (file.isFile()) { - try (InputStream is=file.getInputStream()){ + try (InputStream is = file.getInputStream()) { doc = dBuilder.parse(is); } catch (Exception ex) { throw new NutsExecutionException(session, NutsMessage.cstyle("invalid xml %s", options.input), ex, 2); } } else { - throw new NutsExecutionException(session, NutsMessage.cstyle("invalid path %s",options.input), 1); + throw new NutsExecutionException(session, NutsMessage.cstyle("invalid path %s", options.input), 1); } } else { StringBuilder sb = new StringBuilder(); @@ -118,7 +114,7 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext try { doc = dBuilder.parse(new InputSource(new StringReader(sb.toString()))); } catch (Exception ex) { - throw new NutsExecutionException(session, NutsMessage.cstyle("invalid xml : %s",sb), ex, 2); + throw new NutsExecutionException(session, NutsMessage.cstyle("invalid xml : %s", sb), ex, 2); } break; } else { @@ -144,7 +140,7 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext try { result.add((NodeList) xPath.compile(query).evaluate(doc, XPathConstants.NODESET)); } catch (XPathExpressionException ex) { - throw new NutsExecutionException(session, NutsMessage.cstyle("%s",ex), ex, 103); + throw new NutsExecutionException(session, NutsMessage.cstyle("%s", ex), ex, 103); } } if (all.size() == 1) { @@ -154,4 +150,10 @@ protected void execBuiltin(NutsCommandLine commandLine, SimpleNshCommandContext } } + private static class Options { + + String input; + List xpaths = new ArrayList<>(); + } + } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ZipCommand.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ZipCommand.java index 7c73ceafc..00447ba9c 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ZipCommand.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/cmds/ZipCommand.java @@ -50,14 +50,13 @@ public int execImpl(String[] args, JShellExecutionContext context) { NutsPath outZip = null; NutsArgument a; NutsSession session = context.getSession(); - NutsCommandLineManager nutsCommandLineFormat = session.commandLine(); while (commandLine.hasNext()) { if (commandLine.next("-r") != null) { options.r = true; } else if (commandLine.peek().isOption()) { commandLine.unexpectedArgument(); } else if (commandLine.peek().isNonOption()) { - String path = commandLine.required().nextNonOption(nutsCommandLineFormat.createName("file")).getString(); + String path = commandLine.required().nextNonOption(NutsArgumentName.of("file",session)).getString(); NutsPath file = NutsPath.of(path, session).toAbsolute(context.getShellContext().getCwd()); if (outZip == null) { outZip = file; @@ -74,7 +73,7 @@ public int execImpl(String[] args, JShellExecutionContext context) { if (outZip == null) { commandLine.required(NutsMessage.cstyle("missing out-zip")); } - NutsIOCompressAction aa = session.io().compress() + NutsCompress aa = NutsCompress.of(session) .setTarget(outZip); for (NutsPath file : files) { aa.addSource(file); diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/options/CommandNonOption.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/options/CommandNonOption.java index 96bbef769..3fe70eb4f 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/options/CommandNonOption.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/options/CommandNonOption.java @@ -31,7 +31,7 @@ import net.thevpc.nuts.NutsArgumentCandidate; import net.thevpc.nuts.NutsArgumentName; import net.thevpc.nuts.NutsCommandAutoComplete; -import net.thevpc.nuts.NutsCommandLineManager; +import net.thevpc.nuts.NutsCommandLines; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellBuiltin; import net.thevpc.nuts.toolbox.nsh.bundles.jshell.JShellContext; @@ -57,9 +57,8 @@ public String getName() { @Override public List getCandidates(NutsCommandAutoComplete context) { List all = new ArrayList<>(); - NutsCommandLineManager c = this.context.getSession().commandLine(); for (JShellBuiltin command : this.context.builtins().getAll()) { - all.add(c.createCandidate(command.getName()).build()); + all.add(new NutsArgumentCandidate(command.getName())); } return all; } diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/ColumnRuler.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/ColumnRuler.java new file mode 100644 index 000000000..a98dbfaf4 --- /dev/null +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/ColumnRuler.java @@ -0,0 +1,31 @@ +package net.thevpc.nuts.toolbox.nsh.util; + +import net.thevpc.nuts.NutsSession; +import net.thevpc.nuts.NutsString; +import net.thevpc.nuts.NutsTextStyle; +import net.thevpc.nuts.NutsTexts; +import net.thevpc.nuts.toolbox.nsh.bundles._StringUtils; + +public class ColumnRuler { + private int width; + + public ColumnRuler() { + this(6); + } + public ColumnRuler(int width) { + this.width = width; + } + + public String next(String ruleText){ + if (width <= ruleText.length()) { + width = ruleText.length() + 1; + } + return _StringUtils.formatRight(ruleText, width)+" "; + } + + public NutsString nextNum(long nbr, NutsSession session){ + return NutsTexts.of(session).ofStyled(next(String.valueOf(nbr)), + NutsTextStyle.number() + ); + } +} diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/RowFilter.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/RowFilter.java new file mode 100644 index 000000000..d73fbd5e2 --- /dev/null +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/RowFilter.java @@ -0,0 +1,35 @@ +package net.thevpc.nuts.toolbox.nsh.util; + +import net.thevpc.nuts.NutsExpr; + +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.function.LongPredicate; + +public class RowFilter { + NutsExpr.Node expr; + +// boolean acceptRow(long i,long max){ +// +// } +// +// public boolean isUseMax(NutsExpr.Node n){ +// if(n==null){ +// return false; +// } +// switch (n.getType()){ +// case POSTFIX_OPERATOR:{ +// NutsExpr.Node[] c = n.getChildren(); +// if(c.length==2){ +// if(c[0].getType()== NutsExpr.NodeType.VARIABLE && c[0].getName().equals("_")){ +// +// } +// } +// } +// } +// } + + +} diff --git a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/ShellHelper.java b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/ShellHelper.java index fca1f5d48..718061fb1 100644 --- a/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/ShellHelper.java +++ b/toolbox/nsh/src/main/java/net/thevpc/nuts/toolbox/nsh/util/ShellHelper.java @@ -21,11 +21,10 @@ public static List xfilesOf(List all, String cwd, NutsSession } public static NutsPath xfileOf(String expression, String cwd, NutsSession session) { - NutsIOManager io = session.io(); if (expression.startsWith("file:") || expression.contains("://")) { - return io.path(expression); + return NutsPath.of(expression,session); } - return io.path(_IOUtils.getAbsoluteFile2(expression, cwd)); + return NutsPath.of(_IOUtils.getAbsoluteFile2(expression, cwd),session); } public static String[] splitNameAndValue(String arg) { @@ -87,7 +86,7 @@ public void onPut(String from, String to, boolean mkdir) { @Override public InputStream monitorInputStream(InputStream stream, long length, NutsString message) { - return session.io().monitor().setSource(stream).setLength(length).setName(message).create(); + return NutsInputStreamMonitor.of(session).setSource(stream).setLength(length).setName(message).create(); } } diff --git a/toolbox/nsh/src/main/resources/net/thevpc/nuts/toolbox/nsh/cmd/grep.ntf b/toolbox/nsh/src/main/resources/net/thevpc/nuts/toolbox/nsh/cmd/grep.ntf index b0eb5111c..ca67d29dc 100644 --- a/toolbox/nsh/src/main/resources/net/thevpc/nuts/toolbox/nsh/cmd/grep.ntf +++ b/toolbox/nsh/src/main/resources/net/thevpc/nuts/toolbox/nsh/cmd/grep.ntf @@ -5,9 +5,21 @@ print lines matching a pattern print lines matching a pattern +##) OPTIONS: + +```sh --highlighter []``` + +```sh --selection-style [